title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
MATLAB - Loops - GeeksforGeeks
13 May, 2021 MATLAB stands for Matrix Laboratory. It is a high-performance language that is used for technical computing. It was developed by Cleve Molar of the company MathWorks.Inc in the year 1984.It is written in C, C++, Java. It allows matrix manipulations, plotting of functions, implementation of algorithms and creation of user interfaces. While Loop: While loop works same as it does in other common languages like python, java etc. But here syntax varies from language to language. While loop is used to execute a block of statements repeatedly until a given a condition is satisfied. And when the condition becomes false, the line immediately after the loop in program is executed. Syntax: while expression statements end Example 1: Matlab %MATLAB code to illustrate %for loop count=0; while (count < 3) fprintf('Hello From GeekforGeeks\n'); count=count+1; end Output: Hello From GeekforGeeks Hello From GeekforGeeks Hello From GeekforGeeks For Loop: For loops are used for sequential traversal. As syntax varies from language to language. Let us learn how to use for loop for sequential traversals. Syntax: for initial value:step value:final value statements end or for initial value:final value statements end Example 2 Matlab %MATLAB code to illustrate %for loop for i = 1:5 fprintf('%d ',i) end Output: 1 2 3 4 5 Example 3 Matlab %MATLAB code to illustrate %for loop for i = 1:2:5 fprintf('%d ',i) end Output: 1 3 5 We have one more way of using for loop, that is used to access array elements. Here we assign an array directly to the for loop to access its elements through the iterator variable (i.e., i or j etc). Example 4 Matlab %for iterator_vairable = array for i =[1 2 3 4] fprintf('%d ',i) end Output: 1 2 3 4 Iterating through strings is same as iterating through a range of numbers. Here we use length() function to provide final value in for loop, and we can also use disp() function to print the output. Example 5 Matlab %MATLAB code to illustrate %how to iterate through strings String = 'GeeksforGeeks' for i = 1:length(String) fprintf('%c ',String(i)) %disp(String(i)) end Output: G e e k s f o r G e e k s simranarora5sos MATLAB Advanced Computer Subject Programming Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments ML | Stochastic Gradient Descent (SGD) Copying Files to and from Docker Containers Principal Component Analysis with Python ML | Principal Component Analysis(PCA) ML | Types of Learning – Supervised Learning Modulo Operator (%) in C/C++ with Examples Differences between Procedural and Object Oriented Programming Structures in C++ Arrow operator -> in C/C++ with Examples Top 10 Programming Languages to Learn in 2022
[ { "code": null, "e": 23863, "s": 23835, "text": "\n13 May, 2021" }, { "code": null, "e": 24198, "s": 23863, "text": "MATLAB stands for Matrix Laboratory. It is a high-performance language that is used for technical computing. It was developed by Cleve Molar of the company MathWorks.Inc in the year 1984.It is written in C, C++, Java. It allows matrix manipulations, plotting of functions, implementation of algorithms and creation of user interfaces." }, { "code": null, "e": 24543, "s": 24198, "text": "While Loop: While loop works same as it does in other common languages like python, java etc. But here syntax varies from language to language. While loop is used to execute a block of statements repeatedly until a given a condition is satisfied. And when the condition becomes false, the line immediately after the loop in program is executed." }, { "code": null, "e": 24551, "s": 24543, "text": "Syntax:" }, { "code": null, "e": 24587, "s": 24551, "text": "while expression\n statements\nend" }, { "code": null, "e": 24598, "s": 24587, "text": "Example 1:" }, { "code": null, "e": 24605, "s": 24598, "text": "Matlab" }, { "code": "%MATLAB code to illustrate %for loop count=0; while (count < 3) fprintf('Hello From GeekforGeeks\\n'); count=count+1; end", "e": 24735, "s": 24605, "text": null }, { "code": null, "e": 24745, "s": 24735, "text": " Output:" }, { "code": null, "e": 24817, "s": 24745, "text": "Hello From GeekforGeeks\nHello From GeekforGeeks\nHello From GeekforGeeks" }, { "code": null, "e": 24976, "s": 24817, "text": "For Loop: For loops are used for sequential traversal. As syntax varies from language to language. Let us learn how to use for loop for sequential traversals." }, { "code": null, "e": 24984, "s": 24976, "text": "Syntax:" }, { "code": null, "e": 25043, "s": 24984, "text": "for initial value:step value:final value\n statements\nend" }, { "code": null, "e": 25046, "s": 25043, "text": "or" }, { "code": null, "e": 25099, "s": 25046, "text": "for initial value:final value \n statements \nend " }, { "code": null, "e": 25109, "s": 25099, "text": "Example 2" }, { "code": null, "e": 25116, "s": 25109, "text": "Matlab" }, { "code": "%MATLAB code to illustrate %for loop for i = 1:5 fprintf('%d ',i) end", "e": 25189, "s": 25116, "text": null }, { "code": null, "e": 25197, "s": 25189, "text": "Output:" }, { "code": null, "e": 25207, "s": 25197, "text": "1 2 3 4 5" }, { "code": null, "e": 25217, "s": 25207, "text": "Example 3" }, { "code": null, "e": 25224, "s": 25217, "text": "Matlab" }, { "code": "%MATLAB code to illustrate %for loop for i = 1:2:5 fprintf('%d ',i) end", "e": 25299, "s": 25224, "text": null }, { "code": null, "e": 25308, "s": 25299, "text": "Output: " }, { "code": null, "e": 25314, "s": 25308, "text": "1 3 5" }, { "code": null, "e": 25515, "s": 25314, "text": "We have one more way of using for loop, that is used to access array elements. Here we assign an array directly to the for loop to access its elements through the iterator variable (i.e., i or j etc)." }, { "code": null, "e": 25526, "s": 25515, "text": "Example 4 " }, { "code": null, "e": 25533, "s": 25526, "text": "Matlab" }, { "code": "%for iterator_vairable = array for i =[1 2 3 4] fprintf('%d ',i) end", "e": 25605, "s": 25533, "text": null }, { "code": null, "e": 25614, "s": 25605, "text": "Output: " }, { "code": null, "e": 25622, "s": 25614, "text": "1 2 3 4" }, { "code": null, "e": 25820, "s": 25622, "text": "Iterating through strings is same as iterating through a range of numbers. Here we use length() function to provide final value in for loop, and we can also use disp() function to print the output." }, { "code": null, "e": 25831, "s": 25820, "text": "Example 5 " }, { "code": null, "e": 25838, "s": 25831, "text": "Matlab" }, { "code": "%MATLAB code to illustrate %how to iterate through strings String = 'GeeksforGeeks' for i = 1:length(String) fprintf('%c ',String(i)) %disp(String(i)) end", "e": 25999, "s": 25838, "text": null }, { "code": null, "e": 26008, "s": 25999, "text": "Output: " }, { "code": null, "e": 26034, "s": 26008, "text": "G e e k s f o r G e e k s" }, { "code": null, "e": 26052, "s": 26036, "text": "simranarora5sos" }, { "code": null, "e": 26059, "s": 26052, "text": "MATLAB" }, { "code": null, "e": 26085, "s": 26059, "text": "Advanced Computer Subject" }, { "code": null, "e": 26106, "s": 26085, "text": "Programming Language" }, { "code": null, "e": 26204, "s": 26106, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26213, "s": 26204, "text": "Comments" }, { "code": null, "e": 26226, "s": 26213, "text": "Old Comments" }, { "code": null, "e": 26265, "s": 26226, "text": "ML | Stochastic Gradient Descent (SGD)" }, { "code": null, "e": 26309, "s": 26265, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 26350, "s": 26309, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 26389, "s": 26350, "text": "ML | Principal Component Analysis(PCA)" }, { "code": null, "e": 26434, "s": 26389, "text": "ML | Types of Learning – Supervised Learning" }, { "code": null, "e": 26477, "s": 26434, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 26540, "s": 26477, "text": "Differences between Procedural and Object Oriented Programming" }, { "code": null, "e": 26558, "s": 26540, "text": "Structures in C++" }, { "code": null, "e": 26599, "s": 26558, "text": "Arrow operator -> in C/C++ with Examples" } ]
How to open a binary file in read and write mode with Python?
To open binary files in binary read/write mode, specify 'w+b' as the mode(w=write, b=binary). For example, f = open('my_file.mp3', 'w+b') file_content = f.read() f.write(b'Hello') f.close() Above code opens my_file.mp3 in binary read/write mode, stores the file content in file_content variable and rewrites the file to contain "Hello" in binary. You can also use r+mode as it doesn't truncate the file.
[ { "code": null, "e": 1169, "s": 1062, "text": "To open binary files in binary read/write mode, specify 'w+b' as the mode(w=write, b=binary). For example," }, { "code": null, "e": 1252, "s": 1169, "text": "f = open('my_file.mp3', 'w+b')\nfile_content = f.read()\nf.write(b'Hello')\nf.close()" }, { "code": null, "e": 1467, "s": 1252, "text": "Above code opens my_file.mp3 in binary read/write mode, stores the file content in file_content variable and rewrites the file to contain \"Hello\" in binary. You can also use r+mode as it doesn't truncate the file. " } ]
Managing Python Environments Like a Pro | by Pratik Choudhari | Towards Data Science
Python virtual environments help us manage dependencies easily and effortlessly. The most common environment creation tools are virtualenv and conda, the latter is used for environment management for multiple languages whereas the former is made especially for python. Why not use global python packages, then we won’t need to get into this environment mess, right? Well, yes, it will save us time managing environments but at what cost, the pain of having a setup ready to go for a project will grow exponentially. I learned this fact the hard way, using global packages for everything and not having a dedicated environment for every project. In this blog, I will be writing about virtualenvwrapper , a python library to manage and customize environments in python which runs on top of the good old virtualenv. As we progress, we will see how the VEW CLI commands are similar to Linux commands like mkdir, rmdir and cp. Note: I will be referring to virtualenvwrapper as VEW throughout this article It is important to note that pyenv is not related to virtualenv or VEW. pyenv is used to switch between multiple python versions and does not manage packages installed. Also, pip is a package manager in python and pip too can not help us in managing environment because it was not made to do this. For more information read this stackoverflow thread. stackoverflow.com The installation process is the same as any other library. pip install virtualenvwrapper In a Linux system, after installation, we need to edit the .bashrc file, this will allow the user to access VEW in any terminal and location. export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3export WORKON_HOME=~/my_env_folderexport VIRTUALENVWRAPPER_VIRTUALENV=/home/my_user/.local/bin/virtualenvsource ~/.local/bin/virtualenvwrapper.sh In the first line, we set the VIRTUALENVWRAPPER_PYTHON variable which points to the python binary installation VEW must refer toNext, WORKON_HOME is the folder where VEW will store all environments and utility scriptsVIRTUALENVWRAPPER_VIRTUALENV is the path to the original virtualenv binary In the first line, we set the VIRTUALENVWRAPPER_PYTHON variable which points to the python binary installation VEW must refer to Next, WORKON_HOME is the folder where VEW will store all environments and utility scripts VIRTUALENVWRAPPER_VIRTUALENV is the path to the original virtualenv binary As I said earlier, the commands here are similar to Linux commands. To create a new environment execute the following line. mkvirtualenv my-env This environment will be stored in the path specified in WORKON_HOME variable. Three options are supported alongside virtualenv option, which are: -a my_path: folder for the environment, it means that whenever the environment will be activated, no matter in what path users are in currently, they will be redirected to my_path. It does not mean the environment will be created inside my_path.-i package1 package2 ...: try installing mentioned packages after the environment is created.-r requirements.txt: Create an environment and install from the requirements.txt file. -a my_path: folder for the environment, it means that whenever the environment will be activated, no matter in what path users are in currently, they will be redirected to my_path. It does not mean the environment will be created inside my_path. -i package1 package2 ...: try installing mentioned packages after the environment is created. -r requirements.txt: Create an environment and install from the requirements.txt file. rmvirtualenv my_env Deletes environment folder. Remember to deactivate the environment before deleting it. showvirtualenv my-env lsvirtualenv List all virtual environments created via this tool. Use -b option to just list environments and ignore the details. virtualenv uses the following command to activate an environment. source my-env/bin/activate source is a commonly used Linux command which is primarily used for changing the environment variables with the current shell. Read more about it here. VEW abstracts this source command and provides an easy-to-remember alternative called workon . workon my-env Under the hood, VEW executes the source command. Deactivating an environment in VEW is the same as virtualenv. In an active environment shell, execute the following. deactivate wipeenv This command is to be run inside an active environment. When this is executed VEW will identify all third-party libraries and uninstall them. Although virtualenv works just fine to manage all our environments, virtualenvwrapper is a recommended add-on. Its resemblance to Linux commands makes the operations easier to remember. Follow for more such articles. Thanks for reading till the end :)
[ { "code": null, "e": 441, "s": 172, "text": "Python virtual environments help us manage dependencies easily and effortlessly. The most common environment creation tools are virtualenv and conda, the latter is used for environment management for multiple languages whereas the former is made especially for python." }, { "code": null, "e": 817, "s": 441, "text": "Why not use global python packages, then we won’t need to get into this environment mess, right? Well, yes, it will save us time managing environments but at what cost, the pain of having a setup ready to go for a project will grow exponentially. I learned this fact the hard way, using global packages for everything and not having a dedicated environment for every project." }, { "code": null, "e": 1094, "s": 817, "text": "In this blog, I will be writing about virtualenvwrapper , a python library to manage and customize environments in python which runs on top of the good old virtualenv. As we progress, we will see how the VEW CLI commands are similar to Linux commands like mkdir, rmdir and cp." }, { "code": null, "e": 1172, "s": 1094, "text": "Note: I will be referring to virtualenvwrapper as VEW throughout this article" }, { "code": null, "e": 1523, "s": 1172, "text": "It is important to note that pyenv is not related to virtualenv or VEW. pyenv is used to switch between multiple python versions and does not manage packages installed. Also, pip is a package manager in python and pip too can not help us in managing environment because it was not made to do this. For more information read this stackoverflow thread." }, { "code": null, "e": 1541, "s": 1523, "text": "stackoverflow.com" }, { "code": null, "e": 1600, "s": 1541, "text": "The installation process is the same as any other library." }, { "code": null, "e": 1630, "s": 1600, "text": "pip install virtualenvwrapper" }, { "code": null, "e": 1772, "s": 1630, "text": "In a Linux system, after installation, we need to edit the .bashrc file, this will allow the user to access VEW in any terminal and location." }, { "code": null, "e": 1966, "s": 1772, "text": "export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3export WORKON_HOME=~/my_env_folderexport VIRTUALENVWRAPPER_VIRTUALENV=/home/my_user/.local/bin/virtualenvsource ~/.local/bin/virtualenvwrapper.sh" }, { "code": null, "e": 2258, "s": 1966, "text": "In the first line, we set the VIRTUALENVWRAPPER_PYTHON variable which points to the python binary installation VEW must refer toNext, WORKON_HOME is the folder where VEW will store all environments and utility scriptsVIRTUALENVWRAPPER_VIRTUALENV is the path to the original virtualenv binary" }, { "code": null, "e": 2387, "s": 2258, "text": "In the first line, we set the VIRTUALENVWRAPPER_PYTHON variable which points to the python binary installation VEW must refer to" }, { "code": null, "e": 2477, "s": 2387, "text": "Next, WORKON_HOME is the folder where VEW will store all environments and utility scripts" }, { "code": null, "e": 2552, "s": 2477, "text": "VIRTUALENVWRAPPER_VIRTUALENV is the path to the original virtualenv binary" }, { "code": null, "e": 2676, "s": 2552, "text": "As I said earlier, the commands here are similar to Linux commands. To create a new environment execute the following line." }, { "code": null, "e": 2696, "s": 2676, "text": "mkvirtualenv my-env" }, { "code": null, "e": 2843, "s": 2696, "text": "This environment will be stored in the path specified in WORKON_HOME variable. Three options are supported alongside virtualenv option, which are:" }, { "code": null, "e": 3268, "s": 2843, "text": "-a my_path: folder for the environment, it means that whenever the environment will be activated, no matter in what path users are in currently, they will be redirected to my_path. It does not mean the environment will be created inside my_path.-i package1 package2 ...: try installing mentioned packages after the environment is created.-r requirements.txt: Create an environment and install from the requirements.txt file." }, { "code": null, "e": 3514, "s": 3268, "text": "-a my_path: folder for the environment, it means that whenever the environment will be activated, no matter in what path users are in currently, they will be redirected to my_path. It does not mean the environment will be created inside my_path." }, { "code": null, "e": 3608, "s": 3514, "text": "-i package1 package2 ...: try installing mentioned packages after the environment is created." }, { "code": null, "e": 3695, "s": 3608, "text": "-r requirements.txt: Create an environment and install from the requirements.txt file." }, { "code": null, "e": 3715, "s": 3695, "text": "rmvirtualenv my_env" }, { "code": null, "e": 3802, "s": 3715, "text": "Deletes environment folder. Remember to deactivate the environment before deleting it." }, { "code": null, "e": 3824, "s": 3802, "text": "showvirtualenv my-env" }, { "code": null, "e": 3837, "s": 3824, "text": "lsvirtualenv" }, { "code": null, "e": 3954, "s": 3837, "text": "List all virtual environments created via this tool. Use -b option to just list environments and ignore the details." }, { "code": null, "e": 4020, "s": 3954, "text": "virtualenv uses the following command to activate an environment." }, { "code": null, "e": 4047, "s": 4020, "text": "source my-env/bin/activate" }, { "code": null, "e": 4294, "s": 4047, "text": "source is a commonly used Linux command which is primarily used for changing the environment variables with the current shell. Read more about it here. VEW abstracts this source command and provides an easy-to-remember alternative called workon ." }, { "code": null, "e": 4308, "s": 4294, "text": "workon my-env" }, { "code": null, "e": 4357, "s": 4308, "text": "Under the hood, VEW executes the source command." }, { "code": null, "e": 4474, "s": 4357, "text": "Deactivating an environment in VEW is the same as virtualenv. In an active environment shell, execute the following." }, { "code": null, "e": 4485, "s": 4474, "text": "deactivate" }, { "code": null, "e": 4493, "s": 4485, "text": "wipeenv" }, { "code": null, "e": 4635, "s": 4493, "text": "This command is to be run inside an active environment. When this is executed VEW will identify all third-party libraries and uninstall them." } ]
Arrow operator in ES6 of JavaScript - GeeksforGeeks
30 Oct, 2018 ES6 has come with various advantages and one of them is arrow operator. It has reduced the function defining code size so it is one of the trending questions asked in the interview. Let us have a deeper dive in the arrow operator functioning.Syntax:In ES5 a function is defined by the following syntax: function functionName(arg1, arg2....) { // body of function } But in ES6 a function is defined using arrow operator and whose syntax is like this: const functionName = (arg1, arg2 ....) => { // body of function } Advantages of Arrow Operator:1) Reduces Code Size:As we have replaced the function by corresponding arrow operator so the size of the code is reduced and we have to write less amount of code for same work. That’s why I love the arrow operator method of defining functions.2) Drop the Function braces for one line Functions:We can drop the braces of the function in arrow operator declaration for example:Code #1: <script> //ES5 VERSION var setSize = (sz)=> size=sz; //sets size value to the passed value setSize(10); document.write(size); </script> Output: 10 This can also be written as:Code #2: <script> //ES6 Version //Do not need to put curly braces for one line functions setDoubleSize = (sz)=>size=2*sz; //Sets value of size equivalent to double of //passed argument in setDoubleSize function setDoubleSize(35); document.write(size); </script> Output: 70 3) No need to define return statement in one line Functions:In ES5 you have to define the return statement in the functions and if in ES6 we do not define the return statement then ES6 automatically returns the value whenever given function is called.This will be clear by the following example :ES5 version of one bit left shifting function is as follows : function leftShift(value){ return value / 2;} While in ES6 following function can be written as follows: var leftShift = (value) => value / 2; Code #3: <script> //ES5 VERSION function leftShiftES5(value){ return value/2; } //ES6 VERSION var leftShiftES6 = (value)=>value/2; var a=10,b=10; document.write('values before left shift'+"<br>"); document.write('a : '+a+' b : '+b + "<br>"); //Both of the function should give same output a=leftShiftES5(a); b=leftShiftES6(b); document.write('values after left shift' +"<br>"); document.write('a : '+a+' b : '+b + "<br>"); </script> Output: values before left shift a : 10 b : 10 values after left shift a : 5 b : 5 4) Lexically bind the context :Arrow operator lexically binds the context so this refers to the originating context. It means that it uses this from the arrow functions.L et us consider a class having an array of age and if age<18 we will push them into the child queue. In ES5 you have to do this as follows : this.age.forEach(function(age) { if (age < 18) this.child.push(age);}.bind(this)); In ES6 this can be done as follows : this.age.forEach((age) => { if (age < 18) this.child.push(age);}); So we do not have to bind it implicitly and this is done automatically by arrow functions.So we have seen arrow function makes the function writing less complex and reduces the number of lines so it is being used by questions the developer and also it is one of the most trending questions asked during interviews. Aaditya Kulkarni javascript-operators JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments 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 ? Set the value of an input field in JavaScript Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24332, "s": 24304, "text": "\n30 Oct, 2018" }, { "code": null, "e": 24635, "s": 24332, "text": "ES6 has come with various advantages and one of them is arrow operator. It has reduced the function defining code size so it is one of the trending questions asked in the interview. Let us have a deeper dive in the arrow operator functioning.Syntax:In ES5 a function is defined by the following syntax:" }, { "code": null, "e": 24702, "s": 24635, "text": "function functionName(arg1, arg2....)\n{\n // body of function\n}\n" }, { "code": null, "e": 24787, "s": 24702, "text": "But in ES6 a function is defined using arrow operator and whose syntax is like this:" }, { "code": null, "e": 24858, "s": 24787, "text": "const functionName = (arg1, arg2 ....) => {\n // body of function\n}\n" }, { "code": null, "e": 25271, "s": 24858, "text": "Advantages of Arrow Operator:1) Reduces Code Size:As we have replaced the function by corresponding arrow operator so the size of the code is reduced and we have to write less amount of code for same work. That’s why I love the arrow operator method of defining functions.2) Drop the Function braces for one line Functions:We can drop the braces of the function in arrow operator declaration for example:Code #1:" }, { "code": "<script> //ES5 VERSION var setSize = (sz)=> size=sz; //sets size value to the passed value setSize(10); document.write(size); </script>", "e": 25447, "s": 25271, "text": null }, { "code": null, "e": 25455, "s": 25447, "text": "Output:" }, { "code": null, "e": 25458, "s": 25455, "text": "10" }, { "code": null, "e": 25495, "s": 25458, "text": "This can also be written as:Code #2:" }, { "code": "<script> //ES6 Version //Do not need to put curly braces for one line functions setDoubleSize = (sz)=>size=2*sz; //Sets value of size equivalent to double of //passed argument in setDoubleSize function setDoubleSize(35); document.write(size); </script>", "e": 25787, "s": 25495, "text": null }, { "code": null, "e": 25795, "s": 25787, "text": "Output:" }, { "code": null, "e": 25798, "s": 25795, "text": "70" }, { "code": null, "e": 26156, "s": 25798, "text": "3) No need to define return statement in one line Functions:In ES5 you have to define the return statement in the functions and if in ES6 we do not define the return statement then ES6 automatically returns the value whenever given function is called.This will be clear by the following example :ES5 version of one bit left shifting function is as follows :" }, { "code": "function leftShift(value){ return value / 2;}", "e": 26205, "s": 26156, "text": null }, { "code": null, "e": 26264, "s": 26205, "text": "While in ES6 following function can be written as follows:" }, { "code": "var leftShift = (value) => value / 2;", "e": 26302, "s": 26264, "text": null }, { "code": null, "e": 26311, "s": 26302, "text": "Code #3:" }, { "code": "<script> //ES5 VERSION function leftShiftES5(value){ return value/2; } //ES6 VERSION var leftShiftES6 = (value)=>value/2; var a=10,b=10; document.write('values before left shift'+\"<br>\"); document.write('a : '+a+' b : '+b + \"<br>\"); //Both of the function should give same output a=leftShiftES5(a); b=leftShiftES6(b); document.write('values after left shift' +\"<br>\"); document.write('a : '+a+' b : '+b + \"<br>\"); </script>", "e": 26793, "s": 26311, "text": null }, { "code": null, "e": 26801, "s": 26793, "text": "Output:" }, { "code": null, "e": 26877, "s": 26801, "text": "values before left shift\na : 10 b : 10\nvalues after left shift\na : 5 b : 5\n" }, { "code": null, "e": 27188, "s": 26877, "text": "4) Lexically bind the context :Arrow operator lexically binds the context so this refers to the originating context. It means that it uses this from the arrow functions.L et us consider a class having an array of age and if age<18 we will push them into the child queue. In ES5 you have to do this as follows :" }, { "code": "this.age.forEach(function(age) { if (age < 18) this.child.push(age);}.bind(this));", "e": 27281, "s": 27188, "text": null }, { "code": null, "e": 27318, "s": 27281, "text": "In ES6 this can be done as follows :" }, { "code": "this.age.forEach((age) => { if (age < 18) this.child.push(age);});", "e": 27395, "s": 27318, "text": null }, { "code": null, "e": 27710, "s": 27395, "text": "So we do not have to bind it implicitly and this is done automatically by arrow functions.So we have seen arrow function makes the function writing less complex and reduces the number of lines so it is being used by questions the developer and also it is one of the most trending questions asked during interviews." }, { "code": null, "e": 27727, "s": 27710, "text": "Aaditya Kulkarni" }, { "code": null, "e": 27748, "s": 27727, "text": "javascript-operators" }, { "code": null, "e": 27759, "s": 27748, "text": "JavaScript" }, { "code": null, "e": 27776, "s": 27759, "text": "Web Technologies" }, { "code": null, "e": 27874, "s": 27776, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27883, "s": 27874, "text": "Comments" }, { "code": null, "e": 27896, "s": 27883, "text": "Old Comments" }, { "code": null, "e": 27941, "s": 27896, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28002, "s": 27941, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28074, "s": 28002, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28120, "s": 28074, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 28166, "s": 28120, "text": "Set the value of an input field in JavaScript" }, { "code": null, "e": 28208, "s": 28166, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28241, "s": 28208, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28303, "s": 28241, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28346, "s": 28303, "text": "How to fetch data from an API in ReactJS ?" } ]
ASP.NET - Custom Controls
ASP.NET allows the users to create controls. These user defined controls are categorized into: User controls Custom controls User controls behaves like miniature ASP.NET pages or web forms, which could be used by many other pages. These are derived from the System.Web.UI.UserControl class. These controls have the following characteristics: They have an .ascx extension. They may not contain any <html>, <body>, or <form> tags. They have a Control directive instead of a Page directive. To understand the concept, let us create a simple user control, which will work as footer for the web pages. To create and use the user control, take the following steps: Create a new web application. Right click on the project folder on the Solution Explorer and choose Add New Item. Select Web User Control from the Add New Item dialog box and name it footer.ascx. Initially, the footer.ascx contains only a Control directive. <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="footer.ascx.cs" Inherits="customcontroldemo.footer" %> Select Web User Control from the Add New Item dialog box and name it footer.ascx. Initially, the footer.ascx contains only a Control directive. <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="footer.ascx.cs" Inherits="customcontroldemo.footer" %> Add the following code to the file: <table> <tr> <td align="center"> Copyright ©2010 TutorialPoints Ltd.</td> </tr> <tr> <td align="center"> Location: Hyderabad, A.P </td> </tr> </table> Add the following code to the file: <table> <tr> <td align="center"> Copyright ©2010 TutorialPoints Ltd.</td> </tr> <tr> <td align="center"> Location: Hyderabad, A.P </td> </tr> </table> To add the user control to your web page, you must add the Register directive and an instance of the user control to the page. The following code shows the content file: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="customcontroldemo._Default" %> <%@ Register Src="~/footer.ascx" TagName="footer" TagPrefix="Tfooter" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title> Untitled Page </title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="Label1" runat="server" Text="Welcome to ASP.Net Tutorials "></asp:Label> <br /> <br /> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Copyright Info" /> </div> <Tfooter:footer ID="footer1" runat="server" /> </form> </body> </html> When executed, the page shows the footer and this control could be used in all the pages of your website. Observe the following: (1) The Register directive specifies a tag name as well as tag prefix for the control. <%@ Register Src="~/footer.ascx" TagName="footer" TagPrefix="Tfooter" %> (2) The following tag name and prefix should be used while adding the user control on the page: <Tfooter:footer ID="footer1" runat="server" /> Custom controls are deployed as individual assemblies. They are compiled into a Dynamic Link Library (DLL) and used as any other ASP.NET server control. They could be created in either of the following way: By deriving a custom control from an existing control By composing a new custom control combing two or more existing controls. By deriving from the base control class. To understand the concept, let us create a custom control, which will simply render a text message on the browser. To create this control, take the following steps: Create a new website. Right click the solution (not the project) at the top of the tree in the Solution Explorer. In the New Project dialog box, select ASP.NET Server Control from the project templates. The above step adds a new project and creates a complete custom control to the solution, called ServerControl1. In this example, let us name the project CustomControls. To use this control, this must be added as a reference to the web site before registering it on a page. To add a reference to the existing project, right click on the project (not the solution), and click Add Reference. Select the CustomControls project from the Projects tab of the Add Reference dialog box. The Solution Explorer should show the reference. To use the control on a page, add the Register directive just below the @Page directive: <%@ Register Assembly="CustomControls" Namespace="CustomControls" TagPrefix="ccs" %> Further, you can use the control, similar to any other controls. <form id="form1" runat="server"> <div> <ccs:ServerControl1 runat="server" Text = "I am a Custom Server Control" /> </div> </form> When executed, the Text property of the control is rendered on the browser as shown: In the previous example, the value for the Text property of the custom control was set. ASP.NET added this property by default, when the control was created. The following code behind file of the control reveals this. using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace CustomControls { [DefaultProperty("Text")] [ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1 >")] public class ServerControl1 : WebControl { [Bindable(true)] [Category("Appearance")] [DefaultValue("")] [Localizable(true)] public string Text { get { String s = (String)ViewState["Text"]; return ((s == null) ? "[" + this.ID + "]" : s); } set { ViewState["Text"] = value; } } protected override void RenderContents(HtmlTextWriter output) { output.Write(Text); } } } The above code is automatically generated for a custom control. Events and methods could be added to the custom control class. Let us expand the previous custom control named SeverControl1. Let us give it a method named checkpalindrome, which gives it a power to check for palindromes. Palindromes are words/literals that spell the same when reversed. For example, Malayalam, madam, saras, etc. Extend the code for the custom control, which should look as: using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace CustomControls { [DefaultProperty("Text")] [ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1 >")] public class ServerControl1 : WebControl { [Bindable(true)] [Category("Appearance")] [DefaultValue("")] [Localizable(true)] public string Text { get { String s = (String)ViewState["Text"]; return ((s == null) ? "[" + this.ID + "]" : s); } set { ViewState["Text"] = value; } } protected override void RenderContents(HtmlTextWriter output) { if (this.checkpanlindrome()) { output.Write("This is a palindrome: <br />"); output.Write("<FONT size=5 color=Blue>"); output.Write("<B>"); output.Write(Text); output.Write("</B>"); output.Write("</FONT>"); } else { output.Write("This is not a palindrome: <br />"); output.Write("<FONT size=5 color=red>"); output.Write("<B>"); output.Write(Text); output.Write("</B>"); output.Write("</FONT>"); } } protected bool checkpanlindrome() { if (this.Text != null) { String str = this.Text; String strtoupper = Text.ToUpper(); char[] rev = strtoupper.ToCharArray(); Array.Reverse(rev); String strrev = new String(rev); if (strtoupper == strrev) { return true; } else { return false; } } else { return false; } } } } When you change the code for the control, you must build the solution by clicking Build --> Build Solution, so that the changes are reflected in your project. Add a text box and a button control to the page, so that the user can provide a text, it is checked for palindrome, when the button is clicked. <form id="form1" runat="server"> <div> Enter a word: <br /> <asp:TextBox ID="TextBox1" runat="server" style="width:198px"> </asp:TextBox> <br /> <br /> <asp:Button ID="Button1" runat="server onclick="Button1_Click" Text="Check Palindrome" style="width:132px" /> <br /> <br /> <ccs:ServerControl1 ID="ServerControl11" runat="server" Text = "" /> </div> </form> The Click event handler for the button simply copies the text from the text box to the text property of the custom control. protected void Button1_Click(object sender, EventArgs e) { this.ServerControl11.Text = this.TextBox1.Text; } When executed, the control successfully checks palindromes. Observe the following: (1) When you add a reference to the custom control, it is added to the toolbox and you can directly use it from the toolbox similar to any other control. (2) The RenderContents method of the custom control class is overridden here, as you can add your own methods and events. (3) The RenderContents method takes a parameter of HtmlTextWriter type, which is responsible for rendering on the browser. 51 Lectures 5.5 hours Anadi Sharma 44 Lectures 4.5 hours Kaushik Roy Chowdhury 42 Lectures 18 hours SHIVPRASAD KOIRALA 57 Lectures 3.5 hours University Code 40 Lectures 2.5 hours University Code 138 Lectures 9 hours Bhrugen Patel Print Add Notes Bookmark this page
[ { "code": null, "e": 2442, "s": 2347, "text": "ASP.NET allows the users to create controls. These user defined controls are categorized into:" }, { "code": null, "e": 2456, "s": 2442, "text": "User controls" }, { "code": null, "e": 2472, "s": 2456, "text": "Custom controls" }, { "code": null, "e": 2689, "s": 2472, "text": "User controls behaves like miniature ASP.NET pages or web forms, which could be used by many other pages. These are derived from the System.Web.UI.UserControl class. These controls have the following characteristics:" }, { "code": null, "e": 2719, "s": 2689, "text": "They have an .ascx extension." }, { "code": null, "e": 2776, "s": 2719, "text": "They may not contain any <html>, <body>, or <form> tags." }, { "code": null, "e": 2835, "s": 2776, "text": "They have a Control directive instead of a Page directive." }, { "code": null, "e": 3006, "s": 2835, "text": "To understand the concept, let us create a simple user control, which will work as footer for the web pages. To create and use the user control, take the following steps:" }, { "code": null, "e": 3036, "s": 3006, "text": "Create a new web application." }, { "code": null, "e": 3122, "s": 3036, "text": "Right click on the project folder on the Solution Explorer and choose Add New Item.\n\n" }, { "code": null, "e": 3387, "s": 3122, "text": "Select Web User Control from the Add New Item dialog box and name it footer.ascx. Initially, the footer.ascx contains only a Control directive.\n<%@ Control Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"footer.ascx.cs\" \n Inherits=\"customcontroldemo.footer\" %>\n" }, { "code": null, "e": 3531, "s": 3387, "text": "Select Web User Control from the Add New Item dialog box and name it footer.ascx. Initially, the footer.ascx contains only a Control directive." }, { "code": null, "e": 3651, "s": 3531, "text": "<%@ Control Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"footer.ascx.cs\" \n Inherits=\"customcontroldemo.footer\" %>" }, { "code": null, "e": 3864, "s": 3651, "text": "Add the following code to the file:\n<table>\n <tr>\n <td align=\"center\"> Copyright ©2010 TutorialPoints Ltd.</td>\n </tr>\n\n <tr>\n <td align=\"center\"> Location: Hyderabad, A.P </td>\n </tr>\n</table>\n" }, { "code": null, "e": 3900, "s": 3864, "text": "Add the following code to the file:" }, { "code": null, "e": 4076, "s": 3900, "text": "<table>\n <tr>\n <td align=\"center\"> Copyright ©2010 TutorialPoints Ltd.</td>\n </tr>\n\n <tr>\n <td align=\"center\"> Location: Hyderabad, A.P </td>\n </tr>\n</table>" }, { "code": null, "e": 4246, "s": 4076, "text": "To add the user control to your web page, you must add the Register directive and an instance of the user control to the page. The following code shows the content file:" }, { "code": null, "e": 5133, "s": 4246, "text": "<%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"Default.aspx.cs\" Inherits=\"customcontroldemo._Default\" %>\n \n<%@ Register Src=\"~/footer.ascx\" TagName=\"footer\" TagPrefix=\"Tfooter\" %>\n\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\" >\n\n <head runat=\"server\">\n <title>\n Untitled Page\n </title>\n </head>\n \n <body>\n \n <form id=\"form1\" runat=\"server\">\n <div>\n \n <asp:Label ID=\"Label1\" runat=\"server\" Text=\"Welcome to ASP.Net Tutorials \"></asp:Label>\n <br /> <br />\n <asp:Button ID=\"Button1\" runat=\"server\" onclick=\"Button1_Click\" Text=\"Copyright Info\" />\n \n </div>\n <Tfooter:footer ID=\"footer1\" runat=\"server\" />\n </form>\n \n </body>\n</html>" }, { "code": null, "e": 5239, "s": 5133, "text": "When executed, the page shows the footer and this control could be used in all the pages of your website." }, { "code": null, "e": 5262, "s": 5239, "text": "Observe the following:" }, { "code": null, "e": 5349, "s": 5262, "text": "(1) The Register directive specifies a tag name as well as tag prefix for the control." }, { "code": null, "e": 5422, "s": 5349, "text": "<%@ Register Src=\"~/footer.ascx\" TagName=\"footer\" TagPrefix=\"Tfooter\" %>" }, { "code": null, "e": 5518, "s": 5422, "text": "(2) The following tag name and prefix should be used while adding the user control on the page:" }, { "code": null, "e": 5565, "s": 5518, "text": "<Tfooter:footer ID=\"footer1\" runat=\"server\" />" }, { "code": null, "e": 5772, "s": 5565, "text": "Custom controls are deployed as individual assemblies. They are compiled into a Dynamic Link Library (DLL) and used as any other ASP.NET server control. They could be created in either of the following way:" }, { "code": null, "e": 5826, "s": 5772, "text": "By deriving a custom control from an existing control" }, { "code": null, "e": 5899, "s": 5826, "text": "By composing a new custom control combing two or more existing controls." }, { "code": null, "e": 5940, "s": 5899, "text": "By deriving from the base control class." }, { "code": null, "e": 6105, "s": 5940, "text": "To understand the concept, let us create a custom control, which will simply render a text message on the browser. To create this control, take the following steps:" }, { "code": null, "e": 6219, "s": 6105, "text": "Create a new website. Right click the solution (not the project) at the top of the tree in the Solution Explorer." }, { "code": null, "e": 6308, "s": 6219, "text": "In the New Project dialog box, select ASP.NET Server Control from the project templates." }, { "code": null, "e": 6698, "s": 6308, "text": "The above step adds a new project and creates a complete custom control to the solution, called ServerControl1. In this example, let us name the project CustomControls. To use this control, this must be added as a reference to the web site before registering it on a page. To add a reference to the existing project, right click on the project (not the solution), and click Add Reference." }, { "code": null, "e": 6836, "s": 6698, "text": "Select the CustomControls project from the Projects tab of the Add Reference dialog box. The Solution Explorer should show the reference." }, { "code": null, "e": 6925, "s": 6836, "text": "To use the control on a page, add the Register directive just below the @Page directive:" }, { "code": null, "e": 7012, "s": 6925, "text": "<%@ Register Assembly=\"CustomControls\" Namespace=\"CustomControls\" TagPrefix=\"ccs\" %>" }, { "code": null, "e": 7077, "s": 7012, "text": "Further, you can use the control, similar to any other controls." }, { "code": null, "e": 7220, "s": 7077, "text": "<form id=\"form1\" runat=\"server\">\n <div>\n <ccs:ServerControl1 runat=\"server\" Text = \"I am a Custom Server Control\" />\n </div> \n</form>" }, { "code": null, "e": 7305, "s": 7220, "text": "When executed, the Text property of the control is rendered on the browser as shown:" }, { "code": null, "e": 7523, "s": 7305, "text": "In the previous example, the value for the Text property of the custom control was set. ASP.NET added this property by default, when the control was created. The following code behind file of the control reveals this." }, { "code": null, "e": 8406, "s": 7523, "text": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Linq;\nusing System.Text;\n\nusing System.Web;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\n\nnamespace CustomControls\n{\n [DefaultProperty(\"Text\")]\n [ToolboxData(\"<{0}:ServerControl1 runat=server></{0}:ServerControl1 >\")]\n \n public class ServerControl1 : WebControl\n {\n [Bindable(true)]\n [Category(\"Appearance\")]\n [DefaultValue(\"\")]\n [Localizable(true)]\n \n public string Text\n {\n get\n {\n String s = (String)ViewState[\"Text\"];\n return ((s == null) ? \"[\" + this.ID + \"]\" : s);\n }\n \n set\n {\n ViewState[\"Text\"] = value;\n }\n }\n \n protected override void RenderContents(HtmlTextWriter output)\n {\n output.Write(Text);\n }\n }\n}" }, { "code": null, "e": 8533, "s": 8406, "text": "The above code is automatically generated for a custom control. Events and methods could be added to the custom control class." }, { "code": null, "e": 8692, "s": 8533, "text": "Let us expand the previous custom control named SeverControl1. Let us give it a method named checkpalindrome, which gives it a power to check for palindromes." }, { "code": null, "e": 8801, "s": 8692, "text": "Palindromes are words/literals that spell the same when reversed. For example, Malayalam, madam, saras, etc." }, { "code": null, "e": 8863, "s": 8801, "text": "Extend the code for the custom control, which should look as:" }, { "code": null, "e": 10885, "s": 8863, "text": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Linq;\nusing System.Text;\n\nusing System.Web;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\n\nnamespace CustomControls\n{\n [DefaultProperty(\"Text\")]\n [ToolboxData(\"<{0}:ServerControl1 runat=server></{0}:ServerControl1 >\")]\n \n public class ServerControl1 : WebControl\n {\n [Bindable(true)]\n [Category(\"Appearance\")]\n [DefaultValue(\"\")]\n [Localizable(true)]\n \n public string Text\n {\n get\n {\n String s = (String)ViewState[\"Text\"];\n return ((s == null) ? \"[\" + this.ID + \"]\" : s);\n }\n \n set\n {\n ViewState[\"Text\"] = value;\n }\n }\n \n protected override void RenderContents(HtmlTextWriter output)\n {\n if (this.checkpanlindrome())\n {\n output.Write(\"This is a palindrome: <br />\");\n output.Write(\"<FONT size=5 color=Blue>\");\n output.Write(\"<B>\");\n output.Write(Text);\n output.Write(\"</B>\");\n output.Write(\"</FONT>\");\n }\n else\n {\n output.Write(\"This is not a palindrome: <br />\");\n output.Write(\"<FONT size=5 color=red>\");\n output.Write(\"<B>\");\n output.Write(Text);\n output.Write(\"</B>\");\n output.Write(\"</FONT>\");\n }\n }\n \n protected bool checkpanlindrome()\n {\n if (this.Text != null)\n {\n String str = this.Text;\n String strtoupper = Text.ToUpper();\n char[] rev = strtoupper.ToCharArray();\n Array.Reverse(rev);\n String strrev = new String(rev);\n \n if (strtoupper == strrev)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n else\n {\n return false;\n }\n }\n }\n}" }, { "code": null, "e": 11188, "s": 10885, "text": "When you change the code for the control, you must build the solution by clicking Build --> Build Solution, so that the changes are reflected in your project. Add a text box and a button control to the page, so that the user can provide a text, it is checked for palindrome, when the button is clicked." }, { "code": null, "e": 11624, "s": 11188, "text": "<form id=\"form1\" runat=\"server\">\n <div>\n Enter a word:\n <br />\n <asp:TextBox ID=\"TextBox1\" runat=\"server\" style=\"width:198px\"> </asp:TextBox>\n \n <br /> <br />\n \n <asp:Button ID=\"Button1\" runat=\"server onclick=\"Button1_Click\" Text=\"Check Palindrome\" style=\"width:132px\" />\n \n <br /> <br />\n \n <ccs:ServerControl1 ID=\"ServerControl11\" runat=\"server\" Text = \"\" />\n </div>\n</form>" }, { "code": null, "e": 11748, "s": 11624, "text": "The Click event handler for the button simply copies the text from the text box to the text property of the custom control." }, { "code": null, "e": 11860, "s": 11748, "text": "protected void Button1_Click(object sender, EventArgs e)\n{\n this.ServerControl11.Text = this.TextBox1.Text;\n}" }, { "code": null, "e": 11920, "s": 11860, "text": "When executed, the control successfully checks palindromes." }, { "code": null, "e": 11943, "s": 11920, "text": "Observe the following:" }, { "code": null, "e": 12098, "s": 11943, "text": "(1) When you add a reference to the custom control, it is added to the toolbox and you can directly use it from the toolbox similar to any other control. " }, { "code": null, "e": 12220, "s": 12098, "text": "(2) The RenderContents method of the custom control class is overridden here, as you can add your own methods and events." }, { "code": null, "e": 12343, "s": 12220, "text": "(3) The RenderContents method takes a parameter of HtmlTextWriter type, which is responsible for rendering on the browser." }, { "code": null, "e": 12378, "s": 12343, "text": "\n 51 Lectures \n 5.5 hours \n" }, { "code": null, "e": 12392, "s": 12378, "text": " Anadi Sharma" }, { "code": null, "e": 12427, "s": 12392, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 12450, "s": 12427, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 12484, "s": 12450, "text": "\n 42 Lectures \n 18 hours \n" }, { "code": null, "e": 12504, "s": 12484, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 12539, "s": 12504, "text": "\n 57 Lectures \n 3.5 hours \n" }, { "code": null, "e": 12556, "s": 12539, "text": " University Code" }, { "code": null, "e": 12591, "s": 12556, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 12608, "s": 12591, "text": " University Code" }, { "code": null, "e": 12642, "s": 12608, "text": "\n 138 Lectures \n 9 hours \n" }, { "code": null, "e": 12657, "s": 12642, "text": " Bhrugen Patel" }, { "code": null, "e": 12664, "s": 12657, "text": " Print" }, { "code": null, "e": 12675, "s": 12664, "text": " Add Notes" } ]
MySQL Composite Index
A composite index is an index that is used on multiple columns. It is also known as a multiplecolumn index. Let us see the features − MySQL allows the user to create a composite index which can consist of up to 16 columns. MySQL allows the user to create a composite index which can consist of up to 16 columns. The query optimizer uses the composite indexes for queries which will test all columns in the index. The query optimizer uses the composite indexes for queries which will test all columns in the index. It can also be used for queries which will test the first columns, the first two columns, and so on. It can also be used for queries which will test the first columns, the first two columns, and so on. If the columns are specified in the right order in the index definition, a single composite index can be used that would speed up certain kinds of queries on the same table. If the columns are specified in the right order in the index definition, a single composite index can be used that would speed up certain kinds of queries on the same table. Let us see how a composite index can be created, during the creation of a table. It can be done using the below statement − CREATE TABLE table_name ( c1 data_type PRIMARY KEY, c2 data_type, c3 data_type, c4 data_type, INDEX index_name (c2,c3,c4) ); In the above statement, the composite index consists of three columns c2, c3, and c4. A composite index can also be added into an existing table using the ‘CREATE INDEX’ statement. Let us see how this can be done CREATE INDEX index_name ON table_name(c2,c3,c4); If there is a composite index on (c1,c2,c3), then the user would have indexed search capabilities on one the below mentioned column combinations − (c1) (c1,c2) (c1,c2,c3)
[ { "code": null, "e": 1170, "s": 1062, "text": "A composite index is an index that is used on multiple columns. It is also known as a multiplecolumn index." }, { "code": null, "e": 1196, "s": 1170, "text": "Let us see the features −" }, { "code": null, "e": 1285, "s": 1196, "text": "MySQL allows the user to create a composite index which can consist of up to 16 columns." }, { "code": null, "e": 1374, "s": 1285, "text": "MySQL allows the user to create a composite index which can consist of up to 16 columns." }, { "code": null, "e": 1475, "s": 1374, "text": "The query optimizer uses the composite indexes for queries which will test all columns in the index." }, { "code": null, "e": 1576, "s": 1475, "text": "The query optimizer uses the composite indexes for queries which will test all columns in the index." }, { "code": null, "e": 1677, "s": 1576, "text": "It can also be used for queries which will test the first columns, the first two columns, and so on." }, { "code": null, "e": 1778, "s": 1677, "text": "It can also be used for queries which will test the first columns, the first two columns, and so on." }, { "code": null, "e": 1952, "s": 1778, "text": "If the columns are specified in the right order in the index definition, a single composite index can be used that would speed up certain kinds of queries on the same table." }, { "code": null, "e": 2126, "s": 1952, "text": "If the columns are specified in the right order in the index definition, a single composite index can be used that would speed up certain kinds of queries on the same table." }, { "code": null, "e": 2250, "s": 2126, "text": "Let us see how a composite index can be created, during the creation of a table. It can be done using the below statement −" }, { "code": null, "e": 2390, "s": 2250, "text": "CREATE TABLE table_name (\n c1 data_type PRIMARY KEY,\n c2 data_type,\n c3 data_type,\n c4 data_type,\n INDEX index_name (c2,c3,c4)\n);" }, { "code": null, "e": 2476, "s": 2390, "text": "In the above statement, the composite index consists of three columns c2, c3, and c4." }, { "code": null, "e": 2603, "s": 2476, "text": "A composite index can also be added into an existing table using the ‘CREATE INDEX’ statement. Let us see how this can be done" }, { "code": null, "e": 2652, "s": 2603, "text": "CREATE INDEX index_name\nON table_name(c2,c3,c4);" }, { "code": null, "e": 2799, "s": 2652, "text": "If there is a composite index on (c1,c2,c3), then the user would have indexed search capabilities on one the below mentioned column combinations −" }, { "code": null, "e": 2823, "s": 2799, "text": "(c1)\n(c1,c2)\n(c1,c2,c3)" } ]
0-1 BFS (Shortest Path in a Binary Weight Graph) In C Program?
Suppose we have a graph with some nodes and connected edges. Each edge has binary weights. So the weights will be either 0 or 1. A source vertex is given. We have to find shortest path from source to any other vertices. Suppose the graph is like below − In normal BFS algorithm all edge weights are same. Here some are 0 and some are 1. In each step we will check the optimal distance condition. Here we will use the double ended queue to store the node. So we will check the edge weight. If it is 0, then push it at front, otherwise at back. Let us check the algorithm to get the better idea. binaryBFS(src) − begin define dist array to store source to vertex i into dist[i]. Initially fill with infinity dist[src] := 0 insert src into queue Q. v := first element from Q, and delete it from queue while Q is not empty, do for all connected edge e of v, do if the weight of v to next of i > dist[v] + weight of v to i weight, then update the weight if the weight is 0, then store to front, otherwise back end if done done print all distance from dist array end #include<iostream> #include<vector> #include<deque> #define V 8 using namespace std; struct node { int next, weight; }; vector <node> edges[V]; void binaryBFS(int src) { int dist[V]; for (int i=0; i<V; i++) //initially set as infinity dist[i] = INT_MAX; deque <int> Q; dist[src] = 0; //distance from source to source is 0 Q.push_back(src); while (!Q.empty()) { int v = Q.front(); //delete first vertex, and store to v Q.pop_front(); for (int i=0; i<edges[v].size(); i++) { //check optimal distance if (dist[edges[v][i].next] > dist[v] + edges[v][i].weight) { dist[edges[v][i].next] = dist[v] + edges[v][i].weight; if (edges[v][i].weight == 0) //0 weight edge is stored at front, otherwise at back Q.push_front(edges[v][i].next); else Q.push_back(edges[v][i].next); } } } for (int i=0; i<V; i++) cout << dist[i] << " "; } void addEdge(int u, int v, int wt) { edges[u].push_back({v, wt}); edges[v].push_back({u, wt}); } int main() { addEdge(0, 1, 0); addEdge(0, 3, 1); addEdge(0, 4, 0); addEdge(1, 2, 1); addEdge(1, 7, 0); addEdge(2, 5, 1); addEdge(2, 7, 0); addEdge(3, 4, 0); addEdge(3, 6, 1); addEdge(4, 6, 1); addEdge(5, 7, 1); addEdge(6, 7, 1); int src = 6; binaryBFS(src); } 1 1 1 1 1 2 0 1
[ { "code": null, "e": 1316, "s": 1062, "text": "Suppose we have a graph with some nodes and connected edges. Each edge has binary weights. So the weights will be either 0 or 1. A source vertex is given. We have to find shortest path from source to any other vertices. Suppose the graph is like below −" }, { "code": null, "e": 1656, "s": 1316, "text": "In normal BFS algorithm all edge weights are same. Here some are 0 and some are 1. In each step we will check the optimal distance condition. Here we will use the double ended queue to store the node. So we will check the edge weight. If it is 0, then push it at front, otherwise at back. Let us check the algorithm to get the better idea." }, { "code": null, "e": 1673, "s": 1656, "text": "binaryBFS(src) −" }, { "code": null, "e": 2186, "s": 1673, "text": "begin\n define dist array to store source to vertex i into dist[i]. Initially fill with infinity\n dist[src] := 0\n insert src into queue Q.\n v := first element from Q, and delete it from queue\n while Q is not empty, do\n for all connected edge e of v, do\n if the weight of v to next of i > dist[v] + weight of v to i weight, then update the weight\n if the weight is 0, then store to front, otherwise back\n end if\n done\n done\n print all distance from dist array\nend" }, { "code": null, "e": 3568, "s": 2186, "text": "#include<iostream>\n#include<vector>\n#include<deque>\n#define V 8\nusing namespace std;\nstruct node {\n int next, weight;\n};\nvector <node> edges[V];\nvoid binaryBFS(int src) {\n int dist[V];\n for (int i=0; i<V; i++) //initially set as infinity\n dist[i] = INT_MAX;\n deque <int> Q;\n dist[src] = 0; //distance from source to source is 0\n Q.push_back(src);\n while (!Q.empty()) {\n int v = Q.front(); //delete first vertex, and store to v\n Q.pop_front();\n for (int i=0; i<edges[v].size(); i++) {\n //check optimal distance\n if (dist[edges[v][i].next] > dist[v] + edges[v][i].weight) {\n dist[edges[v][i].next] = dist[v] + edges[v][i].weight;\n if (edges[v][i].weight == 0) //0 weight edge is stored at front, otherwise at back\n Q.push_front(edges[v][i].next);\n else\n Q.push_back(edges[v][i].next);\n }\n }\n }\n for (int i=0; i<V; i++)\n cout << dist[i] << \" \";\n}\nvoid addEdge(int u, int v, int wt) {\n edges[u].push_back({v, wt});\n edges[v].push_back({u, wt});\n}\nint main() {\n addEdge(0, 1, 0);\n addEdge(0, 3, 1);\n addEdge(0, 4, 0);\n addEdge(1, 2, 1);\n addEdge(1, 7, 0);\n addEdge(2, 5, 1);\n addEdge(2, 7, 0);\n addEdge(3, 4, 0);\n addEdge(3, 6, 1);\n addEdge(4, 6, 1);\n addEdge(5, 7, 1);\n addEdge(6, 7, 1);\n int src = 6;\n binaryBFS(src);\n}" }, { "code": null, "e": 3584, "s": 3568, "text": "1 1 1 1 1 2 0 1" } ]
Find minimum difference between any two element in C++
Suppose we have an array of n elements called A. We have to find the minimum difference between any two elements in that array. Suppose the A = [30, 5, 20, 9], then the result will be 4. this is the minimum distance of elements 5 and 9. To solve this problem, we have to follow these steps − Sort the array in non-decreasing order Sort the array in non-decreasing order Initialize the difference as infinite Initialize the difference as infinite Compare all adjacent pairs in the sorted array and keep track of the minimum one Compare all adjacent pairs in the sorted array and keep track of the minimum one #include<iostream> #include<algorithm> using namespace std; int getMinimumDifference(int a[], int n) { sort(a, a+n); int min_diff = INT_MAX; for (int i=0; i<n-1; i++) if (a[i+1] - a[i] < min_diff) min_diff = a[i+1] - a[i]; return min_diff; } int main() { int arr[] = {30, 5, 20, 9}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Minimum difference between two elements is: " << getMinimumDifference(arr, n); } Minimum difference between two elements is: 4
[ { "code": null, "e": 1299, "s": 1062, "text": "Suppose we have an array of n elements called A. We have to find the minimum difference between any two elements in that array. Suppose the A = [30, 5, 20, 9], then the result will be 4. this is the minimum distance of elements 5 and 9." }, { "code": null, "e": 1354, "s": 1299, "text": "To solve this problem, we have to follow these steps −" }, { "code": null, "e": 1393, "s": 1354, "text": "Sort the array in non-decreasing order" }, { "code": null, "e": 1432, "s": 1393, "text": "Sort the array in non-decreasing order" }, { "code": null, "e": 1470, "s": 1432, "text": "Initialize the difference as infinite" }, { "code": null, "e": 1508, "s": 1470, "text": "Initialize the difference as infinite" }, { "code": null, "e": 1589, "s": 1508, "text": "Compare all adjacent pairs in the sorted array and keep track of the minimum one" }, { "code": null, "e": 1670, "s": 1589, "text": "Compare all adjacent pairs in the sorted array and keep track of the minimum one" }, { "code": null, "e": 2115, "s": 1670, "text": "#include<iostream>\n#include<algorithm>\nusing namespace std;\nint getMinimumDifference(int a[], int n) {\n sort(a, a+n);\n int min_diff = INT_MAX;\n for (int i=0; i<n-1; i++)\n if (a[i+1] - a[i] < min_diff)\n min_diff = a[i+1] - a[i];\n return min_diff;\n}\nint main() {\n int arr[] = {30, 5, 20, 9};\n int n = sizeof(arr)/sizeof(arr[0]);\n cout << \"Minimum difference between two elements is: \" << getMinimumDifference(arr, n);\n}" }, { "code": null, "e": 2161, "s": 2115, "text": "Minimum difference between two elements is: 4" } ]
LINQ | Element Operator | FirstOrDefault - GeeksforGeeks
24 May, 2019 The element operators are used to return a single, or a specific element from the sequence or collection. For example, in a school when we ask, who is the principal? Then there will be only one person that will be the principal of the school. So the number of students is a collection and the principal is the only result that comes from the collection. The LINQ Standard Query Operator supports 8 types of element operators: ElementAtElementAtOrDefaultFirstFirstOrDefaultLastLastOrDefaultSingleSingleOrDefault ElementAt ElementAtOrDefault First FirstOrDefault Last LastOrDefault Single SingleOrDefault The FirstOrDefault operator is used to return the first element of the given collection or sequence. Or it can also return the first element according to the given condition. And it provides a default value if the given collection or sequence does not contain any element or if the collection or sequence does not contain the element which specifies the given condition. Or we can say that the FirstOrDefault Operator is created to overcome the InvalidOperationException problem of the First operator. This method can be overloaded in two different ways: FirstOrDefault<TSource>(IEnumerable<TSource>): This method returns the first element of the given sequence or collection without any condition. Or returns the default value if the given collection or sequence does not contain any element. FirstOrDefault<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>): This method returns the first element which specifies the given condition. Or returns the default value if the collection does not contain the element which specifies the given condition. Important Points: It does not support query syntax in C# and VB.Net languages. It support method syntax in both C# and VB.Net languages. It present in both the Queryable and Enumerable class. If the given collection contain a null element, then this method will throw an ArgumentNullException. The default value of the reference types and the nullable types is null. Example 1: // C# program to illustrate the // use of FirstOrDefault operatorusing System;using System.Linq;using System.Collections.Generic; class GFG { static public void Main() { // Data source int[] sequence1 = {112, 44, 55, 66, 77, 777, 56}; // Get the element which specifies // the given condition // Using FirstOrDefault function var result1 = sequence1.FirstOrDefault(seq => seq < 77); Console.WriteLine("Value: {0}", result1); // Getting Default value because the // sequence does not contain any element int[] sequence2 = {}; var result2 = sequence2.FirstOrDefault(); Console.WriteLine("Default value: {0}", result2); }} Value: 44 Default value: 0 Example 2: // C# program to find the name // of the first employeeusing System;using System.Linq;using System.Collections.Generic; // Employee detailspublic class Employee { public int emp_id { get; set; } public string emp_name { get; set; } public string emp_gender { get; set; } public string emp_hire_date { get; set; } public int emp_salary { get; set; }} class GFG { // Main method static public void Main() { List<Employee> emp = new List<Employee>() { new Employee() {emp_id = 209, emp_name = "Anjita", emp_gender = "Female", emp_hire_date = "12/3/2017", emp_salary = 20000}, new Employee() {emp_id = 210, emp_name = "Soniya", emp_gender = "Female", emp_hire_date = "22/4/2018", emp_salary = 30000}, new Employee() {emp_id = 211, emp_name = "Rohit", emp_gender = "Male", emp_hire_date = "3/5/2016", emp_salary = 40000}, new Employee() {emp_id = 212, emp_name = "Supriya", emp_gender = "Female", emp_hire_date = "4/8/2017", emp_salary = 40000}, new Employee() {emp_id = 213, emp_name = "Anil", emp_gender = "Male", emp_hire_date = "12/1/2016", emp_salary = 40000}, new Employee() {emp_id = 214, emp_name = "Anju", emp_gender = "Female", emp_hire_date = "17/6/2015", emp_salary = 50000}, }; // Query to find the name the first // employee Using FirstOrDefault method var res = emp.Select(e => e.emp_name).FirstOrDefault(); Console.WriteLine("Employee Name: {0}", res); }} Employee Name: Anjita CSharp LINQ C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# | Method Overriding C# Dictionary with examples Difference between Ref and Out keywords in C# C# | Delegates Top 50 C# Interview Questions & Answers C# | Constructors Extension Method in C# Introduction to .NET Framework C# | Abstract Classes C# | Class and Object
[ { "code": null, "e": 24251, "s": 24223, "text": "\n24 May, 2019" }, { "code": null, "e": 24605, "s": 24251, "text": "The element operators are used to return a single, or a specific element from the sequence or collection. For example, in a school when we ask, who is the principal? Then there will be only one person that will be the principal of the school. So the number of students is a collection and the principal is the only result that comes from the collection." }, { "code": null, "e": 24677, "s": 24605, "text": "The LINQ Standard Query Operator supports 8 types of element operators:" }, { "code": null, "e": 24762, "s": 24677, "text": "ElementAtElementAtOrDefaultFirstFirstOrDefaultLastLastOrDefaultSingleSingleOrDefault" }, { "code": null, "e": 24772, "s": 24762, "text": "ElementAt" }, { "code": null, "e": 24791, "s": 24772, "text": "ElementAtOrDefault" }, { "code": null, "e": 24797, "s": 24791, "text": "First" }, { "code": null, "e": 24812, "s": 24797, "text": "FirstOrDefault" }, { "code": null, "e": 24817, "s": 24812, "text": "Last" }, { "code": null, "e": 24831, "s": 24817, "text": "LastOrDefault" }, { "code": null, "e": 24838, "s": 24831, "text": "Single" }, { "code": null, "e": 24854, "s": 24838, "text": "SingleOrDefault" }, { "code": null, "e": 25409, "s": 24854, "text": "The FirstOrDefault operator is used to return the first element of the given collection or sequence. Or it can also return the first element according to the given condition. And it provides a default value if the given collection or sequence does not contain any element or if the collection or sequence does not contain the element which specifies the given condition. Or we can say that the FirstOrDefault Operator is created to overcome the InvalidOperationException problem of the First operator. This method can be overloaded in two different ways:" }, { "code": null, "e": 25648, "s": 25409, "text": "FirstOrDefault<TSource>(IEnumerable<TSource>): This method returns the first element of the given sequence or collection without any condition. Or returns the default value if the given collection or sequence does not contain any element." }, { "code": null, "e": 25907, "s": 25648, "text": "FirstOrDefault<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>): This method returns the first element which specifies the given condition. Or returns the default value if the collection does not contain the element which specifies the given condition." }, { "code": null, "e": 25925, "s": 25907, "text": "Important Points:" }, { "code": null, "e": 25986, "s": 25925, "text": "It does not support query syntax in C# and VB.Net languages." }, { "code": null, "e": 26044, "s": 25986, "text": "It support method syntax in both C# and VB.Net languages." }, { "code": null, "e": 26099, "s": 26044, "text": "It present in both the Queryable and Enumerable class." }, { "code": null, "e": 26201, "s": 26099, "text": "If the given collection contain a null element, then this method will throw an ArgumentNullException." }, { "code": null, "e": 26274, "s": 26201, "text": "The default value of the reference types and the nullable types is null." }, { "code": null, "e": 26285, "s": 26274, "text": "Example 1:" }, { "code": "// C# program to illustrate the // use of FirstOrDefault operatorusing System;using System.Linq;using System.Collections.Generic; class GFG { static public void Main() { // Data source int[] sequence1 = {112, 44, 55, 66, 77, 777, 56}; // Get the element which specifies // the given condition // Using FirstOrDefault function var result1 = sequence1.FirstOrDefault(seq => seq < 77); Console.WriteLine(\"Value: {0}\", result1); // Getting Default value because the // sequence does not contain any element int[] sequence2 = {}; var result2 = sequence2.FirstOrDefault(); Console.WriteLine(\"Default value: {0}\", result2); }}", "e": 27058, "s": 26285, "text": null }, { "code": null, "e": 27086, "s": 27058, "text": "Value: 44\nDefault value: 0\n" }, { "code": null, "e": 27097, "s": 27086, "text": "Example 2:" }, { "code": "// C# program to find the name // of the first employeeusing System;using System.Linq;using System.Collections.Generic; // Employee detailspublic class Employee { public int emp_id { get; set; } public string emp_name { get; set; } public string emp_gender { get; set; } public string emp_hire_date { get; set; } public int emp_salary { get; set; }} class GFG { // Main method static public void Main() { List<Employee> emp = new List<Employee>() { new Employee() {emp_id = 209, emp_name = \"Anjita\", emp_gender = \"Female\", emp_hire_date = \"12/3/2017\", emp_salary = 20000}, new Employee() {emp_id = 210, emp_name = \"Soniya\", emp_gender = \"Female\", emp_hire_date = \"22/4/2018\", emp_salary = 30000}, new Employee() {emp_id = 211, emp_name = \"Rohit\", emp_gender = \"Male\", emp_hire_date = \"3/5/2016\", emp_salary = 40000}, new Employee() {emp_id = 212, emp_name = \"Supriya\", emp_gender = \"Female\", emp_hire_date = \"4/8/2017\", emp_salary = 40000}, new Employee() {emp_id = 213, emp_name = \"Anil\", emp_gender = \"Male\", emp_hire_date = \"12/1/2016\", emp_salary = 40000}, new Employee() {emp_id = 214, emp_name = \"Anju\", emp_gender = \"Female\", emp_hire_date = \"17/6/2015\", emp_salary = 50000}, }; // Query to find the name the first // employee Using FirstOrDefault method var res = emp.Select(e => e.emp_name).FirstOrDefault(); Console.WriteLine(\"Employee Name: {0}\", res); }}", "e": 28952, "s": 27097, "text": null }, { "code": null, "e": 28975, "s": 28952, "text": "Employee Name: Anjita\n" }, { "code": null, "e": 28987, "s": 28975, "text": "CSharp LINQ" }, { "code": null, "e": 28990, "s": 28987, "text": "C#" }, { "code": null, "e": 29088, "s": 28990, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29097, "s": 29088, "text": "Comments" }, { "code": null, "e": 29110, "s": 29097, "text": "Old Comments" }, { "code": null, "e": 29133, "s": 29110, "text": "C# | Method Overriding" }, { "code": null, "e": 29161, "s": 29133, "text": "C# Dictionary with examples" }, { "code": null, "e": 29207, "s": 29161, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 29222, "s": 29207, "text": "C# | Delegates" }, { "code": null, "e": 29262, "s": 29222, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 29280, "s": 29262, "text": "C# | Constructors" }, { "code": null, "e": 29303, "s": 29280, "text": "Extension Method in C#" }, { "code": null, "e": 29334, "s": 29303, "text": "Introduction to .NET Framework" }, { "code": null, "e": 29356, "s": 29334, "text": "C# | Abstract Classes" } ]
C++ Program to Implement Ternary Tree
A ternary tree, is a tree data structure in which each node has at most three child nodes, usually represented as “left”, “mid” and “right”. In this tree, nodes with children are parent nodes, and child nodes may contain references to their parents. This is a C++ Program to Implement Ternary Tree and traversal of the tree. Begin Declare function insert(struct nod** root, char *w) if (!(*root)) then *root = newnod(*w); if ((*w) < (*root)->d) then insert(&( (*root)->l ), w); else if ((*w) > (*root)->d) then insert(&( (*root)->r ), w); else if (*(w+1)) insert(&( (*root)->eq ), w+1); else (*root)->EndOfString = 1; End. For Traversal of tree: Begin Declare function traverseTTtil(struct nod* root, char* buffer, int depth) if (root) then traverseTTtil(root->l, buffer, depth) buffer[depth] = root->d if (root->EndOfString) then buffer[depth+1] = '\0' print the value of buffer. traverseTTtil(root->eq, buffer, depth + 1); traverseTTtil(root->r, buffer, depth); End. #include<stdlib.h> #include<iostream> using namespace std; struct nod { char d; unsigned End. fString: 1; struct nod *l, *eq, *r; }*t = NULL; struct nod* newnod(char d) { t = new nod; t->d = d; t->End. fString = 0; t->l = t->eq = t->r = NULL; return t; } void insert(struct nod** root, char *w) { if (!(*root)) *root = newnod(*w); if ((*w) < (*root)->d) insert(&( (*root)->l ), w); else if ((*w) > (*root)->d) insert(&( (*root)->r ), w); else { if (*(w+1)) insert(&( (*root)->eq ), w+1); else (*root)->End. fString = 1; } } void traverseTTtil(struct nod* root, char* buffer, int depth) { if (root) { traverseTTtil(root->l, buffer, depth); buffer[depth] = root->d; if (root->End. String) { buffer[depth+1] = '\0'; cout<<buffer<<endl; } traverseTTtil(root->eq, buffer, depth + 1); traverseTTtil(root->r, buffer, depth); } } void traverseTT(struct nod* root) { char buffer[50]; traverseTTtil(root, buffer, 0); } int main() { struct nod *root = NULL; insert(&root, "mat"); insert(&root, "bat"); insert(&root, "hat"); insert(&root, "rat"); cout<<"Following is traversal of ternary tree\n"; traverseTT(root); } Following is traversal of ternary tree bat hat mat rat
[ { "code": null, "e": 1387, "s": 1062, "text": "A ternary tree, is a tree data structure in which each node has at most three child nodes, usually represented as “left”, “mid” and “right”. In this tree, nodes with children are parent nodes, and child nodes may contain references to their parents. This is a C++ Program to Implement Ternary Tree and traversal of the tree." }, { "code": null, "e": 1781, "s": 1387, "text": "Begin\n Declare function insert(struct nod** root, char *w)\n if (!(*root)) then\n *root = newnod(*w);\n if ((*w) < (*root)->d) then\n insert(&( (*root)->l ), w);\n else if ((*w) > (*root)->d) then\n insert(&( (*root)->r ), w);\n else if (*(w+1))\n insert(&( (*root)->eq ), w+1);\n else\n (*root)->EndOfString = 1;\nEnd." }, { "code": null, "e": 1804, "s": 1781, "text": "For Traversal of tree:" }, { "code": null, "e": 2226, "s": 1804, "text": "Begin\n Declare function traverseTTtil(struct nod* root, char* buffer,\n int depth)\n if (root) then\n traverseTTtil(root->l, buffer, depth)\n buffer[depth] = root->d\n if (root->EndOfString) then\n buffer[depth+1] = '\\0'\n print the value of buffer.\n traverseTTtil(root->eq, buffer, depth + 1);\n traverseTTtil(root->r, buffer, depth);\nEnd." }, { "code": null, "e": 3517, "s": 2226, "text": "#include<stdlib.h>\n#include<iostream>\nusing namespace std;\nstruct nod {\n char d;\n unsigned End.\n fString: 1;\n struct nod *l, *eq, *r;\n}*t = NULL;\nstruct nod* newnod(char d) {\n t = new nod;\n t->d = d;\n t->End.\n fString = 0;\n t->l = t->eq = t->r = NULL;\n return t;\n}\nvoid insert(struct nod** root, char *w) {\n if (!(*root))\n *root = newnod(*w);\n if ((*w) < (*root)->d)\n insert(&( (*root)->l ), w);\n else if ((*w) > (*root)->d)\n insert(&( (*root)->r ), w);\n else {\n if (*(w+1))\n insert(&( (*root)->eq ), w+1);\n else\n (*root)->End.\n fString = 1;\n }\n}\nvoid traverseTTtil(struct nod* root, char* buffer, int depth) {\n if (root) {\n traverseTTtil(root->l, buffer, depth);\n buffer[depth] = root->d;\n if (root->End. String) {\n buffer[depth+1] = '\\0';\n cout<<buffer<<endl;\n }\n traverseTTtil(root->eq, buffer, depth + 1);\n traverseTTtil(root->r, buffer, depth);\n }\n}\nvoid traverseTT(struct nod* root) {\n char buffer[50];\n traverseTTtil(root, buffer, 0);\n}\nint main() {\n struct nod *root = NULL;\n insert(&root, \"mat\");\n insert(&root, \"bat\");\n insert(&root, \"hat\");\n insert(&root, \"rat\");\n cout<<\"Following is traversal of ternary tree\\n\";\n traverseTT(root);\n}" }, { "code": null, "e": 3572, "s": 3517, "text": "Following is traversal of ternary tree\nbat\nhat\nmat\nrat" } ]
How to write a global error handler in JavaScript?
The following global error handler will show how to catch unhandled exception − <!DOCTYPE html> <html> <body> <script> window.onerror = function(errMsg, url, line, column, error) { var result = !column ? '' : '\ncolumn: ' + column; result += !error; document.write("Error= " + errMsg + "\nurl= " + url + "\nline= " + line + result); var suppressErrorAlert = true; return suppressErrorAlert; }; setTimeout(function() { eval("{"); }, 500) </script> </body> </html>
[ { "code": null, "e": 1142, "s": 1062, "text": "The following global error handler will show how to catch unhandled exception −" }, { "code": null, "e": 1651, "s": 1142, "text": "<!DOCTYPE html>\n<html>\n <body>\n <script>\n window.onerror = function(errMsg, url, line, column, error) {\n var result = !column ? '' : '\\ncolumn: ' + column;\n result += !error;\n document.write(\"Error= \" + errMsg + \"\\nurl= \" + url + \"\\nline= \" + line + result);\n var suppressErrorAlert = true;\n return suppressErrorAlert;\n };\n setTimeout(function() {\n eval(\"{\");\n }, 500)\n </script>\n </body>\n</html>" } ]
Count the Specials | Practice | GeeksforGeeks
Given an array A (may contain duplicates) of N elements and a positive integer K. The task is to count the number of elements which occurs exactly floor(N/K) times in the array. Example: Input:N = 5K = 2A[] = 1 4 1 2 4Output:2Explanation:In the given array, 1 and 4 occurs floor(5/2) = 2 times. So count is 2. Your Task:Your task is to complete the function countSpecials() which should count the elements which occurs exactly floor(N/K) times. Constrains:1 <= N <= 1031 <= Ai <= 1031 <= K <= 103 0 hgaur7011 month ago TIME COMPLEXITY : O(n+m) , TIME TAKEN : 0.0 BY USING MAP :- int countSpecials(int arr[], int sizeof_array, int K){ int f = floor(sizeof_array/K), count = 0; int cot = 0; map<int, int> ob; map<int, int>::iterator it; for (int i = 0; i < sizeof_array; i++) { ob[arr[i]]++; } for (auto &&i : ob) { if (i.second == f) { count++; } } return count; } 0 sumitd12991 month ago SIMPLEST CODE WITH LEAST TIME COMPLEXITY YOU WILL GET HERE IS : int countSpecials(int arr[], int sizeof_array, int K){ int f = floor(sizeof_array/K), count = 0; int arr2[1000]={0}; // Your code here for(int i=0;i<sizeof_array;i++){ arr2[arr[i]]++; } for(int i=0;i<1000;i++){ if(arr2[i]==f){ count++; } } return count; } +1 benklomp1 month ago int countSpecials(int arr[], int n, int K) { int f = floor(n/K), count = 0; // Your code here // simple bubble sort for(int i = 0; i < n; ++i) for(int j = 0; j < n; ++j) if(arr[i] > arr[j]) { int T = arr[i]; arr[i] = arr[j]; arr[j] = T; } int counter = 0, p = -1; for(int i = 0; i < n; i += 1) { if(arr[i] == p) continue; int counter = 1, j = i; while(++j < n && arr[i] == arr[j]) ++counter; if(counter == f) ++count; p = arr[i]; } return count; 0 sumitrodge272 months ago i dont know how map works, someone help! int countSpecials(int arr[], int sizeof_array, int K){ int f = floor(sizeof_array/K), count = 0; int t=0; for(int i=0;i<sizeof_array;i++) { for(int j=0;j<sizeof_array;j++) { if(arr[i]==arr[j]) { t++; } } if(t==f) { count++; } t=0; } count=ceil(count/f); return count; } 0 sumitrodge273 months ago someone please tell me what's wrong with my code int countSpecials(int arr[], int sizeof_array, int K){ int f = floor(sizeof_array/K), count = 0; int p=0; for(int i=0;i<sizeof_array;i++) { for(int j=0;j<sizeof_array;j++) { if(arr[i]==arr[j]) { p+=1; } } if(p==f) { count+=1; } p=0; } return count; } -2 dipawalimandaokar3213 months ago // { Driver Code Starts//Initial Template for C++#include <bits/stdc++.h>using namespace std; // Function Prototypeint countSpecials(int[], int, int); // } Driver Code Ends//User function Template for C++ /*Function to count number of elements with occurrence* exactly equal to floor(sizeof_array/K)* arr : input array* sizeof_array : number of array elements*/int countSpecials(int arr[], int sizeof_array, int K){ int f = floor(sizeof_array/K),p=0; for(int i=0;i<sizeof_array;i++) { int count; for(int j=0;j<sizeof_array;j++) { if(arr[i]==arr[j]) count++ ; } if(count==f) p++; } // Your code here return p; } // { Driver Code Starts. // Driver code to rest countSpecials functionint main() {// Testcase inputint testcase;cin >> testcase;while(testcase--){ // sizeof_array : number of array elements // K : as given in statement int sizeof_array, K; cin >> sizeof_array >> K; // array of size sizeof_array int arr[sizeof_array]; for(int i = 0;i<sizeof_array;i++){ cin >> arr[i]; } // calling function and printing count the occurrence cout << countSpecials(arr, sizeof_array, K) << endl; }return 0;} // } Driver Code Ends Whats the problem in countspecial function..am unable to understand. 0 hitentandon3 months ago JS Sol: let f = Math.floor(N/K), count = 0, cc=1; arr.sort(); for(let i = 1; i < N; i++) if(arr[i]==arr[i-1]) cc++; else if(cc===f) { count++; cc=1; } else cc=1; if(cc===f) count++; return count; C++ Sol: int f = floor(N/K), count = 0, cc=1; sort(arr, arr+N); for(int i = 1; i < N; i++) if(arr[i]==arr[i-1]) cc++; else if(cc==f) { count++; cc=1; } else cc=1; if(cc==f) count++; return count; +1 sourabhsingh191220014 months ago Easy C++ Solution int countSpecials(int arr[], int sizeof_array, int K){ int f = floor(sizeof_array/K), cnt = 0; unordered_map<int,int>mp; // Your code here for(int i=0;i<sizeof_array;i++){ if(mp.find(arr[i]) == mp.end()){ mp[arr[i]]=1; }else mp[arr[i]]++; } for(auto &i:mp){ if(i.second==f) cnt++; } return cnt; } 0 harshitd8914 months ago int countSpecials(int arr[], int N, int K){ int f = floor(N/K), count = 0;int array[1000];for(int i=0;i<1000;i++){array[i]=0; } for(int i=0;i<1000;i++){ if(i<N){ int p=arr[i]; array[p]=array[p]+1; } else{ break; }}for(int i=0;i<1000;i++){ if(array[i]==f){ count++; }} return count; } 0 ayushnautiyal11106 months ago int countSpecials(int arr[], int sizeof_array, int K){ int f = floor(sizeof_array/K), count = 0; unordered_map<int,int>mp; for(int i=0;i<sizeof_array;i++){ mp[arr[i]]++; } for(auto it =mp.begin();it!=mp.end();it++){ if(it->second==f){ count++; } } return count;} 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": 456, "s": 278, "text": "Given an array A (may contain duplicates) of N elements and a positive integer K. The task is to count the number of elements which occurs exactly floor(N/K) times in the array." }, { "code": null, "e": 465, "s": 456, "text": "Example:" }, { "code": null, "e": 588, "s": 465, "text": "Input:N = 5K = 2A[] = 1 4 1 2 4Output:2Explanation:In the given array, 1 and 4 occurs floor(5/2) = 2 times. So count is 2." }, { "code": null, "e": 723, "s": 588, "text": "Your Task:Your task is to complete the function countSpecials() which should count the elements which occurs exactly floor(N/K) times." }, { "code": null, "e": 775, "s": 723, "text": "Constrains:1 <= N <= 1031 <= Ai <= 1031 <= K <= 103" }, { "code": null, "e": 777, "s": 775, "text": "0" }, { "code": null, "e": 797, "s": 777, "text": "hgaur7011 month ago" }, { "code": null, "e": 841, "s": 797, "text": "TIME COMPLEXITY : O(n+m) , TIME TAKEN : 0.0" }, { "code": null, "e": 857, "s": 841, "text": "BY USING MAP :-" }, { "code": null, "e": 1258, "s": 857, "text": "int countSpecials(int arr[], int sizeof_array, int K){\n \n int f = floor(sizeof_array/K), count = 0;\n \n int cot = 0;\n \n map<int, int> ob;\n map<int, int>::iterator it;\n\n for (int i = 0; i < sizeof_array; i++)\n {\n ob[arr[i]]++;\n }\n\n for (auto &&i : ob)\n {\n if (i.second == f)\n {\n count++;\n }\n }\n\n \n return count;\n \n}" }, { "code": null, "e": 1260, "s": 1258, "text": "0" }, { "code": null, "e": 1282, "s": 1260, "text": "sumitd12991 month ago" }, { "code": null, "e": 1346, "s": 1282, "text": "SIMPLEST CODE WITH LEAST TIME COMPLEXITY YOU WILL GET HERE IS :" }, { "code": null, "e": 1636, "s": 1348, "text": "int countSpecials(int arr[], int sizeof_array, int K){ int f = floor(sizeof_array/K), count = 0; int arr2[1000]={0}; // Your code here for(int i=0;i<sizeof_array;i++){ arr2[arr[i]]++; } for(int i=0;i<1000;i++){ if(arr2[i]==f){ count++; } }" }, { "code": null, "e": 1650, "s": 1636, "text": "return count;" }, { "code": null, "e": 1652, "s": 1650, "text": "}" }, { "code": null, "e": 1655, "s": 1652, "text": "+1" }, { "code": null, "e": 1675, "s": 1655, "text": "benklomp1 month ago" }, { "code": null, "e": 2393, "s": 1675, "text": "int countSpecials(int arr[], int n, int K)\n{\n int f = floor(n/K), count = 0;\n \n // Your code here\n \n // simple bubble sort\n for(int i = 0; i < n; ++i)\n for(int j = 0; j < n; ++j)\n if(arr[i] > arr[j])\n {\n int T = arr[i];\n arr[i] = arr[j];\n arr[j] = T;\n }\n \n int counter = 0, p = -1;\n for(int i = 0; i < n; i += 1)\n {\n if(arr[i] == p) continue;\n \n int counter = 1, j = i;\n while(++j < n && arr[i] == arr[j])\n ++counter;\n \n if(counter == f)\n ++count;\n \n p = arr[i];\n }\n \n return count;" }, { "code": null, "e": 2395, "s": 2393, "text": "0" }, { "code": null, "e": 2420, "s": 2395, "text": "sumitrodge272 months ago" }, { "code": null, "e": 2461, "s": 2420, "text": "i dont know how map works, someone help!" }, { "code": null, "e": 2899, "s": 2461, "text": "int countSpecials(int arr[], int sizeof_array, int K){\n \n int f = floor(sizeof_array/K), count = 0;\n int t=0;\n for(int i=0;i<sizeof_array;i++)\n {\n for(int j=0;j<sizeof_array;j++)\n {\n if(arr[i]==arr[j])\n {\n t++;\n }\n }\n if(t==f)\n {\n count++;\n }\n t=0;\n }\n \n count=ceil(count/f);\n \n return count;\n \n}" }, { "code": null, "e": 2901, "s": 2899, "text": "0" }, { "code": null, "e": 2926, "s": 2901, "text": "sumitrodge273 months ago" }, { "code": null, "e": 2976, "s": 2926, "text": "someone please tell me what's wrong with my code " }, { "code": null, "e": 3346, "s": 2978, "text": "int countSpecials(int arr[], int sizeof_array, int K){ int f = floor(sizeof_array/K), count = 0; int p=0; for(int i=0;i<sizeof_array;i++) { for(int j=0;j<sizeof_array;j++) { if(arr[i]==arr[j]) { p+=1; } } if(p==f) { count+=1; } p=0; } return count; }" }, { "code": null, "e": 3351, "s": 3348, "text": "-2" }, { "code": null, "e": 3384, "s": 3351, "text": "dipawalimandaokar3213 months ago" }, { "code": null, "e": 3478, "s": 3384, "text": "// { Driver Code Starts//Initial Template for C++#include <bits/stdc++.h>using namespace std;" }, { "code": null, "e": 3535, "s": 3478, "text": "// Function Prototypeint countSpecials(int[], int, int);" }, { "code": null, "e": 3589, "s": 3535, "text": "// } Driver Code Ends//User function Template for C++" }, { "code": null, "e": 3937, "s": 3589, "text": "/*Function to count number of elements with occurrence* exactly equal to floor(sizeof_array/K)* arr : input array* sizeof_array : number of array elements*/int countSpecials(int arr[], int sizeof_array, int K){ int f = floor(sizeof_array/K),p=0; for(int i=0;i<sizeof_array;i++) { int count; for(int j=0;j<sizeof_array;j++)" }, { "code": null, "e": 4081, "s": 3937, "text": " { if(arr[i]==arr[j]) count++ ; } if(count==f) p++; } // Your code here return p; }" }, { "code": null, "e": 4106, "s": 4081, "text": "// { Driver Code Starts." }, { "code": null, "e": 4650, "s": 4106, "text": "// Driver code to rest countSpecials functionint main() {// Testcase inputint testcase;cin >> testcase;while(testcase--){ // sizeof_array : number of array elements // K : as given in statement int sizeof_array, K; cin >> sizeof_array >> K; // array of size sizeof_array int arr[sizeof_array]; for(int i = 0;i<sizeof_array;i++){ cin >> arr[i]; } // calling function and printing count the occurrence cout << countSpecials(arr, sizeof_array, K) << endl; }return 0;} // } Driver Code Ends" }, { "code": null, "e": 4719, "s": 4650, "text": "Whats the problem in countspecial function..am unable to understand." }, { "code": null, "e": 4721, "s": 4719, "text": "0" }, { "code": null, "e": 4745, "s": 4721, "text": "hitentandon3 months ago" }, { "code": null, "e": 4753, "s": 4745, "text": "JS Sol:" }, { "code": null, "e": 5103, "s": 4753, "text": " let f = Math.floor(N/K), count = 0, cc=1;\n arr.sort();\n for(let i = 1; i < N; i++)\n if(arr[i]==arr[i-1])\n cc++;\n else if(cc===f)\n {\n count++;\n cc=1;\n }\n else\n cc=1;\n if(cc===f)\n count++;\n return count;" }, { "code": null, "e": 5112, "s": 5103, "text": "C++ Sol:" }, { "code": null, "e": 5400, "s": 5112, "text": " int f = floor(N/K), count = 0, cc=1;\n sort(arr, arr+N);\n for(int i = 1; i < N; i++)\n if(arr[i]==arr[i-1])\n cc++;\n else if(cc==f)\n {\n count++;\n cc=1;\n }\n else\n cc=1;\n if(cc==f)\n count++;\n return count;" }, { "code": null, "e": 5403, "s": 5400, "text": "+1" }, { "code": null, "e": 5436, "s": 5403, "text": "sourabhsingh191220014 months ago" }, { "code": null, "e": 5455, "s": 5436, "text": "Easy C++ Solution " }, { "code": null, "e": 5855, "s": 5455, "text": "int countSpecials(int arr[], int sizeof_array, int K){\n \n int f = floor(sizeof_array/K), cnt = 0;\n unordered_map<int,int>mp;\n \n // Your code here\n for(int i=0;i<sizeof_array;i++){\n if(mp.find(arr[i]) == mp.end()){\n mp[arr[i]]=1;\n }else\n mp[arr[i]]++;\n }\n for(auto &i:mp){\n if(i.second==f)\n cnt++;\n }\n \n return cnt;\n \n}" }, { "code": null, "e": 5857, "s": 5855, "text": "0" }, { "code": null, "e": 5881, "s": 5857, "text": "harshitd8914 months ago" }, { "code": null, "e": 6013, "s": 5881, "text": "int countSpecials(int arr[], int N, int K){ int f = floor(N/K), count = 0;int array[1000];for(int i=0;i<1000;i++){array[i]=0; }" }, { "code": null, "e": 6206, "s": 6013, "text": "for(int i=0;i<1000;i++){ if(i<N){ int p=arr[i]; array[p]=array[p]+1; } else{ break; }}for(int i=0;i<1000;i++){ if(array[i]==f){ count++; }} return count; } " }, { "code": null, "e": 6208, "s": 6206, "text": "0" }, { "code": null, "e": 6238, "s": 6208, "text": "ayushnautiyal11106 months ago" }, { "code": null, "e": 6546, "s": 6238, "text": "int countSpecials(int arr[], int sizeof_array, int K){ int f = floor(sizeof_array/K), count = 0; unordered_map<int,int>mp; for(int i=0;i<sizeof_array;i++){ mp[arr[i]]++; } for(auto it =mp.begin();it!=mp.end();it++){ if(it->second==f){ count++; } } return count;}" }, { "code": null, "e": 6692, "s": 6546, "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": 6728, "s": 6692, "text": " Login to access your submissions. " }, { "code": null, "e": 6738, "s": 6728, "text": "\nProblem\n" }, { "code": null, "e": 6748, "s": 6738, "text": "\nContest\n" }, { "code": null, "e": 6811, "s": 6748, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6959, "s": 6811, "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": 7167, "s": 6959, "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": 7273, "s": 7167, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to simulate pressing enter in html text input with Selenium?
We can simulate pressing enter in the html text input box with Selenium webdriver. We shall take the help of sendKeys method and pass Keys.ENTER as an argument to the method. Besides, we can pass Keys.RETURN as an argument to the method to perform the same task. Also, we have to import org.openqa.selenium.Keys package to the code for using the Keys class. Let us press ENTER/RETURN after entering some text inside the below input box. Code Implementation with Keys.ENTER. import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.By; import org.openqa.selenium.Keys; public class PressEnter{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://www.tutorialspoint.com/about/about_careers.htm"); // identify element WebElement l=driver.findElement(By.id("gsc-i-id1")); l.sendKeys("Selenium"); // press enter with sendKeys method and pass Keys.ENTER l.sendKeys(Keys.ENTER); driver.close(); } } Code Implementation with Keys.RETURN. import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.By; import org.openqa.selenium.Keys; public class PressReturn{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://www.tutorialspoint.com/about/about_careers.htm"); // identify element WebElement l=driver.findElement(By.id("gsc-i-id1")); l.sendKeys("Selenium"); // press enter with sendKeys method and pass Keys.RETURN l.sendKeys(Keys.RETURN); driver.close(); } }
[ { "code": null, "e": 1325, "s": 1062, "text": "We can simulate pressing enter in the html text input box with Selenium webdriver. We shall take the help of sendKeys method and pass Keys.ENTER as an argument to the method. Besides, we can pass Keys.RETURN as an argument to the method to perform the same task." }, { "code": null, "e": 1499, "s": 1325, "text": "Also, we have to import org.openqa.selenium.Keys package to the code for using the Keys class. Let us press ENTER/RETURN after entering some text inside the below input box." }, { "code": null, "e": 1536, "s": 1499, "text": "Code Implementation with Keys.ENTER." }, { "code": null, "e": 2259, "s": 1536, "text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.By;\nimport org.openqa.selenium.Keys;\npublic class PressEnter{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\");\n // identify element\n WebElement l=driver.findElement(By.id(\"gsc-i-id1\"));\n l.sendKeys(\"Selenium\");\n // press enter with sendKeys method and pass Keys.ENTER\n l.sendKeys(Keys.ENTER);\n driver.close();\n }\n}" }, { "code": null, "e": 2297, "s": 2259, "text": "Code Implementation with Keys.RETURN." }, { "code": null, "e": 3023, "s": 2297, "text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.By;\nimport org.openqa.selenium.Keys;\npublic class PressReturn{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\",\n\"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\");\n // identify element\n WebElement l=driver.findElement(By.id(\"gsc-i-id1\"));\n l.sendKeys(\"Selenium\");\n // press enter with sendKeys method and pass Keys.RETURN\n l.sendKeys(Keys.RETURN);\n driver.close();\n }\n}" } ]
C++ Program for Longest Common Subsequence
A subsequence is a sequence with the same order of the set of elements. For the sequence “stuv”, the subsequences are “stu”, “tuv”, “suv”,.... etc. For a string of length n, there can be 2n ways to create subsequence from the string. The longest common subsequence for the strings “ ABCDGH ” and “ AEDFHR ” is of length 3. Live Demo #include <iostream> #include <string.h> using namespace std; int max(int a, int b); int lcs(char* X, char* Y, int m, int n){ if (m == 0 || n == 0) return 0; if (X[m - 1] == Y[n - 1]) return 1 + lcs(X, Y, m - 1, n - 1); else return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); } int max(int a, int b){ return (a > b) ? a : b; } int main(){ char X[] = "AGGTAB"; char Y[] = "GXTXAYB"; int m = strlen(X); int n = strlen(Y); printf("Length of LCS is %d\n", lcs(X, Y, m, n)); return 0; } Length of LCS is 4
[ { "code": null, "e": 1210, "s": 1062, "text": "A subsequence is a sequence with the same order of the set of elements. For the sequence “stuv”, the subsequences are “stu”, “tuv”, “suv”,.... etc." }, { "code": null, "e": 1296, "s": 1210, "text": "For a string of length n, there can be 2n ways to create subsequence from the string." }, { "code": null, "e": 1385, "s": 1296, "text": "The longest common subsequence for the strings “ ABCDGH ” and “ AEDFHR ” is of length 3." }, { "code": null, "e": 1396, "s": 1385, "text": " Live Demo" }, { "code": null, "e": 1928, "s": 1396, "text": "#include <iostream>\n#include <string.h>\nusing namespace std;\nint max(int a, int b);\nint lcs(char* X, char* Y, int m, int n){\n if (m == 0 || n == 0)\n return 0;\n if (X[m - 1] == Y[n - 1])\n return 1 + lcs(X, Y, m - 1, n - 1);\n else\n return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n));\n}\nint max(int a, int b){\n return (a > b) ? a : b;\n}\nint main(){\n char X[] = \"AGGTAB\";\n char Y[] = \"GXTXAYB\";\n int m = strlen(X);\n int n = strlen(Y);\n printf(\"Length of LCS is %d\\n\", lcs(X, Y, m, n));\n return 0;\n}" }, { "code": null, "e": 1947, "s": 1928, "text": "Length of LCS is 4" } ]
MFC - Activex Control
An ActiveX control container is a parent program that supplies the environment for an ActiveX (formerly OLE) control to run. ActiveX control is a control using Microsoft ActiveX technologies. ActiveX control is a control using Microsoft ActiveX technologies. ActiveX is not a programming language, but rather a set of rules for how applications should share information. ActiveX is not a programming language, but rather a set of rules for how applications should share information. Programmers can develop ActiveX controls in a variety of languages, including C, C++, Visual Basic, and Java. Programmers can develop ActiveX controls in a variety of languages, including C, C++, Visual Basic, and Java. You can create an application capable of containing ActiveX controls with or without MFC, but it is much easier to do with MFC. You can create an application capable of containing ActiveX controls with or without MFC, but it is much easier to do with MFC. Let us look into simple example of add ActiveX controls in your MFC dialog based application. Step 1 − Right-click on the dialog in the designer window and select Insert ActiveX Control. Step 2 − Select the Microsoft Picture Clip Control and click OK. Step 3 − Resize the Picture control and in the Properties window, click the Picture field. Step 4 − Browse the folder that contains Pictures. Select any picture. Step 5 − When you run this application, you will see the following output. Let us have a look into another simple example. Step 1 − Right-click on the dialog in the designer window. Step 2 − Select Insert ActiveX Control. Step 3 − Select the Microsoft ProgressBar Control 6.0, click OK. Step 4 − Select the progress bar and set its Orientation in the Properties Window to 1 – ccOrientationVertical. Step 5 − Add control variable for Progress bar. Step 6 − Add the following code in the OnInitDialog() m_progBarCtrl.SetScrollRange(0,100,TRUE); m_progBarCtrl.put_Value(53); Step 7 − When you run this application again, you will see the progress bar in Vertical direction as well. Print Add Notes Bookmark this page
[ { "code": null, "e": 2192, "s": 2067, "text": "An ActiveX control container is a parent program that supplies the environment for an ActiveX (formerly OLE) control to run." }, { "code": null, "e": 2259, "s": 2192, "text": "ActiveX control is a control using Microsoft ActiveX technologies." }, { "code": null, "e": 2326, "s": 2259, "text": "ActiveX control is a control using Microsoft ActiveX technologies." }, { "code": null, "e": 2438, "s": 2326, "text": "ActiveX is not a programming language, but rather a set of rules for how applications should share information." }, { "code": null, "e": 2550, "s": 2438, "text": "ActiveX is not a programming language, but rather a set of rules for how applications should share information." }, { "code": null, "e": 2660, "s": 2550, "text": "Programmers can develop ActiveX controls in a variety of languages, including C, C++, Visual Basic, and Java." }, { "code": null, "e": 2770, "s": 2660, "text": "Programmers can develop ActiveX controls in a variety of languages, including C, C++, Visual Basic, and Java." }, { "code": null, "e": 2898, "s": 2770, "text": "You can create an application capable of containing ActiveX controls with or without MFC, but it is much easier to do with MFC." }, { "code": null, "e": 3026, "s": 2898, "text": "You can create an application capable of containing ActiveX controls with or without MFC, but it is much easier to do with MFC." }, { "code": null, "e": 3120, "s": 3026, "text": "Let us look into simple example of add ActiveX controls in your MFC dialog based application." }, { "code": null, "e": 3213, "s": 3120, "text": "Step 1 − Right-click on the dialog in the designer window and select Insert ActiveX Control." }, { "code": null, "e": 3278, "s": 3213, "text": "Step 2 − Select the Microsoft Picture Clip Control and click OK." }, { "code": null, "e": 3369, "s": 3278, "text": "Step 3 − Resize the Picture control and in the Properties window, click the Picture field." }, { "code": null, "e": 3440, "s": 3369, "text": "Step 4 − Browse the folder that contains Pictures. Select any picture." }, { "code": null, "e": 3515, "s": 3440, "text": "Step 5 − When you run this application, you will see the following output." }, { "code": null, "e": 3563, "s": 3515, "text": "Let us have a look into another simple example." }, { "code": null, "e": 3622, "s": 3563, "text": "Step 1 − Right-click on the dialog in the designer window." }, { "code": null, "e": 3662, "s": 3622, "text": "Step 2 − Select Insert ActiveX Control." }, { "code": null, "e": 3727, "s": 3662, "text": "Step 3 − Select the Microsoft ProgressBar Control 6.0, click OK." }, { "code": null, "e": 3839, "s": 3727, "text": "Step 4 − Select the progress bar and set its Orientation in the Properties Window to 1 – ccOrientationVertical." }, { "code": null, "e": 3887, "s": 3839, "text": "Step 5 − Add control variable for Progress bar." }, { "code": null, "e": 3941, "s": 3887, "text": "Step 6 − Add the following code in the OnInitDialog()" }, { "code": null, "e": 4012, "s": 3941, "text": "m_progBarCtrl.SetScrollRange(0,100,TRUE);\nm_progBarCtrl.put_Value(53);" }, { "code": null, "e": 4119, "s": 4012, "text": "Step 7 − When you run this application again, you will see the progress bar in Vertical direction as well." }, { "code": null, "e": 4126, "s": 4119, "text": " Print" }, { "code": null, "e": 4137, "s": 4126, "text": " Add Notes" } ]
Anagram checking in Python using collections.Counter() - GeeksforGeeks
31 Oct, 2017 Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other. Examples: Input : str1 = “abcd”, str2 = “dabc” Output : True Input : str1 = “abcf”, str2 = “kabc” Output : False This problem has existing solution please refer Check whether two strings are anagram of each other link. We will solve this problem in python in a single line using collections.Counter() module. # Python code to check if two strings are# anagramfrom collections import Counter def anagram(input1, input2): # Counter() returns a dictionary data # structure which contains characters # of input as key and their frequencies # as it's corresponding value return Counter(input1) == Counter(input2) # Driver functionif __name__ == "__main__": input1 = 'abcd' input2 = 'dcab' print anagram(input1, input2) Output: True How dictionary comparison works in python ?If we have two dictionary data structures in python dict1 = {‘a’:2,’b’:3,’c’:1} and dict2 = {‘b’:3,’c’:1,’a’:2} and we compare both of them like dict1=dict2 then it will result True. In python ordinary dictionary data structure does not follow any ordering of keys, when we compare two dictionaries then it compares three checks in order number of keys (if they don’t match, the dicts are not equal), names of keys (if they don’t match, they’re not equal) and value of each key (they have to be ‘==’, too). This article is contributed by Shashank Mishra (Gullu). 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. anagram frequency-counting Python Strings Strings anagram Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Reverse a string in Java Write a program to reverse an array or string Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string C++ Data Types
[ { "code": null, "e": 23901, "s": 23873, "text": "\n31 Oct, 2017" }, { "code": null, "e": 24164, "s": 23901, "text": "Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other." }, { "code": null, "e": 24174, "s": 24164, "text": "Examples:" }, { "code": null, "e": 24279, "s": 24174, "text": "Input : str1 = “abcd”, str2 = “dabc”\nOutput : True\n\nInput : str1 = “abcf”, str2 = “kabc”\nOutput : False\n" }, { "code": null, "e": 24475, "s": 24279, "text": "This problem has existing solution please refer Check whether two strings are anagram of each other link. We will solve this problem in python in a single line using collections.Counter() module." }, { "code": "# Python code to check if two strings are# anagramfrom collections import Counter def anagram(input1, input2): # Counter() returns a dictionary data # structure which contains characters # of input as key and their frequencies # as it's corresponding value return Counter(input1) == Counter(input2) # Driver functionif __name__ == \"__main__\": input1 = 'abcd' input2 = 'dcab' print anagram(input1, input2)", "e": 24909, "s": 24475, "text": null }, { "code": null, "e": 24917, "s": 24909, "text": "Output:" }, { "code": null, "e": 24923, "s": 24917, "text": "True\n" }, { "code": null, "e": 25473, "s": 24923, "text": "How dictionary comparison works in python ?If we have two dictionary data structures in python dict1 = {‘a’:2,’b’:3,’c’:1} and dict2 = {‘b’:3,’c’:1,’a’:2} and we compare both of them like dict1=dict2 then it will result True. In python ordinary dictionary data structure does not follow any ordering of keys, when we compare two dictionaries then it compares three checks in order number of keys (if they don’t match, the dicts are not equal), names of keys (if they don’t match, they’re not equal) and value of each key (they have to be ‘==’, too)." }, { "code": null, "e": 25784, "s": 25473, "text": "This article is contributed by Shashank Mishra (Gullu). 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": 25909, "s": 25784, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 25917, "s": 25909, "text": "anagram" }, { "code": null, "e": 25936, "s": 25917, "text": "frequency-counting" }, { "code": null, "e": 25943, "s": 25936, "text": "Python" }, { "code": null, "e": 25951, "s": 25943, "text": "Strings" }, { "code": null, "e": 25959, "s": 25951, "text": "Strings" }, { "code": null, "e": 25967, "s": 25959, "text": "anagram" }, { "code": null, "e": 26065, "s": 25967, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26074, "s": 26065, "text": "Comments" }, { "code": null, "e": 26087, "s": 26074, "text": "Old Comments" }, { "code": null, "e": 26119, "s": 26087, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26175, "s": 26119, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26217, "s": 26175, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26259, "s": 26217, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26295, "s": 26259, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 26320, "s": 26295, "text": "Reverse a string in Java" }, { "code": null, "e": 26366, "s": 26320, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 26400, "s": 26366, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 26460, "s": 26400, "text": "Write a program to print all permutations of a given string" } ]
Check if a given number N has at least one odd divisor not exceeding N - 1 - GeeksforGeeks
23 Nov, 2021 Given a positive integer N, the task is to check if the given number N has at least 1 odd divisor from the range [2, N – 1] or not. If found to be true, then print “Yes”. Otherwise, print “No”. Examples: Input: N = 10Output: YesExplanation:10 has 5 as the odd divisor. Therefore, print Yes. Input: N = 8Output: No Approach: The idea to solve the given problem is to iterate through all possible odd divisors over the range [3, sqrt(N)] and if there exists any such divisor, then print “Yes”. Otherwise, print “No”. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check whether N// has at least one odd divisor// not exceeding N - 1 or notstring oddDivisor(int N){ // Stores the value of N int X = N; // Reduce the given number // N by dividing it by 2 while (N % 2 == 0) { N /= 2; } for (int i = 3; i * i <= X; i += 2) { // If N is divisible by // an odd divisor i if (N % i == 0) { return "Yes"; } } // Check if N is an odd divisor after // reducing N by dividing it by 2 if (N != X) return "Yes"; // Otherwise return "No";} // Driver Codeint main(){ int N = 10; // Function Call cout << oddDivisor(N); return 0;} /*package whatever //do not write package name here */import java.io.*; class GFG { // Function to check whether N // has at least one odd divisor // not exceeding N - 1 or not public static String oddDivisor(int N) { // Stores the value of N int X = N; // Reduce the given number // N by dividing it by 2 while (N % 2 == 0) { N /= 2; } for (int i = 3; i * i <= X; i += 2) { // If N is divisible by // an odd divisor i if (N % i == 0) { return "Yes"; } } // Check if N is an odd divisor after // reducing N by dividing it by 2 if (N != X) { return "Yes"; } // Otherwise return "No"; } // Driver Code public static void main(String[] args) { int N = 10; // Function Call System.out.println(oddDivisor(N)); }} // This code is contributed by aditya7409. # Python program for the above approach # Function to check whether N# has at least one odd divisor# not exceeding N - 1 or notdef oddDivisor(N): # Stores the value of N X = N # Reduce the given number # N by dividing it by 2 while (N % 2 == 0): N //= 2 i = 3 while(i * i <= X): # If N is divisible by # an odd divisor i if (N % i == 0): return "Yes" i += 2 # Check if N is an odd divisor after # reducing N by dividing it by 2 if (N != X): return "Yes" # Otherwise return "No" # Driver Code N = 10# Function Callprint(oddDivisor(N)) # This code is contributed by shubhamsingh10 // C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to check whether N // has at least one odd divisor // not exceeding N - 1 or not public static string oddDivisor(int N) { // Stores the value of N int X = N; // Reduce the given number // N by dividing it by 2 while (N % 2 == 0) { N /= 2; } for (int i = 3; i * i <= X; i += 2) { // If N is divisible by // an odd divisor i if (N % i == 0) { return "Yes"; } } // Check if N is an odd divisor after // reducing N by dividing it by 2 if (N != X) { return "Yes"; } // Otherwise return "No"; } // Driver Code static public void Main() { int N = 10; // Function Call Console.Write(oddDivisor(N)); }} // This code is contributed by sanjoy_62. <script> // javascript program for the above approach // Function to check whether N// has at least one odd divisor// not exceeding N - 1 or notfunction oddDivisor(N){ // Stores the value of N var X = N; var i; // Reduce the given number // N by dividing it by 2 while (N % 2 == 0) { N /= 2; } for (i = 3; i * i <= X; i += 2) { // If N is divisible by // an odd divisor i if (N % i == 0) { return "Yes"; } } // Check if N is an odd divisor after // reducing N by dividing it by 2 if (N != X) return "Yes"; // Otherwise return "No";} // Driver Code var N = 10; // Function Call document.write(oddDivisor(N)); // This code is contributed by ipg2016107.</script> Yes Time Complexity: O(√N)Auxiliary Space: O(1) Another approach : The only possibility for any number n>1 not to have an odd divisor is for n to be a power of two. To check power of two, we can use this approach n&(n−1) , the result will be zero only if n is a power of two. C++ Java #include <iostream>using namespace std; void oddDivisor(int n){ //checking power of two or not if ((n & (n - 1)) == 0) { cout << "NO" << endl; } else { cout << "YES" << endl; }} int main() { int N = 10; // Function Call oddDivisor(N); return 0;} /*package whatever //do not write package name here */ import java.io.*; class GFG { public static void main (String[] args) { int N = 10; // Function Call oddDivisor(N); } static void oddDivisor(int n){ //checking power of two or not if ((n & (n - 1)) == 0) { System.out.println("NO"); } else { System.out.println("YES"); }}} YES aditya7409 SHUBHAMSINGH10 sanjoy_62 ipg2016107 abhi0709singh divisors Mathematical Technical Scripter Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Merge two sorted arrays Prime Numbers Modulo Operator (%) in C/C++ with Examples Program for Decimal to Binary Conversion Program to find sum of elements in a given array Modulo 10^9+7 (1000000007) The Knight's tour problem | Backtracking-1 Program for factorial of a number Operators in C / C++ Minimum number of jumps to reach end
[ { "code": null, "e": 24531, "s": 24503, "text": "\n23 Nov, 2021" }, { "code": null, "e": 24725, "s": 24531, "text": "Given a positive integer N, the task is to check if the given number N has at least 1 odd divisor from the range [2, N – 1] or not. If found to be true, then print “Yes”. Otherwise, print “No”." }, { "code": null, "e": 24735, "s": 24725, "text": "Examples:" }, { "code": null, "e": 24822, "s": 24735, "text": "Input: N = 10Output: YesExplanation:10 has 5 as the odd divisor. Therefore, print Yes." }, { "code": null, "e": 24845, "s": 24822, "text": "Input: N = 8Output: No" }, { "code": null, "e": 25047, "s": 24845, "text": "Approach: The idea to solve the given problem is to iterate through all possible odd divisors over the range [3, sqrt(N)] and if there exists any such divisor, then print “Yes”. Otherwise, print “No”. " }, { "code": null, "e": 25098, "s": 25047, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25102, "s": 25098, "text": "C++" }, { "code": null, "e": 25107, "s": 25102, "text": "Java" }, { "code": null, "e": 25115, "s": 25107, "text": "Python3" }, { "code": null, "e": 25118, "s": 25115, "text": "C#" }, { "code": null, "e": 25129, "s": 25118, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check whether N// has at least one odd divisor// not exceeding N - 1 or notstring oddDivisor(int N){ // Stores the value of N int X = N; // Reduce the given number // N by dividing it by 2 while (N % 2 == 0) { N /= 2; } for (int i = 3; i * i <= X; i += 2) { // If N is divisible by // an odd divisor i if (N % i == 0) { return \"Yes\"; } } // Check if N is an odd divisor after // reducing N by dividing it by 2 if (N != X) return \"Yes\"; // Otherwise return \"No\";} // Driver Codeint main(){ int N = 10; // Function Call cout << oddDivisor(N); return 0;}", "e": 25889, "s": 25129, "text": null }, { "code": "/*package whatever //do not write package name here */import java.io.*; class GFG { // Function to check whether N // has at least one odd divisor // not exceeding N - 1 or not public static String oddDivisor(int N) { // Stores the value of N int X = N; // Reduce the given number // N by dividing it by 2 while (N % 2 == 0) { N /= 2; } for (int i = 3; i * i <= X; i += 2) { // If N is divisible by // an odd divisor i if (N % i == 0) { return \"Yes\"; } } // Check if N is an odd divisor after // reducing N by dividing it by 2 if (N != X) { return \"Yes\"; } // Otherwise return \"No\"; } // Driver Code public static void main(String[] args) { int N = 10; // Function Call System.out.println(oddDivisor(N)); }} // This code is contributed by aditya7409.", "e": 26897, "s": 25889, "text": null }, { "code": "# Python program for the above approach # Function to check whether N# has at least one odd divisor# not exceeding N - 1 or notdef oddDivisor(N): # Stores the value of N X = N # Reduce the given number # N by dividing it by 2 while (N % 2 == 0): N //= 2 i = 3 while(i * i <= X): # If N is divisible by # an odd divisor i if (N % i == 0): return \"Yes\" i += 2 # Check if N is an odd divisor after # reducing N by dividing it by 2 if (N != X): return \"Yes\" # Otherwise return \"No\" # Driver Code N = 10# Function Callprint(oddDivisor(N)) # This code is contributed by shubhamsingh10", "e": 27603, "s": 26897, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to check whether N // has at least one odd divisor // not exceeding N - 1 or not public static string oddDivisor(int N) { // Stores the value of N int X = N; // Reduce the given number // N by dividing it by 2 while (N % 2 == 0) { N /= 2; } for (int i = 3; i * i <= X; i += 2) { // If N is divisible by // an odd divisor i if (N % i == 0) { return \"Yes\"; } } // Check if N is an odd divisor after // reducing N by dividing it by 2 if (N != X) { return \"Yes\"; } // Otherwise return \"No\"; } // Driver Code static public void Main() { int N = 10; // Function Call Console.Write(oddDivisor(N)); }} // This code is contributed by sanjoy_62.", "e": 28452, "s": 27603, "text": null }, { "code": "<script> // javascript program for the above approach // Function to check whether N// has at least one odd divisor// not exceeding N - 1 or notfunction oddDivisor(N){ // Stores the value of N var X = N; var i; // Reduce the given number // N by dividing it by 2 while (N % 2 == 0) { N /= 2; } for (i = 3; i * i <= X; i += 2) { // If N is divisible by // an odd divisor i if (N % i == 0) { return \"Yes\"; } } // Check if N is an odd divisor after // reducing N by dividing it by 2 if (N != X) return \"Yes\"; // Otherwise return \"No\";} // Driver Code var N = 10; // Function Call document.write(oddDivisor(N)); // This code is contributed by ipg2016107.</script>", "e": 29227, "s": 28452, "text": null }, { "code": null, "e": 29231, "s": 29227, "text": "Yes" }, { "code": null, "e": 29275, "s": 29231, "text": "Time Complexity: O(√N)Auxiliary Space: O(1)" }, { "code": null, "e": 29392, "s": 29275, "text": "Another approach : The only possibility for any number n>1 not to have an odd divisor is for n to be a power of two." }, { "code": null, "e": 29441, "s": 29392, "text": "To check power of two, we can use this approach " }, { "code": null, "e": 29504, "s": 29441, "text": "n&(n−1) , the result will be zero only if n is a power of two." }, { "code": null, "e": 29508, "s": 29504, "text": "C++" }, { "code": null, "e": 29513, "s": 29508, "text": "Java" }, { "code": "#include <iostream>using namespace std; void oddDivisor(int n){ //checking power of two or not if ((n & (n - 1)) == 0) { cout << \"NO\" << endl; } else { cout << \"YES\" << endl; }} int main() { int N = 10; // Function Call oddDivisor(N); return 0;}", "e": 29797, "s": 29513, "text": null }, { "code": "/*package whatever //do not write package name here */ import java.io.*; class GFG { public static void main (String[] args) { int N = 10; // Function Call oddDivisor(N); } static void oddDivisor(int n){ //checking power of two or not if ((n & (n - 1)) == 0) { System.out.println(\"NO\"); } else { System.out.println(\"YES\"); }}}", "e": 30171, "s": 29797, "text": null }, { "code": null, "e": 30175, "s": 30171, "text": "YES" }, { "code": null, "e": 30186, "s": 30175, "text": "aditya7409" }, { "code": null, "e": 30201, "s": 30186, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 30211, "s": 30201, "text": "sanjoy_62" }, { "code": null, "e": 30222, "s": 30211, "text": "ipg2016107" }, { "code": null, "e": 30236, "s": 30222, "text": "abhi0709singh" }, { "code": null, "e": 30245, "s": 30236, "text": "divisors" }, { "code": null, "e": 30258, "s": 30245, "text": "Mathematical" }, { "code": null, "e": 30277, "s": 30258, "text": "Technical Scripter" }, { "code": null, "e": 30290, "s": 30277, "text": "Mathematical" }, { "code": null, "e": 30388, "s": 30290, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30397, "s": 30388, "text": "Comments" }, { "code": null, "e": 30410, "s": 30397, "text": "Old Comments" }, { "code": null, "e": 30434, "s": 30410, "text": "Merge two sorted arrays" }, { "code": null, "e": 30448, "s": 30434, "text": "Prime Numbers" }, { "code": null, "e": 30491, "s": 30448, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 30532, "s": 30491, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 30581, "s": 30532, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 30608, "s": 30581, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 30651, "s": 30608, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 30685, "s": 30651, "text": "Program for factorial of a number" }, { "code": null, "e": 30706, "s": 30685, "text": "Operators in C / C++" } ]
Multiplication of two Matrices using Java
Matrix multiplication leads to a new matrix by multiplying 2 matrices. But this is only possible if the columns of the first matrix are equal to the rows of the second matrix. An example of matrix multiplication with square matrices is given as follows. Live Demo public class Example { public static void main(String args[]) { int n = 3; int[][] a = { {5, 2, 3}, {2, 6, 3}, {6, 9, 1} }; int[][] b = { {2, 7, 5}, {1, 4, 3}, {1, 2, 1} }; int[][] c = new int[n][n]; System.out.println("Matrix A:"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(a[i][j] + " "); } System.out.println(); } System.out.println("Matrix B:"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(b[i][j] + " "); } System.out.println(); } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++){ for (int k = 0; k < n; k++) { c[i][j] = c[i][j] + a[i][k] * b[k][j]; } } } System.out.println("The product of two matrices is:"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(c[i][j] + " "); } System.out.println(); } } } Matrix A: 5 2 3 2 6 3 6 9 1 Matrix B: 2 7 5 1 4 3 1 2 1 The product of two matrices is: 15 49 34 13 44 31 22 80 58
[ { "code": null, "e": 1316, "s": 1062, "text": "Matrix multiplication leads to a new matrix by multiplying 2 matrices. But this is only possible if the columns of the first matrix are equal to the rows of the second matrix. An example of matrix multiplication with square matrices is given as follows." }, { "code": null, "e": 1327, "s": 1316, "text": " Live Demo" }, { "code": null, "e": 2413, "s": 1327, "text": "public class Example {\n public static void main(String args[]) {\n int n = 3;\n int[][] a = { {5, 2, 3}, {2, 6, 3}, {6, 9, 1} };\n int[][] b = { {2, 7, 5}, {1, 4, 3}, {1, 2, 1} };\n int[][] c = new int[n][n];\n System.out.println(\"Matrix A:\");\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n System.out.print(a[i][j] + \" \");\n }\n System.out.println();\n }\n System.out.println(\"Matrix B:\");\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n System.out.print(b[i][j] + \" \");\n }\n System.out.println();\n }\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++){\n for (int k = 0; k < n; k++) {\n c[i][j] = c[i][j] + a[i][k] * b[k][j];\n }\n }\n }\n System.out.println(\"The product of two matrices is:\");\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n System.out.print(c[i][j] + \" \");\n }\n System.out.println();\n }\n }\n}" }, { "code": null, "e": 2528, "s": 2413, "text": "Matrix A:\n5 2 3\n2 6 3\n6 9 1\nMatrix B:\n2 7 5\n1 4 3\n1 2 1\nThe product of two matrices is:\n15 49 34\n13 44 31\n22 80 58" } ]
How to declare a pointer to a function in C?
A pointer is a variable whose value is the address of another variable or memory block, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable or block address. Datatype *variable_name Begin. Define a function show. Declare a variable x of the integer datatype. Print the value of varisble x. Declare a pointer p of the integer datatype. Define p as the pointer to the address of show() function. Initialize value to p pointer. End. This is a simple example in C to understand the concept a pointer to a function. #include void show(int x) { printf("Value of x is %d\n", x); } int main() { void (*p)(int); // declaring a pointer p = &show; // p is the pointer to the show() (*p)(7); //initializing values. return 0; } Value of x is 7.
[ { "code": null, "e": 1309, "s": 1062, "text": "A pointer is a variable whose value is the address of another variable or memory block, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable or block address." }, { "code": null, "e": 1333, "s": 1309, "text": "Datatype *variable_name" }, { "code": null, "e": 1605, "s": 1333, "text": "Begin.\n Define a function show.\n Declare a variable x of the integer datatype.\n Print the value of varisble x.\n Declare a pointer p of the integer datatype.\n Define p as the pointer to the address of show() function.\n Initialize value to p pointer.\nEnd." }, { "code": null, "e": 1686, "s": 1605, "text": "This is a simple example in C to understand the concept a pointer to a function." }, { "code": null, "e": 1905, "s": 1686, "text": "#include\nvoid show(int x)\n{\n printf(\"Value of x is %d\\n\", x);\n}\nint main()\n{\n void (*p)(int); // declaring a pointer\n p = &show; // p is the pointer to the show()\n (*p)(7); //initializing values.\n return 0;\n}" }, { "code": null, "e": 1922, "s": 1905, "text": "Value of x is 7." } ]
Importance of join() method in Java?
A join() is a final method of Thread class and it can be used to join the start of a thread's execution to the end of another thread's execution so that a thread will not start running until another thread has ended. If the join() method is called on a thread instance, the currently running thread will block until the thread instance has finished executing. public final void join() throws InterruptedException public class JoinTest extends Thread { public void run() { for(int i=1; i <= 3; i++) { try { Thread.sleep(1000); } catch(Exception e) { System.out.println(e); } System.out.println("TutorialsPoint "+ i); } } public static void main(String args[]) { JoinTest t1 = new JoinTest(); JoinTest t2 = new JoinTest(); JoinTest t3 = new JoinTest(); t1.start(); try { t1.join(); // calling join() method } catch(Exception e) { System.out.println(e); } t2.start(); t3.start(); } } TutorialsPoint 1 TutorialsPoint 2 TutorialsPoint 3 TutorialsPoint 1 TutorialsPoint 1 TutorialsPoint 2 TutorialsPoint 2 TutorialsPoint 3 TutorialsPoint 3
[ { "code": null, "e": 1422, "s": 1062, "text": "A join() is a final method of Thread class and it can be used to join the start of a thread's execution to the end of another thread's execution so that a thread will not start running until another thread has ended. If the join() method is called on a thread instance, the currently running thread will block until the thread instance has finished executing." }, { "code": null, "e": 1475, "s": 1422, "text": "public final void join() throws InterruptedException" }, { "code": null, "e": 2099, "s": 1475, "text": "public class JoinTest extends Thread {\n public void run() {\n for(int i=1; i <= 3; i++) {\n try {\n Thread.sleep(1000);\n } catch(Exception e) {\n System.out.println(e);\n }\n System.out.println(\"TutorialsPoint \"+ i);\n }\n }\n public static void main(String args[]) {\n JoinTest t1 = new JoinTest();\n JoinTest t2 = new JoinTest();\n JoinTest t3 = new JoinTest();\n t1.start();\n try {\n t1.join(); // calling join() method\n } catch(Exception e) {\n System.out.println(e);\n }\n t2.start();\n t3.start();\n }\n}" }, { "code": null, "e": 2252, "s": 2099, "text": "TutorialsPoint 1\nTutorialsPoint 2\nTutorialsPoint 3\nTutorialsPoint 1\nTutorialsPoint 1\nTutorialsPoint 2\nTutorialsPoint 2\nTutorialsPoint 3\nTutorialsPoint 3" } ]
Using TensorFlow Serving's RESTful API | Towards Data Science
TensorFlow-Serving is a useful tool that, due to its recency and rather niche use case, does not have much in the way of online tutorials. Here, I’ll showcase a solution demonstrating an end-to-end implementation of TensorFlow-Serving on an image-based model, covering everything from converting images to Base64 to integrating TensorFlow Model Server with a deep neural network. In this tutorial, a minimum working example is provided — this implementation can easily be extended to include Docker containers, Bazel builds, batched inferences, and model decoupling. The main focus here is to understand the general requirements for working with TensorFlow-Serving, independent of any optional bells and whistles. The RESTful version of TensorFlow-Serving is used, as opposed to the gRPC version, and we implement the predict function though classify and regress can also be used. If you would like to view this tutorial in a Jupyter Notebook, please click here. At its most basic level, TensorFlow-Serving allows developers to integrate client requests and data with deep learning models served independently of client systems. Benefits of this include clients being able to make inferences on data without actually having to install TensorFlow or even have any contact with the actual model, and the ability to serve multiple clients with one instance of a model. Our pipeline will look like this: Note especially that the image must pass from the client to the server as a Base64 encoded string. This is because JSON has no other way to represent images (besides an array representation of a tensor, and that gets out of hand very quickly). The image must also pass from the ProtoBuf to the Generator as a tensor. This can be modified, but it is best to keep any pre- and post-processing decoupled from the model itself. Exporting a TensorFlow model for serving is probably the most confusing part of the process, since there are a few steps involved. Export graph to ProtoBuf format. This saves the GraphDef and variables, and represents the trained model. In order to export an image-based model, we have to inject bitstring conversion layers into the beginning and ending of the graph, since we require our inference function to deal only in tensors.Wrap the ProtoBuf in a SavedModel. This step is necessary because TensorFlow-Serving’s RESTful API is implemented through a SavedModelBuilder. We’ll import our GraphDef, then extract the TensorInfo of the input and output to define our PREDICT signature definition. Export graph to ProtoBuf format. This saves the GraphDef and variables, and represents the trained model. In order to export an image-based model, we have to inject bitstring conversion layers into the beginning and ending of the graph, since we require our inference function to deal only in tensors. Wrap the ProtoBuf in a SavedModel. This step is necessary because TensorFlow-Serving’s RESTful API is implemented through a SavedModelBuilder. We’ll import our GraphDef, then extract the TensorInfo of the input and output to define our PREDICT signature definition. We’ll use CycleGAN as a usage example. First, import some useful libraries: import tensorflow as tfimport argparseimport syssys.path.insert(0, “../CycleGAN-TensorFlow”)import model Here, we instantiate a CycleGAN and inject our first layer. graph = tf.Graph()with graph.as_default(): # Instantiate a CycleGAN cycle_gan = model.CycleGAN(ngf=64, norm="instance", image_size=64) # Create placeholder for image bitstring # This is the injection of the input bitstring layer input_bytes = tf.placeholder(tf.string, shape=[], name="input_bytes") Next, we preprocess the bitstring to a float tensor batch so it can be used in the model. with graph.as_default(): input_bytes = tf.reshape(input_bytes, []) # Transform bitstring to uint8 tensor input_tensor = tf.image.decode_png(input_bytes, channels=3) # Convert to float32 tensor input_tensor = tf.image.convert_image_dtype(input_tensor, dtype=tf.float32) # Ensure tensor has correct shape input_tensor = tf.reshape(input_tensor, [64, 64, 3]) # CycleGAN's inference function accepts a batch of images # So expand the single tensor into a batch of 1 input_tensor = tf.expand_dims(input_tensor, 0) Then, we feed the tensor to the model and save its output. with graph.as_default(): # Get style transferred tensor output_tensor = cycle_gan.G.sample(input_tensor) Post-inference, we convert the float tensor back to a bitstring. This is the injection of the output layer: with graph.as_default(): # Convert to uint8 tensor output_tensor = tf.image.convert_image_dtype(output_tensor, tf.uint8) # Remove the batch dimension output_tensor = tf.squeeze(output_tensor, [0]) # Transform uint8 tensor to bitstring output_bytes = tf.image.encode_png(output_tensor) output_bytes = tf.identity(output_bytes, name="output_bytes") # Instantiate a Saver saver = tf.train.Saver() Now that we have injected the bitstring layers into our model, we will load our train checkpoints and save the graph as a ProtoBuf. Prior to coding this server, I trained CycleGAN for 10,000 steps and saved the checkpoint file on my local machine, which I access in this session. # Start a TensorFlow sessionwith tf.Session(graph=graph) as sess: sess.run(tf.global_variables_initializer()) # Access variables and weights from last checkpoint latest_ckpt = tf.train.latest_checkpoint("../CycleGAN-TensorFlow/checkpoints/20180628-1208") saver.restore(sess, latest_ckpt) # Export graph to ProtoBuf output_graph_def = tf.graph_util.convert_variables_to_constants(sess, graph.as_graph_def(), [output_bytes.op.name]) tf.train.write_graph(output_graph_def, "../CycleGAN-TensorFlow/protobufs", "model_v1", as_text=False) With that, we’ve completed step one! In step two, we will wrap the ProtoBuf in a SavedModel to use the RESTful API. # Instantiate a SavedModelBuilder# Note that the serve directory is REQUIRED to have a model version subdirectorybuilder = tf.saved_model.builder.SavedModelBuilder("serve/1")# Read in ProtoBuf filewith tf.gfile.GFile("../CycleGAN-TensorFlow/protobufs/model_v1", "rb") as protobuf_file: graph_def = tf.GraphDef() graph_def.ParseFromString(protobuf_file.read())# Get input and output tensors from GraphDef# These are our injected bitstring layers[inp, out] = tf.import_graph_def(graph_def, name="", return_elements=["input_bytes:0", "output_bytes:0"]) Next, we define our signature definition, which expects the TensorInfo of the input and output to the model. When we save the model, we’ll get a “No assets” message, but that’s okay because our graph and variables were already saved in the ProtoBuf. # Start a TensorFlow session with our saved graphwith tf.Session(graph=out.graph) as sess: # Signature_definition expects a batch # So we'll turn the output bitstring into a batch of 1 element out = tf.expand_dims(out, 0) # Build prototypes of input and output bitstrings input_bytes = tf.saved_model.utils.build_tensor_info(inp) output_bytes = tf.saved_model.utils.build_tensor_info(out) # Create signature for prediction signature_definition = tf.saved_model.signature_def_utils.build_signature_def( inputs={"input_bytes": input_bytes}, outputs={"output_bytes": output_bytes}, method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME) # Add meta-information builder.add_meta_graph_and_variables( sess, [tf.saved_model.tag_constants.SERVING], signature_def_map={ tf.saved_model.signature_constants. DEFAULT_SERVING_SIGNATURE_DEF_KEY: signature_definition })# Create the SavedModelbuilder.save() And that’s it! Returned on the command line is the path to our SavedModel, which is used to build the TensorFlow Model Server. Our “variables” folder inside serve/1 will be empty, but that is okay because our variables were already saved in the ProtoBuf. As of July 2018, Python 3 is not officially supported with TensorFlow Serving, but someone made a solution. Install the Python 3 TensorFlow Serving API with: pip install tensorflow-serving-api-python3 Now, we can run this TensorFlow Model Server from bash with the command: tensorflow_model_server --rest_api_port=8501 --model_name=saved_model --model_base_path=$(path) Where $(path) is the path to the serve directory. In my case, it is /mnt/c/Users/Tyler/Desktop/tendies/minimum_working_example/serve. The client’s job is to accept an image as input, convert it to Base64, pass it to the server using JSON, and decode the response. First, import some useful libraries: import base64import requestsimport jsonimport argparse We will be performing style transfer from an image of Gaussian noise to an image of sinusoidal noise. Here’s the Gaussian image: First, we’ll open the image and convert it to Base64. # Open and read image as bitstringinput_image = open("images/gaussian.png", "rb").read()print("Raw bitstring: " + str(input_image[:10]) + " ... " + str(input_image[-10:]))# Encode image in b64encoded_input_string = base64.b64encode(input_image)input_string = encoded_input_string.decode("utf-8")print("Base64 encoded string: " + input_string[:10] + " ... " + input_string[-10:]) JSON data sent to our TensorFlow Model Server has to be structured in a very particular way. This method will be slightly different for classification and regression. For image prediction calls, our JSON body must look like this: { "instances": [ {"b64": "iVBORw"}, {"b64": "pT4rmN"}, {"b64": "w0KGg2"} ]} Since we’re only sending one image to the server, it’s pretty simple. We can create our JSON data like so: # Wrap bitstring in JSONinstance = [{"b64": input_string}]data = json.dumps({"instances": instance})print(data[:30] + " ... " + data[-10:]) This is all we need to send our POST request to the TensorFlow Model Server. This is a synchronous call, so the client will pause until it receives a response from the server (useful to know when you’re wondering why your code has stopped after POSTing a very large image). json_response = requests.post("http://localhost:8501/v1/models/saved_model:predict", data=data) To interpret the response, we do the above steps in the reverse order. To grab our base64-encoded image from the JSON response, we have to access: The value corresponding to “predictions” in the response dictionary.The first entry in the resultant array.The value corresponding to “b64” in the resultant dictionary. The value corresponding to “predictions” in the response dictionary. The first entry in the resultant array. The value corresponding to “b64” in the resultant dictionary. Then, we’ll decode that value to a raw bitstring. # Extract text from JSONresponse = json.loads(json_response.text)# Interpret bitstring outputresponse_string = response["predictions"][0]["b64"]print("Base64 encoded string: " + response_string[:10] + " ... " + response_string[-10:])# Decode bitstringencoded_response_string = response_string.encode("utf-8")response_image = base64.b64decode(encoded_response_string)print("Raw bitstring: " + str(response_image[:10]) + " ... " + str(response_image[-10:]))# Save inferred imagewith open("images/sinusoidal.png", "wb") as output_file: output_file.write(response_image) Success! Here’s the resultant image, which imposes a sinusoidal noise pattern on our original image. Thanks for following along with this tutorial; I hope it helped you out! This Notebook was built on the minimum working example of my TensorFlow Distributed Image Serving library, which you can download here. If you are interested in integrating this library with the TensorFlow Object Detection API or even your own model, check out the sequel to this article. For more blog posts and information about me, please visit my website.
[ { "code": null, "e": 552, "s": 172, "text": "TensorFlow-Serving is a useful tool that, due to its recency and rather niche use case, does not have much in the way of online tutorials. Here, I’ll showcase a solution demonstrating an end-to-end implementation of TensorFlow-Serving on an image-based model, covering everything from converting images to Base64 to integrating TensorFlow Model Server with a deep neural network." }, { "code": null, "e": 1053, "s": 552, "text": "In this tutorial, a minimum working example is provided — this implementation can easily be extended to include Docker containers, Bazel builds, batched inferences, and model decoupling. The main focus here is to understand the general requirements for working with TensorFlow-Serving, independent of any optional bells and whistles. The RESTful version of TensorFlow-Serving is used, as opposed to the gRPC version, and we implement the predict function though classify and regress can also be used." }, { "code": null, "e": 1135, "s": 1053, "text": "If you would like to view this tutorial in a Jupyter Notebook, please click here." }, { "code": null, "e": 1538, "s": 1135, "text": "At its most basic level, TensorFlow-Serving allows developers to integrate client requests and data with deep learning models served independently of client systems. Benefits of this include clients being able to make inferences on data without actually having to install TensorFlow or even have any contact with the actual model, and the ability to serve multiple clients with one instance of a model." }, { "code": null, "e": 1572, "s": 1538, "text": "Our pipeline will look like this:" }, { "code": null, "e": 1996, "s": 1572, "text": "Note especially that the image must pass from the client to the server as a Base64 encoded string. This is because JSON has no other way to represent images (besides an array representation of a tensor, and that gets out of hand very quickly). The image must also pass from the ProtoBuf to the Generator as a tensor. This can be modified, but it is best to keep any pre- and post-processing decoupled from the model itself." }, { "code": null, "e": 2127, "s": 1996, "text": "Exporting a TensorFlow model for serving is probably the most confusing part of the process, since there are a few steps involved." }, { "code": null, "e": 2694, "s": 2127, "text": "Export graph to ProtoBuf format. This saves the GraphDef and variables, and represents the trained model. In order to export an image-based model, we have to inject bitstring conversion layers into the beginning and ending of the graph, since we require our inference function to deal only in tensors.Wrap the ProtoBuf in a SavedModel. This step is necessary because TensorFlow-Serving’s RESTful API is implemented through a SavedModelBuilder. We’ll import our GraphDef, then extract the TensorInfo of the input and output to define our PREDICT signature definition." }, { "code": null, "e": 2996, "s": 2694, "text": "Export graph to ProtoBuf format. This saves the GraphDef and variables, and represents the trained model. In order to export an image-based model, we have to inject bitstring conversion layers into the beginning and ending of the graph, since we require our inference function to deal only in tensors." }, { "code": null, "e": 3262, "s": 2996, "text": "Wrap the ProtoBuf in a SavedModel. This step is necessary because TensorFlow-Serving’s RESTful API is implemented through a SavedModelBuilder. We’ll import our GraphDef, then extract the TensorInfo of the input and output to define our PREDICT signature definition." }, { "code": null, "e": 3338, "s": 3262, "text": "We’ll use CycleGAN as a usage example. First, import some useful libraries:" }, { "code": null, "e": 3443, "s": 3338, "text": "import tensorflow as tfimport argparseimport syssys.path.insert(0, “../CycleGAN-TensorFlow”)import model" }, { "code": null, "e": 3503, "s": 3443, "text": "Here, we instantiate a CycleGAN and inject our first layer." }, { "code": null, "e": 3817, "s": 3503, "text": "graph = tf.Graph()with graph.as_default(): # Instantiate a CycleGAN cycle_gan = model.CycleGAN(ngf=64, norm=\"instance\", image_size=64) # Create placeholder for image bitstring # This is the injection of the input bitstring layer input_bytes = tf.placeholder(tf.string, shape=[], name=\"input_bytes\")" }, { "code": null, "e": 3907, "s": 3817, "text": "Next, we preprocess the bitstring to a float tensor batch so it can be used in the model." }, { "code": null, "e": 4464, "s": 3907, "text": "with graph.as_default(): input_bytes = tf.reshape(input_bytes, []) # Transform bitstring to uint8 tensor input_tensor = tf.image.decode_png(input_bytes, channels=3) # Convert to float32 tensor input_tensor = tf.image.convert_image_dtype(input_tensor, dtype=tf.float32) # Ensure tensor has correct shape input_tensor = tf.reshape(input_tensor, [64, 64, 3]) # CycleGAN's inference function accepts a batch of images # So expand the single tensor into a batch of 1 input_tensor = tf.expand_dims(input_tensor, 0)" }, { "code": null, "e": 4523, "s": 4464, "text": "Then, we feed the tensor to the model and save its output." }, { "code": null, "e": 4634, "s": 4523, "text": "with graph.as_default(): # Get style transferred tensor output_tensor = cycle_gan.G.sample(input_tensor)" }, { "code": null, "e": 4742, "s": 4634, "text": "Post-inference, we convert the float tensor back to a bitstring. This is the injection of the output layer:" }, { "code": null, "e": 5179, "s": 4742, "text": "with graph.as_default(): # Convert to uint8 tensor output_tensor = tf.image.convert_image_dtype(output_tensor, tf.uint8) # Remove the batch dimension output_tensor = tf.squeeze(output_tensor, [0]) # Transform uint8 tensor to bitstring output_bytes = tf.image.encode_png(output_tensor) output_bytes = tf.identity(output_bytes, name=\"output_bytes\") # Instantiate a Saver saver = tf.train.Saver()" }, { "code": null, "e": 5459, "s": 5179, "text": "Now that we have injected the bitstring layers into our model, we will load our train checkpoints and save the graph as a ProtoBuf. Prior to coding this server, I trained CycleGAN for 10,000 steps and saved the checkpoint file on my local machine, which I access in this session." }, { "code": null, "e": 6041, "s": 5459, "text": "# Start a TensorFlow sessionwith tf.Session(graph=graph) as sess: sess.run(tf.global_variables_initializer()) # Access variables and weights from last checkpoint latest_ckpt = tf.train.latest_checkpoint(\"../CycleGAN-TensorFlow/checkpoints/20180628-1208\") saver.restore(sess, latest_ckpt) # Export graph to ProtoBuf output_graph_def = tf.graph_util.convert_variables_to_constants(sess, graph.as_graph_def(), [output_bytes.op.name]) tf.train.write_graph(output_graph_def, \"../CycleGAN-TensorFlow/protobufs\", \"model_v1\", as_text=False)" }, { "code": null, "e": 6157, "s": 6041, "text": "With that, we’ve completed step one! In step two, we will wrap the ProtoBuf in a SavedModel to use the RESTful API." }, { "code": null, "e": 6713, "s": 6157, "text": "# Instantiate a SavedModelBuilder# Note that the serve directory is REQUIRED to have a model version subdirectorybuilder = tf.saved_model.builder.SavedModelBuilder(\"serve/1\")# Read in ProtoBuf filewith tf.gfile.GFile(\"../CycleGAN-TensorFlow/protobufs/model_v1\", \"rb\") as protobuf_file: graph_def = tf.GraphDef() graph_def.ParseFromString(protobuf_file.read())# Get input and output tensors from GraphDef# These are our injected bitstring layers[inp, out] = tf.import_graph_def(graph_def, name=\"\", return_elements=[\"input_bytes:0\", \"output_bytes:0\"])" }, { "code": null, "e": 6963, "s": 6713, "text": "Next, we define our signature definition, which expects the TensorInfo of the input and output to the model. When we save the model, we’ll get a “No assets” message, but that’s okay because our graph and variables were already saved in the ProtoBuf." }, { "code": null, "e": 8035, "s": 6963, "text": "# Start a TensorFlow session with our saved graphwith tf.Session(graph=out.graph) as sess: # Signature_definition expects a batch # So we'll turn the output bitstring into a batch of 1 element out = tf.expand_dims(out, 0) # Build prototypes of input and output bitstrings input_bytes = tf.saved_model.utils.build_tensor_info(inp) output_bytes = tf.saved_model.utils.build_tensor_info(out) # Create signature for prediction signature_definition = tf.saved_model.signature_def_utils.build_signature_def( inputs={\"input_bytes\": input_bytes}, outputs={\"output_bytes\": output_bytes}, method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME) # Add meta-information builder.add_meta_graph_and_variables( sess, [tf.saved_model.tag_constants.SERVING], signature_def_map={ tf.saved_model.signature_constants. DEFAULT_SERVING_SIGNATURE_DEF_KEY: signature_definition })# Create the SavedModelbuilder.save()" }, { "code": null, "e": 8290, "s": 8035, "text": "And that’s it! Returned on the command line is the path to our SavedModel, which is used to build the TensorFlow Model Server. Our “variables” folder inside serve/1 will be empty, but that is okay because our variables were already saved in the ProtoBuf." }, { "code": null, "e": 8448, "s": 8290, "text": "As of July 2018, Python 3 is not officially supported with TensorFlow Serving, but someone made a solution. Install the Python 3 TensorFlow Serving API with:" }, { "code": null, "e": 8491, "s": 8448, "text": "pip install tensorflow-serving-api-python3" }, { "code": null, "e": 8564, "s": 8491, "text": "Now, we can run this TensorFlow Model Server from bash with the command:" }, { "code": null, "e": 8660, "s": 8564, "text": "tensorflow_model_server --rest_api_port=8501 --model_name=saved_model --model_base_path=$(path)" }, { "code": null, "e": 8794, "s": 8660, "text": "Where $(path) is the path to the serve directory. In my case, it is /mnt/c/Users/Tyler/Desktop/tendies/minimum_working_example/serve." }, { "code": null, "e": 8961, "s": 8794, "text": "The client’s job is to accept an image as input, convert it to Base64, pass it to the server using JSON, and decode the response. First, import some useful libraries:" }, { "code": null, "e": 9016, "s": 8961, "text": "import base64import requestsimport jsonimport argparse" }, { "code": null, "e": 9145, "s": 9016, "text": "We will be performing style transfer from an image of Gaussian noise to an image of sinusoidal noise. Here’s the Gaussian image:" }, { "code": null, "e": 9199, "s": 9145, "text": "First, we’ll open the image and convert it to Base64." }, { "code": null, "e": 9578, "s": 9199, "text": "# Open and read image as bitstringinput_image = open(\"images/gaussian.png\", \"rb\").read()print(\"Raw bitstring: \" + str(input_image[:10]) + \" ... \" + str(input_image[-10:]))# Encode image in b64encoded_input_string = base64.b64encode(input_image)input_string = encoded_input_string.decode(\"utf-8\")print(\"Base64 encoded string: \" + input_string[:10] + \" ... \" + input_string[-10:])" }, { "code": null, "e": 9808, "s": 9578, "text": "JSON data sent to our TensorFlow Model Server has to be structured in a very particular way. This method will be slightly different for classification and regression. For image prediction calls, our JSON body must look like this:" }, { "code": null, "e": 9952, "s": 9808, "text": "{ \"instances\": [ {\"b64\": \"iVBORw\"}, {\"b64\": \"pT4rmN\"}, {\"b64\": \"w0KGg2\"} ]}" }, { "code": null, "e": 10059, "s": 9952, "text": "Since we’re only sending one image to the server, it’s pretty simple. We can create our JSON data like so:" }, { "code": null, "e": 10199, "s": 10059, "text": "# Wrap bitstring in JSONinstance = [{\"b64\": input_string}]data = json.dumps({\"instances\": instance})print(data[:30] + \" ... \" + data[-10:])" }, { "code": null, "e": 10473, "s": 10199, "text": "This is all we need to send our POST request to the TensorFlow Model Server. This is a synchronous call, so the client will pause until it receives a response from the server (useful to know when you’re wondering why your code has stopped after POSTing a very large image)." }, { "code": null, "e": 10569, "s": 10473, "text": "json_response = requests.post(\"http://localhost:8501/v1/models/saved_model:predict\", data=data)" }, { "code": null, "e": 10716, "s": 10569, "text": "To interpret the response, we do the above steps in the reverse order. To grab our base64-encoded image from the JSON response, we have to access:" }, { "code": null, "e": 10885, "s": 10716, "text": "The value corresponding to “predictions” in the response dictionary.The first entry in the resultant array.The value corresponding to “b64” in the resultant dictionary." }, { "code": null, "e": 10954, "s": 10885, "text": "The value corresponding to “predictions” in the response dictionary." }, { "code": null, "e": 10994, "s": 10954, "text": "The first entry in the resultant array." }, { "code": null, "e": 11056, "s": 10994, "text": "The value corresponding to “b64” in the resultant dictionary." }, { "code": null, "e": 11106, "s": 11056, "text": "Then, we’ll decode that value to a raw bitstring." }, { "code": null, "e": 11676, "s": 11106, "text": "# Extract text from JSONresponse = json.loads(json_response.text)# Interpret bitstring outputresponse_string = response[\"predictions\"][0][\"b64\"]print(\"Base64 encoded string: \" + response_string[:10] + \" ... \" + response_string[-10:])# Decode bitstringencoded_response_string = response_string.encode(\"utf-8\")response_image = base64.b64decode(encoded_response_string)print(\"Raw bitstring: \" + str(response_image[:10]) + \" ... \" + str(response_image[-10:]))# Save inferred imagewith open(\"images/sinusoidal.png\", \"wb\") as output_file: output_file.write(response_image)" }, { "code": null, "e": 11777, "s": 11676, "text": "Success! Here’s the resultant image, which imposes a sinusoidal noise pattern on our original image." } ]
Complete Guide to Regressional Analysis Using Python | by Brandon Morgan | Towards Data Science
Hello and welcome to this FULL IN-DEPTH, and very long, overview of Regressional Analysis in Python! In this deep dive, we will cover Least Squares, Weighted Least Squares; Lasso, Ridge, and Elastic Net Regularization; and wrap up with Kernel and Support Vector Machine Regression! Although I’d like to cover some advanced Machine Learning models for regression, such as random forests and neural networks, their complexity demand their own future post! In this post I will approach Regressional Analysis from two sides: Theoretical and Application. From the Theoretical side I will introduce the algorithms at a basic level and derive their base solution while in the Application side I will use sklearn in Python to actually apply these models to a real-life dataset! What is Regression? Our Data Set — Medical Cost How to Measure Error? Least Squares Solution (MLR) Interpretation of the Model Weighted Least Squares (WLR) How to deal with Overfitting — Regularization How to deal with Underfitting — Kernel Regression Support Vector Machine Conclusion In the realm of Machine Learning, tasks are often split into four major categories: Supervised Learning, Unsupervised Learning, Semi-Supervised Learning, and Reinforcement Learning. Regression falls into the domain of Supervised Learning, where the goal is to learn or model a function that maps a set of inputs to a set of outputs. In Supervised Learning, our set of outputs are commonly called the dependent variable in statistics or the target variable in the Machine Learning Community. This target variable can either be discrete, commonly called Classification, or continuous, commonly called Regression. In this way, Regression is simply trying to predict a continuous target variable given a set of inputs. To give some application to the theoretical side of Regressional Analysis, we will be applying our models to a real dataset: Medical Cost Personal. This dataset is derived from Brett Lantz’ textbook: Machine Learning with R, where all of his datasets associated with the textbook are royalty free under the following license: Database Contents License (DbCL) v1.0. This dataset contains 1338 medical records of different individuals recording a few metrics: age, sex, bmi, number of children, whether or not they smoke, and the region they live. The goal is to use these features to predict the persons ‘charges’, medical cost. Because this will already be a long post, I will not go in detail over the exploratory analysis and pre-processing steps in detail; however, they are listed below: import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns data = pd.read_csv("insurance.csv") data 1338 rows × 7 columns data.dtypes age int64 sex object bmi float64 children int64 smoker object region object charges float64 dtype: object data.describe() sns.countplot(x='sex', data=data) <AxesSubplot:xlabel='sex', ylabel='count'> sns.countplot(x='smoker', data=data) <AxesSubplot:xlabel='smoker', ylabel='count'> sns.countplot(x='region', data=data) <AxesSubplot:xlabel='region', ylabel='count'> data = pd.get_dummies(data) data 1338 rows × 12 columns X = data.drop(["charges"], axis=1) Y = data["charges"] plt.figure(figsize=(16, 6)) sns.heatmap(X.corr(), annot=True) <AxesSubplot:> plt.figure(figsize=(16, 6)) sns.heatmap(data.corr()[['charges']].sort_values(by='charges', ascending=False), vmin=-1, vmax=1, annot=True, cmap='BrBG') <AxesSubplot:> X = X.to_numpy() Y = Y.to_numpy() n = len(X) train_perc = 0.75 # percentage of training set train_ind = range(0, int(train_perc*n)) # indices of dataset for training train_x = X[train_ind] train_y = Y[train_ind] test_ind = range(n-int(train_perc*n), n) # indices of dataset for testing test_x = X[test_ind] test_y = Y[test_ind] plt.hist(train_y) (array([404., 304., 95., 60., 30., 38., 43., 26., 1., 2.]), array([ 1121.8739 , 7386.729311, 13651.584722, 19916.440133, 26181.295544, 32446.150955, 38711.006366, 44975.861777, 51240.717188, 57505.572599, 63770.42801 ]), <BarContainer object of 10 artists>) Heavily Skewed, Least Squares works on the assumption that y∼N(XTβ,ε). Meaning Y needs to be distributed Normally; however, as we can see above it is not... One common solution to skewed distrubutions above is to perform logarithm transformation: train_y = np.log(train_y) plt.hist(train_y) (array([ 39., 80., 77., 113., 153., 207., 119., 90., 82., 43.]), array([ 7.02275569, 7.42678461, 7.83081352, 8.23484244, 8.63887136, 9.04290027, 9.44692919, 9.8509581 , 10.25498702, 10.65901594, 11.06304485]), <BarContainer object of 10 artists>) Now we can see from Above that log(Y) is distributed Normally; we will use this transformation as our new target variable. Here is the code on how to load in the dataset, split it into the feature and target variables, as well as partition it into a testing and training set: The reason why we split our dataset into a training and testing dataset is that we train our model on the training set and evaluate it on how well it generalizes to new data that it has not seen before, the testing set. In addition, I’ve also had to perform a Logarithm transformation on our target variable as it follows a heavily skewed distribution. Under some principle assumptions of Least Squares, Y needs to follow a Normal distribution, which will be explained later. As of right now, heavily skewed positive distributions can be made to follow a normal distribution through eithe ra Logarithm or BoxCox Transformation. In the Machine Learning community there has been a lot of research and debate on the best way to measure error. For Regression, most error measurements are derived from a concept found in Linear Algebra known as norms. Norms are measurements that allow one to measure how big is a tensor/matrix/vector. As one can see, if these norms measure how big is a tensor, then the goal of Machine Learning models is to minimize the norm difference between our expected output and the predicted output! In mathematical format, a norm of x, is commonly defined to be: Where p is a parameter that changes the measurement. Here below are some of the most common p-norms: How do we use these norms to help us measure error? Well, we can use them to measure the difference between our models prediction, f(x), and the actual target variable, y. Thus, we can measure error to be the difference between the prediction and actual, which can be quantified by a single numeric value using a norm: The two most common error measurements in Machine Learning are Mean Squared Error (MSE) and Mean Absolute Error (MAE): In the Machine Learning models we’ll look into today, MSE is chosen as the measurement to quantify error due to the convex nature of squaring the error — in layman’s terms, the numerical methods have an easier time of minimizing squared numbers rather than absolute due to the derivative of the absolute operation being non-defined. There exists only one problem with the error measurements described above, they do not explain how well the model performs relative to the target value, only the size of the error. Does a large error mean a poor model? Does a small error mean a good model? A good model can have an extremely large MSE while a poor model can have a small MSE if the variation of the target variable is small. For example, suppose we have two different lines for two different datasets. The prediction for the dataset on the left has a lower MSE than the one on the right, does that mean the model on the left is better? I’m guessing that you’d say the prediction line on the right is better than the one of the left despite having a higher MSE as the dataset on the right has higher variation within the Y variable. The problem with only using MSE or MAE is that it does not take into account the variation of the target variable. If the target variable has a lot of variance, as in the dataset on the right, then the MSE will be naturally higher. A popular metric used to take the variation of the target variable into account is known as the Coefficient of Determination, commonly called R Squared: As we can see from above, R Squared is proportional to the ratio of the Residual Sum Squared (RSS) versus the Total Sum of Squares (TSS). R Squared ranges from (-infinity, 1]. Where the interpretation is the percentage of the variation of the target variable explained. For example, suppose a model has an R Squared value of 0.88, then that model explains approximately 88% of the variability of the target variable. Hence, larger R Squared values are more desirable as the model will explain a greater percentage of the target variable. However, if the RSS of the model is larger than the TSS, then the R Squared metric will be negative, which means that the variance of the model outweighs the variance of the target, aka the model sucks. Now that we’ve defined our error measurement, it’s time to introduce our first classic Machine Learning model, Least Squares! As with most of the models going to be discussed, Least Squares works off the assumption that the dependent/target variable is a linear combination of the feature variable (assuming k number of features): The goal of the coefficients are to act as the slope for the respective input variable, and the intercept is to act as the point where the target variable starts when the input variables are zero. With this strong assumption above, our goal is to find accurate predictions to the coefficients: Because our beta estimates are not going to be exact, we will have an error term, epsilon. This can be written in matrix format as the following: To derive the estimate coefficients for beta, there are two main derivations. I will give both. First, using simple matrix manipulation: The second derivation is most the most common, by trying to minimize the Expectation of the difference using gradients. In statistics, Expectation is commonly defined to be weighted mean of a random variable: Which can be converted into matrix format: Then, we can find the gradient of J, set it equal to zero, and find the analytical solution for beta! As we can see, both methodologies led to the same solution! In fact, they are the equal! However, if you’ve been paying acute attention, we’ve made three big assumptions: Y is distributed Normally; X^T*X is invertible; and the expected value of epsilon is zero with constant variance. Although these assumptions are broken sometimes in practice, the Least Squares model still performs well! I hope now you understand as to why we had to perform a logarithmic transformation on our target variable to achieve Normality! The time complexity for standard Least Squares is O(k3) as the time complexity is O(n3) to find the inverse of a matrix, but our matrix result, X^T*X is actually k by k, where k is the number of features/columns. Now that we’ve discussed the theoretical background for Least Squares, lets apply it our problem! We can use the LinearRegression object from the sklearn library to implement our Least Squares solution! To assess our model, we can look at the MSE and R2 value both on the testing and training dataset: As we can see from the above barplot on the left hand side, the MSE for both the testing and training sets are extremely low, only around 0.19; however, if you remember, the target variable underwent a Logarithmic Transformation, meaning that an MSE of 0.016 is not relatively small given the scale of the target variable. Therefore, a better measurement is to assess the R2 value, which we can see from the barplot on the right hand side is decent. Our model only explains approximately 79% of the variability of the target variable for the training set and roughly 76% of the variability for the testing set. Although is result is reasonable for some scenarios, for this simple dataset this is known as underfitting, when a model performs poorly at predicting a target variable. We will cover some methodologies on how to fix this problem later. One big advantage of Linear Regression over some other Regression models is its simplicity and explanatory power. Each beta coefficient can be assessed to explain how the model is achieving its predictions. Machine Learning models like this are known as White Box Methods, meaning that it is apparent how the model is achieving its output. On the other hand, Machine Learning models where the formulation process on how the prediction was achieved is unknown are known as Black Box Methods. For example, here are our beta coefficient values: Unfortunately, because we scaled the target variable using a logarithm, the coefficient values are in terms of explaining the log of the target. To combat this, we can rescale the coefficients by the inverse of logarithm, the exponentiation. Here are our exponentiated beta coefficients: The interpretation of exponentiated beta coefficients is the percentage change in the target variable. For example, when the person is a smoker, their medical cost increases by 116.8% ((2.168–1)*100). On the other hand, if the person is not a smoker then their medical cost will decrease by 63.9% ((0.461–1)*100). Essentially, any beta coefficient larger than one imposes an increase percentage of medical costs while any beta coefficient smaller imposes a decrease percentage of medical costs. In addition, we can definitely see that the largest exponentiated beta coefficient belongs to smokers, meaning that variable, whether the person is a smoker, has the largest influence to medical cost out of the other variables. Let’s suppose that we did not perform a logarithmic transformation, how would we interpret the beta coefficients then? The interpretation is in terms of the unit scale of the target variable. Because our target variable was measure in dollars, we can see that if a person was a smoker, then their medical cost would increase by $11,907 ; or decrease by $11,907 if they were not a smoker. For age, we can see that as the older the person becomes, their medical cost will increase by $264 per year of age. If we were to look at sex, the coefficients are the same, meaning that medical cost does not go up whether or not the person is male or female. Hopefully you can see the power of interpreting the coefficients of Least Squares Regression. One of the main assumptions made under Least Squares is that the errors, epsilon, is Normally distributed with constant Variance: One can check this assumption by plotting the residuals, f(x)-y, verses the actual, commonly called a residual plot. Here is our residual plot from our previous model on the training sample: As we can see from above, the variance of our residual errors does not have mean of zero nor constant variance, as it is highly non-linear. In addition, we can see that the squared residuals show a slight upward trend as the target variable approaches its max value. Residual errors with non-constant variance are called heteroscedastic. One way to combat heteroscedasticity is through Weighted Least Squares. Weighted Least Squares is like standard Least Squares; however, each observation is weighted by its own unique value. In this way, observations with larger weights are more favored by the model to fit than smaller weights. To give an example of the power of adding weights, here below we have two prediction lines, one unweighted and one not. As we can see from the weighted prediction, the instances that have the higher weight are going to have a better fit as the model will gravitate to fixing the prediction line about those points more than instances with lesser weights. Now it is time for the derivation of the Weighted Least Squares Solution. To start off, we want to minimize the Expectation of the weighted residual error: This can be converted to matrix format: Now the partial derivate can be found and set to zero to find the analytical solution: As we can see from above, the solution is extremely similar to that of Linear Regression, except with a diagonal matrix W, containing the weights for each instance. One of the main powers of WLS is the ability to weight different instances to give preference within the model, either to create homoscedasticity, constant variance, or to model better certain records. However, one of the main drawbacks of WLS is how to determine the weights. In our problem, we want to fix our residuals to have constant variance. Below I have depicted the four major types of residual variances found in practice. The top left showcases the ideal, where the variance is constant with a mean of zero. The top right showcases how the residual variance grows with y, revealing a ‘MegaPhone’ type distribution. The bottom left depicts non linear residuals, revealing that our model is lacking the complexity to create an association. Lastly, the bottom right showcases a binomial residual variance. WLS is commonly used only when a binomial or MegaPhone type residual plot is found, as nonlinear residuals can only be fixed the addition of nonlinear features. A common solution for Binomial and MegaPhone residuals is to make the weights equal their squared residual error: As we can see, this intuitively makes sense, we weight instances based off how large is their error. In sklearn, this is simple, just create another model and add the extra weight_sample argument: If you were to test these weights above, the residual plot would look similar and with similar R2 and MSE scores, this is because our residual variance is highly non linear: For this situation, we only have one solution, try the addition of nonlinear terms in hopes to explain the variance. Which we will cover with Kernel Regression, but first we need to discuss Regularization. Suppose we trained a Linear Regression model on a given dataset, and during its application and deployment we found out that it was performing extremely poorly, despite having good MSE and R2 scores on the training data; this is known as overfitting — when the metrics on the Testing Dataset are much worse than the Training dataset. To give an example: As we can see from above, we have a linear trend of points; however, if we were to fit a 10th Degree Polynomial we can artificially minimize both MSE and R2 to zero on our training dataset. Despite this, we can see intuitively that model will generalize poorly when new data is seen. Regularization works by adding a Penalty Term to the loss function that will penalize the parameters of the model; in our case for Linear Regression, the beta coefficients. There are two main types of Regularization when it comes to Linear Regression: Ridge and Lasso. First, lets start off with Ridge Regression, commonly called L2 Regularization as its penalty term squares the beta coefficients to obtain the magnitude. The idea behind Ridge Regression is to penalize large beta coefficients. The Loss Function that Ridge Regression tries to minimize is the following: As we can see from above, the Loss function is exactly the same as before, except now with the addition of the penalty term in red. The parameter lambda scales the penalty. For example, if lambda=0, then the function is the same as before in Least Squares; however, as lambda grows larger the model will lead to underfitting as it will penalize the size of the beta coefficients to zero. Lets look at a simple example below: As we can see from above, when using a 20th Degree Polynomial model to approximate the points and lambda=0, we have no penalization and exhibit extreme overfitting in the blue line. As we start to increase lambda to 0.5, denoted by the orange line, we start to truly model the underlying distribution; however, we can see that when lambda=100 in the purple line, our model starts to become a straight line, leading to underfitting as the penalty term forces the coefficients to zero. Choosing the lambda value in practice is either performed on a Validation Set or through Cross-Validation. In this way, we retrain our model on our training dataset with different lambda values and which ever one performs best on our Validation set is chosen to be final for the Testing dataset. Mathematically speaking, our loss function can be transformed into matrix form: Where beta can be solved for as previously, by finding the gradient and setting it to zero: Now that we’ve discussed the mathematical theory behind Ridge Regression, lets apply it to our dataset. In practice, one would want to tune the lambda value on a validation set, not the testing set in order to get a good generalization error; however, I am going to do it on the testing set in order to save some room: As we can see from above, as we increase our lambda value, our error on the training and testing set increase drastically; in addition, it appears that the min error on the testing set is around lambda=0. If you remember correctly, our dataset was not failing from overfitting but underfitting! Therefore, it makes no sense to use regularization, which is why our testing error is getting worse instead of better! I just wanted to show how one could use Ridge Regression if your model was exhibiting overfitting! The next regularization method to be covered is Lasso, which is commonly called L1 regularization as its penalty term is built off the absolute value of the beta coefficients: Notice that the only difference between Ridge and Lasso Regularization is that Ridge squares the beta coefficients while Lasso takes the absolute value. The main difference between the two is that Ridge penalizes the size of the beta coefficients, whereas Lasso will drive some of the beta coefficient values to zero, leading to feature selection. These types of penalty terms can often be rewritten as a constraint problem: Because Ridge regression squares the beta coefficients, plotting the constraint would lead to a circle; whereas Lasso would lead to square. If we were to plot two beta coefficients (called w1 and w2 in the graph below) values against each other we might end up with the following: The red line represents the range of values that the two coefficient values can take on, as the coefficient value for w1 increases, the value of w2 starts to decrease. When we plot our L1 norm constraint: |w1|+|w2|≤ lambda, we can see it denoted by the dotted square. Wherever this square box intersects the red line is the chosen value for the coefficients, which we can see would cause w1 to have a value of zero. On the other hand, when we plot our L2 norm constraint: w12+w22≤ lambda, we get a circle, as denoted by the dotted circle. Wherever this circle intersects the red line is the chosen value for the constraints, which we can see are both small nonzero values for w1 and w2. Unfortunately, finding the analytical solution for beta in Lasso Regularization is difficult using matrix calculus as the gradient of the absolute value operation is undefined, therefore numerical methods like Coordinate Descent are often utilized. Because of the complex nature of these algorithms I will not detail the math. In python, Lasso Regression can be performed as follows: As we can see from above, as we increase our lambda value, our error on the training and testing set increase drastically, eventually converging around lambda=15. The reason why the error converged is because our lambda value was too large for the model and it drove all the beta coefficients to zero. If you remember correctly, our dataset was not failing from overfitting but underfitting! Therefore, it makes no sense to use regularization, which is why our testing error is getting worse instead of better! I just wanted to showcase how you use Lasso Regression if your model was exhibiting overfitting! The last Regularization technique I am going to introduce is Elastic Net, which came about to harmonize Ridge and Lasso, as Ridge penalizes large coefficients whereas Lasso drives coefficients to zero. The idea behind Elastic Net is create a penalty that will both create feature selection and minimize the size of the weights. There are many different versions of Elastic Net, here are the two most common: As one can see, the penalty term is a combination of Ridge and Lasso, each with their own lambda value to control how much each penalty term affect the model. We’ve discussed what to do when a model starts to overfit, but what about when a model underfits? In our example dataset thus far, our model has shown various signs of underfitting: non-linear residuals and poor R2 value on a relatively simple dataset. The most common way to deal with underfitting is to utilize a Kernel. A Kernel is a density function that satisfy three main properties: Kernel Regression is often called a non-parametric regression technique by the Statistics Community. The premise behind using a Kernel is that if we map our input variables to a higher dimension, then the problem can be either easily classified or predicted. The easiest example to see how this works in practice is through a simple classification problem. Suppose we have two groups that we wish to classify using only a line/hyperplane. We can see down below that no line will be able to classify the two groups: However, if we were to transfer the data into a higher dimension (as we can see on the right hand side), now there exists a hyperplane capable of classifying the data. To give an example for regression, suppose we only have one feature variable, X, where the target variable Y is equal to X3. We can see below in the bottom left picture that a linear model will fail to accurately represent this data. However, if instead we project our feature variable, X, to a higher dimension, X3, then we can see that our linear model fits a perfect line. I hope now I’ve convinced you of the power of projecting our feature variables to higher dimension! However, now the question becomes, how do we do so? First, we need to define a function, commonly denoted as phi, that maps our variables to higher dimensional input space. In Kernel Regression, the way in which this is performed is by Kernel Functions. One of the most popular and basic of Kernels is the Polynomial kernel, which simply raises the feature variables to a power. Lets take for example, the simple case where we have only two variables: x1 and x2; then, we want to map this to a higher dimensional space by simply using a polynomial kernel with the power 2: As we can see from above, we mapped our original data, x1 and x2, to a higher dimension using the phi function with a polynomial power of 2. The only problem is that now our time complexity is proportional to the power of our polynomial, O(k^p). We can reduce this complexity through the Kernel Trick. First, lets recalculate our loss/error metric using phi(x). Note that Kernel Regression utilizes Ridge Regression as the coefficients tend to be extremely large, which is why this method is commonly called Kernel Ridge Regression: We can se that the derivation of beta is actually recursive, meaning the optimal beta is a function of itself. However, if we were to plug this beta back into our error metric we get: As you can see, as we reduce our loss function with the new beta value, we get phi(x_i)*phi(x_j), where phi(x) is a O(k^p) operation, which makes this procedure a very time consuming operation. However, the Trick, is that To give a concrete, example, lets apply this to our previous kernel function, a polynomial with power of two: As we can see from above, the Kernel Trick is the fact that the dot product of of two data points converted to a high dimensional mapping is the same as the high dimensional mapping of the dot product between the two points! This saves a lot of time and computational resources! Now, we can trade this back in to our loss function to get: As we can see from above, the format of the loss function is very similar to Least Squares, except where K=X and alpha=beta. To find the optimal beta, we first find the optimal solution for alpha, then plug that into beta! The time complexity for standard Least Squares is O(k3), but now our matrix result is an n by n matrix as K is n by n; therefore, the time complexity for Kernel Regression is O(n3), which is extremely computationally heavy when there is a lot of data! A common solution is to simply sample data from the total dataset such that n is small. Another hyperparameter that needs to be tuned for Kernel regression is choosing which Kernel Function to utilize. The three most common are the following: As we can see from above, each Kernel Function will have its own set of hyperparameters to tune, adding to the complexity. Now that we’ve discussed the theoretical background, lets apply Kernel Ridge Regression to our problem! For this example I will only showcase the Polynomial Kernel as it is the most common. Because Kernel Ridge also has a lambda/penalty term, I will show the influence of increasing the penalty term on the testing dataset. Note that in practice one would want to this on a validation set, not testing. As we can see from the plot above, increasing the penalty term of lambda actually decreases the R2 value on both testing and training error; however, in practice this might not be the case, so always test out different regularization values. Immediately however, we can see that using Kernel Regression increased the R2 on the testing dataset from 0.76 to 0.83, meaning that our model now explains approximately 83% of the variability of the target variable, little bit better than 76%. Now lets examine the residual plot on the training dataset in comparison with the standard Linear Regression: As we can see from above, our residual plot for Kernel Ridge (on the right hand side) definitely evens out the variance of the residuals to a constant for Y values between 7 and 9; however, the extremely large residuals for Y values between 9 and 10.5 still exist; indicating that our model is underfitting some of those points. One of the downfalls of Kernel Regression is that interpretability of the model is lost, as now the beta coefficients are not for the feature variables but the data observations, as the prediction of new data is given by: As we can see, for a new prediction we form a new Kernel Matrix, K, from the dot products between the new data and the data the beta was trained upon, multiplied the alpha vector holding the coefficients. Due to this high dimensional mapping, the interpretability on how the model achieved its results from simply the feature variables is lost, making Kernel Regression a Black Box Method. However, you might be thinking to yourself, if Kernel Regression is a black box method because the projection to a higher dimension is summed up to one value between the data instances, why don’t we manually project our feature space? For example, suppose we have the following feature space with three variables and project it to a second degree polynomial: Now we’ve projected our initial data dimension to a higher dimension, allowing us to perform ridge regression to obtain the white-box beta coefficients! However, the problem is that we assume in our Least Squares derivation that (X^T*X) is invertible, which assumes X is linearly independent, meaning no column is a combination of another; but we can clearly see that our new projected data is a linear combination of the original data dimension! In this way, the more higher dimensional terms we add the more likely the inverse does not exist. Kernel Regression escapes this problem as it projects the dot product between data instances, where we assume the data instances are sampled independently. For our last method in this deep dive into Regressional Analysis, we will look at a close counterpart to Kernel Ridge Regression, Support Vector Machines (SVMs). To give the basic intuition behind SVMs, lets switch over to the objective of classification, where we want to find a decision boundary to classify two groups and we have three possible models: The problem is that all three decision boundaries correctly classify all points, so now the question is which one is better? The ideal model would be the red line as it is not too close class 1 or class 2. SVM’s solve this problem by adding a margin about the decision boundary, commonly called the Support Vectors: By adding these support vectors, our model has the ability to ‘feel’ out the data to find a decision boundary that can minimize the error within these support vector margins. There are two types of SVM’s, Soft Margin and Hard Margin. Hard Margin makes the model find a decision boundary such that no data instance is inside the support vector margins; whereas Soft Margin allows for instances to be inside the margins. Hard Margin only works on linearly classifiable data and is extremely sensitive to outliers, therefore Soft Margin is the most common type of SVM. The width of these support vectors, the margin, is commonly denoted as epsilon. The error function for Support Vector Regression is similar to that of least squares, in that it assumes that the target variable is a linear combination of the feature variables: However, the construction of the Loss/Error function is different than before, as we want to minimize beta to ensure Flatness, meaning we want small beta coefficients so that no feature variable coefficient becomes too large, leading to overfitting. In addition, we also want to minimize the residual error to be less than the margin width, denoted as epsilon: However the problem is that a model might not exist for the given epsilon that satisfies this condition (Hard Margin), leading to a surrogate function using slack variables (called Soft Margin): Unfortunately, the mathematics used to solve this problem are no longer as easy as finding a derivative and setting it equal to zero, but involves quadratic programming. Because of this complex nature, I am going to skip the math to find the final solution. Because SVM’s utilize the data matrix X, non linear mapping can be utilized through kernel functions to achieve non linear regressional planes. I am going to skip the math behind this as it gets messy and complicated; however, the idea is the same as mentioned above for Kernel Ridge. The nice thing is that the Kernel Trick still applies here as well, leading to saved time and computation. Now that we’ve talked about the theoretical side of SVM’s, lets apply it to our problem! As with Kernel Ridge Regression, there are a whole host of possible Kernel Function to use, to which this time I am going to test three: Polynomial, RBF, and Linear. In addition, there are two more important hyperparameters that SVM needs, C and epsilon. Epsilon is the margin width and C is regularization term. In practice, only the regularization term, C, is changed as changing the margin width will drastically lead to poor results. Here we have the three kernels with default parameters at various C values evaluated on the testing set. As we can see, for this particular dataset, by increasing the C value, almost all three kernels increase the R2 value on the testing set. We can visible see that the RBF kernel performs the best so lets examine its results at C=100 a little bit more in depth: As we can see, our R2 on the testing dataset was better than Least Squares, explaining 81% of the variability of the target variable, but not quite as good as Kernel Ridge Regression with a Polynomial Kernel. However, note that this might not always occur in practice. One could examine the residual plot for this model but it would be very similar to the ones before as the R2 is so similar. Unfortunately, as with Kernel Ridge Regression, because SVMs find their coefficients based off kernels instead of the feature variables, the interpretation on how the model achieved its prediction is lost, making SVM a black box method. If you’ve made it this far, congratulations! I hope you’ve learned a lot about Regression in the realm of Data Science and Machine Learning! As a quick recap, we introduced our first model, Least Squares, which simply assumed that the target variable was linear combination of the feature variables, to which the goal was to find these coefficients. The problem that arose was that Least Squares is built off a few assumptions, namely that the errors had constant variance and a mean of zero. In practice however, this was often violated as by assessing a residual plot one could observe the non-linearity of the residuals. Assuming the residuals followed a particular trend, such as a binomial or megaphone, Weighted Least Squares could be utilized to create a model to satisfy these assumptions. One of the many pros of Least Squares and its derivates is its open white-box nature, meaning the model prediction can be directly observed by the coefficients for the feature variables. In the situation where our model had low training error but yet high test error, we needed to include regularization to prevent overfitting. We discussed three of the most common types of regularization: Ridge, Lasso, and Elastic Net. Ridge regularization shrinks the values of the coefficients while Lasso drives some coefficients to zero, and Elastic Net seeks to harmonize the two. On the other end of the spectrum, where instead of overfitting, our model underfitted with both high training and testing errors. In order to fix this problem, we projected our feature space to a higher dimension using kernel functions in hopes that a prediction plane would be able to fit the data. This was performed through two methods — Kernel Ridge Regression and Support Vector Machines. The difference between the two is the formulation of the error/loss function, where SVM’s include a margin of error to minimize as well. However, the problem with these higher dimensional mapping models is that the interpretation of how the model achieved its prediction in terms of the feature variables is lost, making them both black-box methods. In practice, there is no best model to utilize. If you are wanting to present your model to businessmen with no background in machine learning then using LR or WLR to explain the importance of different features would be beneficial as they both are white-box methods, then reporting the scores of the black-box methods as they tend to perform better. All in all, I hope you have learned a lot about the topics discussed above, both theoretically and for application!
[ { "code": null, "e": 942, "s": 172, "text": "Hello and welcome to this FULL IN-DEPTH, and very long, overview of Regressional Analysis in Python! In this deep dive, we will cover Least Squares, Weighted Least Squares; Lasso, Ridge, and Elastic Net Regularization; and wrap up with Kernel and Support Vector Machine Regression! Although I’d like to cover some advanced Machine Learning models for regression, such as random forests and neural networks, their complexity demand their own future post! In this post I will approach Regressional Analysis from two sides: Theoretical and Application. From the Theoretical side I will introduce the algorithms at a basic level and derive their base solution while in the Application side I will use sklearn in Python to actually apply these models to a real-life dataset!" }, { "code": null, "e": 962, "s": 942, "text": "What is Regression?" }, { "code": null, "e": 990, "s": 962, "text": "Our Data Set — Medical Cost" }, { "code": null, "e": 1012, "s": 990, "text": "How to Measure Error?" }, { "code": null, "e": 1041, "s": 1012, "text": "Least Squares Solution (MLR)" }, { "code": null, "e": 1069, "s": 1041, "text": "Interpretation of the Model" }, { "code": null, "e": 1098, "s": 1069, "text": "Weighted Least Squares (WLR)" }, { "code": null, "e": 1144, "s": 1098, "text": "How to deal with Overfitting — Regularization" }, { "code": null, "e": 1194, "s": 1144, "text": "How to deal with Underfitting — Kernel Regression" }, { "code": null, "e": 1217, "s": 1194, "text": "Support Vector Machine" }, { "code": null, "e": 1228, "s": 1217, "text": "Conclusion" }, { "code": null, "e": 1943, "s": 1228, "text": "In the realm of Machine Learning, tasks are often split into four major categories: Supervised Learning, Unsupervised Learning, Semi-Supervised Learning, and Reinforcement Learning. Regression falls into the domain of Supervised Learning, where the goal is to learn or model a function that maps a set of inputs to a set of outputs. In Supervised Learning, our set of outputs are commonly called the dependent variable in statistics or the target variable in the Machine Learning Community. This target variable can either be discrete, commonly called Classification, or continuous, commonly called Regression. In this way, Regression is simply trying to predict a continuous target variable given a set of inputs." }, { "code": null, "e": 2308, "s": 1943, "text": "To give some application to the theoretical side of Regressional Analysis, we will be applying our models to a real dataset: Medical Cost Personal. This dataset is derived from Brett Lantz’ textbook: Machine Learning with R, where all of his datasets associated with the textbook are royalty free under the following license: Database Contents License (DbCL) v1.0." }, { "code": null, "e": 2571, "s": 2308, "text": "This dataset contains 1338 medical records of different individuals recording a few metrics: age, sex, bmi, number of children, whether or not they smoke, and the region they live. The goal is to use these features to predict the persons ‘charges’, medical cost." }, { "code": null, "e": 2735, "s": 2571, "text": "Because this will already be a long post, I will not go in detail over the exploratory analysis and pre-processing steps in detail; however, they are listed below:" }, { "code": null, "e": 2829, "s": 2735, "text": "import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n" }, { "code": null, "e": 2871, "s": 2829, "text": "data = pd.read_csv(\"insurance.csv\")\ndata\n" }, { "code": null, "e": 2893, "s": 2871, "text": "1338 rows × 7 columns" }, { "code": null, "e": 2906, "s": 2893, "text": "data.dtypes\n" }, { "code": null, "e": 3060, "s": 2906, "text": "age int64\nsex object\nbmi float64\nchildren int64\nsmoker object\nregion object\ncharges float64\ndtype: object" }, { "code": null, "e": 3077, "s": 3060, "text": "data.describe()\n" }, { "code": null, "e": 3112, "s": 3077, "text": "sns.countplot(x='sex', data=data)\n" }, { "code": null, "e": 3155, "s": 3112, "text": "<AxesSubplot:xlabel='sex', ylabel='count'>" }, { "code": null, "e": 3193, "s": 3155, "text": "sns.countplot(x='smoker', data=data)\n" }, { "code": null, "e": 3239, "s": 3193, "text": "<AxesSubplot:xlabel='smoker', ylabel='count'>" }, { "code": null, "e": 3277, "s": 3239, "text": "sns.countplot(x='region', data=data)\n" }, { "code": null, "e": 3323, "s": 3277, "text": "<AxesSubplot:xlabel='region', ylabel='count'>" }, { "code": null, "e": 3357, "s": 3323, "text": "data = pd.get_dummies(data)\ndata\n" }, { "code": null, "e": 3380, "s": 3357, "text": "1338 rows × 12 columns" }, { "code": null, "e": 3436, "s": 3380, "text": "X = data.drop([\"charges\"], axis=1)\nY = data[\"charges\"]\n" }, { "code": null, "e": 3499, "s": 3436, "text": "plt.figure(figsize=(16, 6))\nsns.heatmap(X.corr(), annot=True)\n" }, { "code": null, "e": 3514, "s": 3499, "text": "<AxesSubplot:>" }, { "code": null, "e": 3666, "s": 3514, "text": "plt.figure(figsize=(16, 6))\nsns.heatmap(data.corr()[['charges']].sort_values(by='charges', ascending=False), vmin=-1, vmax=1, annot=True, cmap='BrBG')\n" }, { "code": null, "e": 3681, "s": 3666, "text": "<AxesSubplot:>" }, { "code": null, "e": 3716, "s": 3681, "text": "X = X.to_numpy()\nY = Y.to_numpy()\n" }, { "code": null, "e": 4016, "s": 3716, "text": "n = len(X)\n\ntrain_perc = 0.75 # percentage of training set\ntrain_ind = range(0, int(train_perc*n)) # indices of dataset for training\ntrain_x = X[train_ind]\ntrain_y = Y[train_ind]\n\ntest_ind = range(n-int(train_perc*n), n) # indices of dataset for testing\ntest_x = X[test_ind]\ntest_y = Y[test_ind]\n" }, { "code": null, "e": 4035, "s": 4016, "text": "plt.hist(train_y)\n" }, { "code": null, "e": 4323, "s": 4035, "text": "(array([404., 304., 95., 60., 30., 38., 43., 26., 1., 2.]),\n array([ 1121.8739 , 7386.729311, 13651.584722, 19916.440133,\n 26181.295544, 32446.150955, 38711.006366, 44975.861777,\n 51240.717188, 57505.572599, 63770.42801 ]),\n <BarContainer object of 10 artists>)" }, { "code": null, "e": 4570, "s": 4323, "text": "Heavily Skewed, Least Squares works on the assumption that y∼N(XTβ,ε). Meaning Y needs to be distributed Normally; however, as we can see above it is not... One common solution to skewed distrubutions above is to perform logarithm transformation:" }, { "code": null, "e": 4615, "s": 4570, "text": "train_y = np.log(train_y)\nplt.hist(train_y)\n" }, { "code": null, "e": 4892, "s": 4615, "text": "(array([ 39., 80., 77., 113., 153., 207., 119., 90., 82., 43.]),\n array([ 7.02275569, 7.42678461, 7.83081352, 8.23484244, 8.63887136,\n 9.04290027, 9.44692919, 9.8509581 , 10.25498702, 10.65901594,\n 11.06304485]),\n <BarContainer object of 10 artists>)" }, { "code": null, "e": 5015, "s": 4892, "text": "Now we can see from Above that log(Y) is distributed Normally; we will use this transformation as our new target variable." }, { "code": null, "e": 5168, "s": 5015, "text": "Here is the code on how to load in the dataset, split it into the feature and target variables, as well as partition it into a testing and training set:" }, { "code": null, "e": 5796, "s": 5168, "text": "The reason why we split our dataset into a training and testing dataset is that we train our model on the training set and evaluate it on how well it generalizes to new data that it has not seen before, the testing set. In addition, I’ve also had to perform a Logarithm transformation on our target variable as it follows a heavily skewed distribution. Under some principle assumptions of Least Squares, Y needs to follow a Normal distribution, which will be explained later. As of right now, heavily skewed positive distributions can be made to follow a normal distribution through eithe ra Logarithm or BoxCox Transformation." }, { "code": null, "e": 6353, "s": 5796, "text": "In the Machine Learning community there has been a lot of research and debate on the best way to measure error. For Regression, most error measurements are derived from a concept found in Linear Algebra known as norms. Norms are measurements that allow one to measure how big is a tensor/matrix/vector. As one can see, if these norms measure how big is a tensor, then the goal of Machine Learning models is to minimize the norm difference between our expected output and the predicted output! In mathematical format, a norm of x, is commonly defined to be:" }, { "code": null, "e": 6454, "s": 6353, "text": "Where p is a parameter that changes the measurement. Here below are some of the most common p-norms:" }, { "code": null, "e": 6773, "s": 6454, "text": "How do we use these norms to help us measure error? Well, we can use them to measure the difference between our models prediction, f(x), and the actual target variable, y. Thus, we can measure error to be the difference between the prediction and actual, which can be quantified by a single numeric value using a norm:" }, { "code": null, "e": 6892, "s": 6773, "text": "The two most common error measurements in Machine Learning are Mean Squared Error (MSE) and Mean Absolute Error (MAE):" }, { "code": null, "e": 7225, "s": 6892, "text": "In the Machine Learning models we’ll look into today, MSE is chosen as the measurement to quantify error due to the convex nature of squaring the error — in layman’s terms, the numerical methods have an easier time of minimizing squared numbers rather than absolute due to the derivative of the absolute operation being non-defined." }, { "code": null, "e": 8024, "s": 7225, "text": "There exists only one problem with the error measurements described above, they do not explain how well the model performs relative to the target value, only the size of the error. Does a large error mean a poor model? Does a small error mean a good model? A good model can have an extremely large MSE while a poor model can have a small MSE if the variation of the target variable is small. For example, suppose we have two different lines for two different datasets. The prediction for the dataset on the left has a lower MSE than the one on the right, does that mean the model on the left is better? I’m guessing that you’d say the prediction line on the right is better than the one of the left despite having a higher MSE as the dataset on the right has higher variation within the Y variable." }, { "code": null, "e": 8409, "s": 8024, "text": "The problem with only using MSE or MAE is that it does not take into account the variation of the target variable. If the target variable has a lot of variance, as in the dataset on the right, then the MSE will be naturally higher. A popular metric used to take the variation of the target variable into account is known as the Coefficient of Determination, commonly called R Squared:" }, { "code": null, "e": 9150, "s": 8409, "text": "As we can see from above, R Squared is proportional to the ratio of the Residual Sum Squared (RSS) versus the Total Sum of Squares (TSS). R Squared ranges from (-infinity, 1]. Where the interpretation is the percentage of the variation of the target variable explained. For example, suppose a model has an R Squared value of 0.88, then that model explains approximately 88% of the variability of the target variable. Hence, larger R Squared values are more desirable as the model will explain a greater percentage of the target variable. However, if the RSS of the model is larger than the TSS, then the R Squared metric will be negative, which means that the variance of the model outweighs the variance of the target, aka the model sucks." }, { "code": null, "e": 9481, "s": 9150, "text": "Now that we’ve defined our error measurement, it’s time to introduce our first classic Machine Learning model, Least Squares! As with most of the models going to be discussed, Least Squares works off the assumption that the dependent/target variable is a linear combination of the feature variable (assuming k number of features):" }, { "code": null, "e": 9775, "s": 9481, "text": "The goal of the coefficients are to act as the slope for the respective input variable, and the intercept is to act as the point where the target variable starts when the input variables are zero. With this strong assumption above, our goal is to find accurate predictions to the coefficients:" }, { "code": null, "e": 9921, "s": 9775, "text": "Because our beta estimates are not going to be exact, we will have an error term, epsilon. This can be written in matrix format as the following:" }, { "code": null, "e": 10058, "s": 9921, "text": "To derive the estimate coefficients for beta, there are two main derivations. I will give both. First, using simple matrix manipulation:" }, { "code": null, "e": 10267, "s": 10058, "text": "The second derivation is most the most common, by trying to minimize the Expectation of the difference using gradients. In statistics, Expectation is commonly defined to be weighted mean of a random variable:" }, { "code": null, "e": 10310, "s": 10267, "text": "Which can be converted into matrix format:" }, { "code": null, "e": 10412, "s": 10310, "text": "Then, we can find the gradient of J, set it equal to zero, and find the analytical solution for beta!" }, { "code": null, "e": 10931, "s": 10412, "text": "As we can see, both methodologies led to the same solution! In fact, they are the equal! However, if you’ve been paying acute attention, we’ve made three big assumptions: Y is distributed Normally; X^T*X is invertible; and the expected value of epsilon is zero with constant variance. Although these assumptions are broken sometimes in practice, the Least Squares model still performs well! I hope now you understand as to why we had to perform a logarithmic transformation on our target variable to achieve Normality!" }, { "code": null, "e": 11144, "s": 10931, "text": "The time complexity for standard Least Squares is O(k3) as the time complexity is O(n3) to find the inverse of a matrix, but our matrix result, X^T*X is actually k by k, where k is the number of features/columns." }, { "code": null, "e": 11347, "s": 11144, "text": "Now that we’ve discussed the theoretical background for Least Squares, lets apply it our problem! We can use the LinearRegression object from the sklearn library to implement our Least Squares solution!" }, { "code": null, "e": 11446, "s": 11347, "text": "To assess our model, we can look at the MSE and R2 value both on the testing and training dataset:" }, { "code": null, "e": 12294, "s": 11446, "text": "As we can see from the above barplot on the left hand side, the MSE for both the testing and training sets are extremely low, only around 0.19; however, if you remember, the target variable underwent a Logarithmic Transformation, meaning that an MSE of 0.016 is not relatively small given the scale of the target variable. Therefore, a better measurement is to assess the R2 value, which we can see from the barplot on the right hand side is decent. Our model only explains approximately 79% of the variability of the target variable for the training set and roughly 76% of the variability for the testing set. Although is result is reasonable for some scenarios, for this simple dataset this is known as underfitting, when a model performs poorly at predicting a target variable. We will cover some methodologies on how to fix this problem later." }, { "code": null, "e": 12785, "s": 12294, "text": "One big advantage of Linear Regression over some other Regression models is its simplicity and explanatory power. Each beta coefficient can be assessed to explain how the model is achieving its predictions. Machine Learning models like this are known as White Box Methods, meaning that it is apparent how the model is achieving its output. On the other hand, Machine Learning models where the formulation process on how the prediction was achieved is unknown are known as Black Box Methods." }, { "code": null, "e": 12836, "s": 12785, "text": "For example, here are our beta coefficient values:" }, { "code": null, "e": 13124, "s": 12836, "text": "Unfortunately, because we scaled the target variable using a logarithm, the coefficient values are in terms of explaining the log of the target. To combat this, we can rescale the coefficients by the inverse of logarithm, the exponentiation. Here are our exponentiated beta coefficients:" }, { "code": null, "e": 13847, "s": 13124, "text": "The interpretation of exponentiated beta coefficients is the percentage change in the target variable. For example, when the person is a smoker, their medical cost increases by 116.8% ((2.168–1)*100). On the other hand, if the person is not a smoker then their medical cost will decrease by 63.9% ((0.461–1)*100). Essentially, any beta coefficient larger than one imposes an increase percentage of medical costs while any beta coefficient smaller imposes a decrease percentage of medical costs. In addition, we can definitely see that the largest exponentiated beta coefficient belongs to smokers, meaning that variable, whether the person is a smoker, has the largest influence to medical cost out of the other variables." }, { "code": null, "e": 13966, "s": 13847, "text": "Let’s suppose that we did not perform a logarithmic transformation, how would we interpret the beta coefficients then?" }, { "code": null, "e": 14589, "s": 13966, "text": "The interpretation is in terms of the unit scale of the target variable. Because our target variable was measure in dollars, we can see that if a person was a smoker, then their medical cost would increase by $11,907 ; or decrease by $11,907 if they were not a smoker. For age, we can see that as the older the person becomes, their medical cost will increase by $264 per year of age. If we were to look at sex, the coefficients are the same, meaning that medical cost does not go up whether or not the person is male or female. Hopefully you can see the power of interpreting the coefficients of Least Squares Regression." }, { "code": null, "e": 14719, "s": 14589, "text": "One of the main assumptions made under Least Squares is that the errors, epsilon, is Normally distributed with constant Variance:" }, { "code": null, "e": 14910, "s": 14719, "text": "One can check this assumption by plotting the residuals, f(x)-y, verses the actual, commonly called a residual plot. Here is our residual plot from our previous model on the training sample:" }, { "code": null, "e": 15898, "s": 14910, "text": "As we can see from above, the variance of our residual errors does not have mean of zero nor constant variance, as it is highly non-linear. In addition, we can see that the squared residuals show a slight upward trend as the target variable approaches its max value. Residual errors with non-constant variance are called heteroscedastic. One way to combat heteroscedasticity is through Weighted Least Squares. Weighted Least Squares is like standard Least Squares; however, each observation is weighted by its own unique value. In this way, observations with larger weights are more favored by the model to fit than smaller weights. To give an example of the power of adding weights, here below we have two prediction lines, one unweighted and one not. As we can see from the weighted prediction, the instances that have the higher weight are going to have a better fit as the model will gravitate to fixing the prediction line about those points more than instances with lesser weights." }, { "code": null, "e": 16054, "s": 15898, "text": "Now it is time for the derivation of the Weighted Least Squares Solution. To start off, we want to minimize the Expectation of the weighted residual error:" }, { "code": null, "e": 16094, "s": 16054, "text": "This can be converted to matrix format:" }, { "code": null, "e": 16181, "s": 16094, "text": "Now the partial derivate can be found and set to zero to find the analytical solution:" }, { "code": null, "e": 16346, "s": 16181, "text": "As we can see from above, the solution is extremely similar to that of Linear Regression, except with a diagonal matrix W, containing the weights for each instance." }, { "code": null, "e": 17321, "s": 16346, "text": "One of the main powers of WLS is the ability to weight different instances to give preference within the model, either to create homoscedasticity, constant variance, or to model better certain records. However, one of the main drawbacks of WLS is how to determine the weights. In our problem, we want to fix our residuals to have constant variance. Below I have depicted the four major types of residual variances found in practice. The top left showcases the ideal, where the variance is constant with a mean of zero. The top right showcases how the residual variance grows with y, revealing a ‘MegaPhone’ type distribution. The bottom left depicts non linear residuals, revealing that our model is lacking the complexity to create an association. Lastly, the bottom right showcases a binomial residual variance. WLS is commonly used only when a binomial or MegaPhone type residual plot is found, as nonlinear residuals can only be fixed the addition of nonlinear features." }, { "code": null, "e": 17435, "s": 17321, "text": "A common solution for Binomial and MegaPhone residuals is to make the weights equal their squared residual error:" }, { "code": null, "e": 17536, "s": 17435, "text": "As we can see, this intuitively makes sense, we weight instances based off how large is their error." }, { "code": null, "e": 17632, "s": 17536, "text": "In sklearn, this is simple, just create another model and add the extra weight_sample argument:" }, { "code": null, "e": 17806, "s": 17632, "text": "If you were to test these weights above, the residual plot would look similar and with similar R2 and MSE scores, this is because our residual variance is highly non linear:" }, { "code": null, "e": 18012, "s": 17806, "text": "For this situation, we only have one solution, try the addition of nonlinear terms in hopes to explain the variance. Which we will cover with Kernel Regression, but first we need to discuss Regularization." }, { "code": null, "e": 18366, "s": 18012, "text": "Suppose we trained a Linear Regression model on a given dataset, and during its application and deployment we found out that it was performing extremely poorly, despite having good MSE and R2 scores on the training data; this is known as overfitting — when the metrics on the Testing Dataset are much worse than the Training dataset. To give an example:" }, { "code": null, "e": 18823, "s": 18366, "text": "As we can see from above, we have a linear trend of points; however, if we were to fit a 10th Degree Polynomial we can artificially minimize both MSE and R2 to zero on our training dataset. Despite this, we can see intuitively that model will generalize poorly when new data is seen. Regularization works by adding a Penalty Term to the loss function that will penalize the parameters of the model; in our case for Linear Regression, the beta coefficients." }, { "code": null, "e": 19222, "s": 18823, "text": "There are two main types of Regularization when it comes to Linear Regression: Ridge and Lasso. First, lets start off with Ridge Regression, commonly called L2 Regularization as its penalty term squares the beta coefficients to obtain the magnitude. The idea behind Ridge Regression is to penalize large beta coefficients. The Loss Function that Ridge Regression tries to minimize is the following:" }, { "code": null, "e": 19647, "s": 19222, "text": "As we can see from above, the Loss function is exactly the same as before, except now with the addition of the penalty term in red. The parameter lambda scales the penalty. For example, if lambda=0, then the function is the same as before in Least Squares; however, as lambda grows larger the model will lead to underfitting as it will penalize the size of the beta coefficients to zero. Lets look at a simple example below:" }, { "code": null, "e": 20427, "s": 19647, "text": "As we can see from above, when using a 20th Degree Polynomial model to approximate the points and lambda=0, we have no penalization and exhibit extreme overfitting in the blue line. As we start to increase lambda to 0.5, denoted by the orange line, we start to truly model the underlying distribution; however, we can see that when lambda=100 in the purple line, our model starts to become a straight line, leading to underfitting as the penalty term forces the coefficients to zero. Choosing the lambda value in practice is either performed on a Validation Set or through Cross-Validation. In this way, we retrain our model on our training dataset with different lambda values and which ever one performs best on our Validation set is chosen to be final for the Testing dataset." }, { "code": null, "e": 20507, "s": 20427, "text": "Mathematically speaking, our loss function can be transformed into matrix form:" }, { "code": null, "e": 20599, "s": 20507, "text": "Where beta can be solved for as previously, by finding the gradient and setting it to zero:" }, { "code": null, "e": 20918, "s": 20599, "text": "Now that we’ve discussed the mathematical theory behind Ridge Regression, lets apply it to our dataset. In practice, one would want to tune the lambda value on a validation set, not the testing set in order to get a good generalization error; however, I am going to do it on the testing set in order to save some room:" }, { "code": null, "e": 21431, "s": 20918, "text": "As we can see from above, as we increase our lambda value, our error on the training and testing set increase drastically; in addition, it appears that the min error on the testing set is around lambda=0. If you remember correctly, our dataset was not failing from overfitting but underfitting! Therefore, it makes no sense to use regularization, which is why our testing error is getting worse instead of better! I just wanted to show how one could use Ridge Regression if your model was exhibiting overfitting!" }, { "code": null, "e": 21607, "s": 21431, "text": "The next regularization method to be covered is Lasso, which is commonly called L1 regularization as its penalty term is built off the absolute value of the beta coefficients:" }, { "code": null, "e": 21955, "s": 21607, "text": "Notice that the only difference between Ridge and Lasso Regularization is that Ridge squares the beta coefficients while Lasso takes the absolute value. The main difference between the two is that Ridge penalizes the size of the beta coefficients, whereas Lasso will drive some of the beta coefficient values to zero, leading to feature selection." }, { "code": null, "e": 22032, "s": 21955, "text": "These types of penalty terms can often be rewritten as a constraint problem:" }, { "code": null, "e": 22313, "s": 22032, "text": "Because Ridge regression squares the beta coefficients, plotting the constraint would lead to a circle; whereas Lasso would lead to square. If we were to plot two beta coefficients (called w1 and w2 in the graph below) values against each other we might end up with the following:" }, { "code": null, "e": 23000, "s": 22313, "text": "The red line represents the range of values that the two coefficient values can take on, as the coefficient value for w1 increases, the value of w2 starts to decrease. When we plot our L1 norm constraint: |w1|+|w2|≤ lambda, we can see it denoted by the dotted square. Wherever this square box intersects the red line is the chosen value for the coefficients, which we can see would cause w1 to have a value of zero. On the other hand, when we plot our L2 norm constraint: w12+w22≤ lambda, we get a circle, as denoted by the dotted circle. Wherever this circle intersects the red line is the chosen value for the constraints, which we can see are both small nonzero values for w1 and w2." }, { "code": null, "e": 23384, "s": 23000, "text": "Unfortunately, finding the analytical solution for beta in Lasso Regularization is difficult using matrix calculus as the gradient of the absolute value operation is undefined, therefore numerical methods like Coordinate Descent are often utilized. Because of the complex nature of these algorithms I will not detail the math. In python, Lasso Regression can be performed as follows:" }, { "code": null, "e": 23992, "s": 23384, "text": "As we can see from above, as we increase our lambda value, our error on the training and testing set increase drastically, eventually converging around lambda=15. The reason why the error converged is because our lambda value was too large for the model and it drove all the beta coefficients to zero. If you remember correctly, our dataset was not failing from overfitting but underfitting! Therefore, it makes no sense to use regularization, which is why our testing error is getting worse instead of better! I just wanted to showcase how you use Lasso Regression if your model was exhibiting overfitting!" }, { "code": null, "e": 24400, "s": 23992, "text": "The last Regularization technique I am going to introduce is Elastic Net, which came about to harmonize Ridge and Lasso, as Ridge penalizes large coefficients whereas Lasso drives coefficients to zero. The idea behind Elastic Net is create a penalty that will both create feature selection and minimize the size of the weights. There are many different versions of Elastic Net, here are the two most common:" }, { "code": null, "e": 24559, "s": 24400, "text": "As one can see, the penalty term is a combination of Ridge and Lasso, each with their own lambda value to control how much each penalty term affect the model." }, { "code": null, "e": 24949, "s": 24559, "text": "We’ve discussed what to do when a model starts to overfit, but what about when a model underfits? In our example dataset thus far, our model has shown various signs of underfitting: non-linear residuals and poor R2 value on a relatively simple dataset. The most common way to deal with underfitting is to utilize a Kernel. A Kernel is a density function that satisfy three main properties:" }, { "code": null, "e": 25464, "s": 24949, "text": "Kernel Regression is often called a non-parametric regression technique by the Statistics Community. The premise behind using a Kernel is that if we map our input variables to a higher dimension, then the problem can be either easily classified or predicted. The easiest example to see how this works in practice is through a simple classification problem. Suppose we have two groups that we wish to classify using only a line/hyperplane. We can see down below that no line will be able to classify the two groups:" }, { "code": null, "e": 25632, "s": 25464, "text": "However, if we were to transfer the data into a higher dimension (as we can see on the right hand side), now there exists a hyperplane capable of classifying the data." }, { "code": null, "e": 26008, "s": 25632, "text": "To give an example for regression, suppose we only have one feature variable, X, where the target variable Y is equal to X3. We can see below in the bottom left picture that a linear model will fail to accurately represent this data. However, if instead we project our feature variable, X, to a higher dimension, X3, then we can see that our linear model fits a perfect line." }, { "code": null, "e": 26681, "s": 26008, "text": "I hope now I’ve convinced you of the power of projecting our feature variables to higher dimension! However, now the question becomes, how do we do so? First, we need to define a function, commonly denoted as phi, that maps our variables to higher dimensional input space. In Kernel Regression, the way in which this is performed is by Kernel Functions. One of the most popular and basic of Kernels is the Polynomial kernel, which simply raises the feature variables to a power. Lets take for example, the simple case where we have only two variables: x1 and x2; then, we want to map this to a higher dimensional space by simply using a polynomial kernel with the power 2:" }, { "code": null, "e": 27214, "s": 26681, "text": "As we can see from above, we mapped our original data, x1 and x2, to a higher dimension using the phi function with a polynomial power of 2. The only problem is that now our time complexity is proportional to the power of our polynomial, O(k^p). We can reduce this complexity through the Kernel Trick. First, lets recalculate our loss/error metric using phi(x). Note that Kernel Regression utilizes Ridge Regression as the coefficients tend to be extremely large, which is why this method is commonly called Kernel Ridge Regression:" }, { "code": null, "e": 27398, "s": 27214, "text": "We can se that the derivation of beta is actually recursive, meaning the optimal beta is a function of itself. However, if we were to plug this beta back into our error metric we get:" }, { "code": null, "e": 27620, "s": 27398, "text": "As you can see, as we reduce our loss function with the new beta value, we get phi(x_i)*phi(x_j), where phi(x) is a O(k^p) operation, which makes this procedure a very time consuming operation. However, the Trick, is that" }, { "code": null, "e": 27730, "s": 27620, "text": "To give a concrete, example, lets apply this to our previous kernel function, a polynomial with power of two:" }, { "code": null, "e": 28069, "s": 27730, "text": "As we can see from above, the Kernel Trick is the fact that the dot product of of two data points converted to a high dimensional mapping is the same as the high dimensional mapping of the dot product between the two points! This saves a lot of time and computational resources! Now, we can trade this back in to our loss function to get:" }, { "code": null, "e": 28292, "s": 28069, "text": "As we can see from above, the format of the loss function is very similar to Least Squares, except where K=X and alpha=beta. To find the optimal beta, we first find the optimal solution for alpha, then plug that into beta!" }, { "code": null, "e": 28632, "s": 28292, "text": "The time complexity for standard Least Squares is O(k3), but now our matrix result is an n by n matrix as K is n by n; therefore, the time complexity for Kernel Regression is O(n3), which is extremely computationally heavy when there is a lot of data! A common solution is to simply sample data from the total dataset such that n is small." }, { "code": null, "e": 28787, "s": 28632, "text": "Another hyperparameter that needs to be tuned for Kernel regression is choosing which Kernel Function to utilize. The three most common are the following:" }, { "code": null, "e": 28910, "s": 28787, "text": "As we can see from above, each Kernel Function will have its own set of hyperparameters to tune, adding to the complexity." }, { "code": null, "e": 29313, "s": 28910, "text": "Now that we’ve discussed the theoretical background, lets apply Kernel Ridge Regression to our problem! For this example I will only showcase the Polynomial Kernel as it is the most common. Because Kernel Ridge also has a lambda/penalty term, I will show the influence of increasing the penalty term on the testing dataset. Note that in practice one would want to this on a validation set, not testing." }, { "code": null, "e": 29910, "s": 29313, "text": "As we can see from the plot above, increasing the penalty term of lambda actually decreases the R2 value on both testing and training error; however, in practice this might not be the case, so always test out different regularization values. Immediately however, we can see that using Kernel Regression increased the R2 on the testing dataset from 0.76 to 0.83, meaning that our model now explains approximately 83% of the variability of the target variable, little bit better than 76%. Now lets examine the residual plot on the training dataset in comparison with the standard Linear Regression:" }, { "code": null, "e": 30239, "s": 29910, "text": "As we can see from above, our residual plot for Kernel Ridge (on the right hand side) definitely evens out the variance of the residuals to a constant for Y values between 7 and 9; however, the extremely large residuals for Y values between 9 and 10.5 still exist; indicating that our model is underfitting some of those points." }, { "code": null, "e": 30461, "s": 30239, "text": "One of the downfalls of Kernel Regression is that interpretability of the model is lost, as now the beta coefficients are not for the feature variables but the data observations, as the prediction of new data is given by:" }, { "code": null, "e": 30851, "s": 30461, "text": "As we can see, for a new prediction we form a new Kernel Matrix, K, from the dot products between the new data and the data the beta was trained upon, multiplied the alpha vector holding the coefficients. Due to this high dimensional mapping, the interpretability on how the model achieved its results from simply the feature variables is lost, making Kernel Regression a Black Box Method." }, { "code": null, "e": 31210, "s": 30851, "text": "However, you might be thinking to yourself, if Kernel Regression is a black box method because the projection to a higher dimension is summed up to one value between the data instances, why don’t we manually project our feature space? For example, suppose we have the following feature space with three variables and project it to a second degree polynomial:" }, { "code": null, "e": 31911, "s": 31210, "text": "Now we’ve projected our initial data dimension to a higher dimension, allowing us to perform ridge regression to obtain the white-box beta coefficients! However, the problem is that we assume in our Least Squares derivation that (X^T*X) is invertible, which assumes X is linearly independent, meaning no column is a combination of another; but we can clearly see that our new projected data is a linear combination of the original data dimension! In this way, the more higher dimensional terms we add the more likely the inverse does not exist. Kernel Regression escapes this problem as it projects the dot product between data instances, where we assume the data instances are sampled independently." }, { "code": null, "e": 32267, "s": 31911, "text": "For our last method in this deep dive into Regressional Analysis, we will look at a close counterpart to Kernel Ridge Regression, Support Vector Machines (SVMs). To give the basic intuition behind SVMs, lets switch over to the objective of classification, where we want to find a decision boundary to classify two groups and we have three possible models:" }, { "code": null, "e": 32583, "s": 32267, "text": "The problem is that all three decision boundaries correctly classify all points, so now the question is which one is better? The ideal model would be the red line as it is not too close class 1 or class 2. SVM’s solve this problem by adding a margin about the decision boundary, commonly called the Support Vectors:" }, { "code": null, "e": 33149, "s": 32583, "text": "By adding these support vectors, our model has the ability to ‘feel’ out the data to find a decision boundary that can minimize the error within these support vector margins. There are two types of SVM’s, Soft Margin and Hard Margin. Hard Margin makes the model find a decision boundary such that no data instance is inside the support vector margins; whereas Soft Margin allows for instances to be inside the margins. Hard Margin only works on linearly classifiable data and is extremely sensitive to outliers, therefore Soft Margin is the most common type of SVM." }, { "code": null, "e": 33409, "s": 33149, "text": "The width of these support vectors, the margin, is commonly denoted as epsilon. The error function for Support Vector Regression is similar to that of least squares, in that it assumes that the target variable is a linear combination of the feature variables:" }, { "code": null, "e": 33770, "s": 33409, "text": "However, the construction of the Loss/Error function is different than before, as we want to minimize beta to ensure Flatness, meaning we want small beta coefficients so that no feature variable coefficient becomes too large, leading to overfitting. In addition, we also want to minimize the residual error to be less than the margin width, denoted as epsilon:" }, { "code": null, "e": 33965, "s": 33770, "text": "However the problem is that a model might not exist for the given epsilon that satisfies this condition (Hard Margin), leading to a surrogate function using slack variables (called Soft Margin):" }, { "code": null, "e": 34223, "s": 33965, "text": "Unfortunately, the mathematics used to solve this problem are no longer as easy as finding a derivative and setting it equal to zero, but involves quadratic programming. Because of this complex nature, I am going to skip the math to find the final solution." }, { "code": null, "e": 34704, "s": 34223, "text": "Because SVM’s utilize the data matrix X, non linear mapping can be utilized through kernel functions to achieve non linear regressional planes. I am going to skip the math behind this as it gets messy and complicated; however, the idea is the same as mentioned above for Kernel Ridge. The nice thing is that the Kernel Trick still applies here as well, leading to saved time and computation. Now that we’ve talked about the theoretical side of SVM’s, lets apply it to our problem!" }, { "code": null, "e": 35247, "s": 34704, "text": "As with Kernel Ridge Regression, there are a whole host of possible Kernel Function to use, to which this time I am going to test three: Polynomial, RBF, and Linear. In addition, there are two more important hyperparameters that SVM needs, C and epsilon. Epsilon is the margin width and C is regularization term. In practice, only the regularization term, C, is changed as changing the margin width will drastically lead to poor results. Here we have the three kernels with default parameters at various C values evaluated on the testing set." }, { "code": null, "e": 35507, "s": 35247, "text": "As we can see, for this particular dataset, by increasing the C value, almost all three kernels increase the R2 value on the testing set. We can visible see that the RBF kernel performs the best so lets examine its results at C=100 a little bit more in depth:" }, { "code": null, "e": 35900, "s": 35507, "text": "As we can see, our R2 on the testing dataset was better than Least Squares, explaining 81% of the variability of the target variable, but not quite as good as Kernel Ridge Regression with a Polynomial Kernel. However, note that this might not always occur in practice. One could examine the residual plot for this model but it would be very similar to the ones before as the R2 is so similar." }, { "code": null, "e": 36137, "s": 35900, "text": "Unfortunately, as with Kernel Ridge Regression, because SVMs find their coefficients based off kernels instead of the feature variables, the interpretation on how the model achieved its prediction is lost, making SVM a black box method." }, { "code": null, "e": 36278, "s": 36137, "text": "If you’ve made it this far, congratulations! I hope you’ve learned a lot about Regression in the realm of Data Science and Machine Learning!" }, { "code": null, "e": 37122, "s": 36278, "text": "As a quick recap, we introduced our first model, Least Squares, which simply assumed that the target variable was linear combination of the feature variables, to which the goal was to find these coefficients. The problem that arose was that Least Squares is built off a few assumptions, namely that the errors had constant variance and a mean of zero. In practice however, this was often violated as by assessing a residual plot one could observe the non-linearity of the residuals. Assuming the residuals followed a particular trend, such as a binomial or megaphone, Weighted Least Squares could be utilized to create a model to satisfy these assumptions. One of the many pros of Least Squares and its derivates is its open white-box nature, meaning the model prediction can be directly observed by the coefficients for the feature variables." }, { "code": null, "e": 37507, "s": 37122, "text": "In the situation where our model had low training error but yet high test error, we needed to include regularization to prevent overfitting. We discussed three of the most common types of regularization: Ridge, Lasso, and Elastic Net. Ridge regularization shrinks the values of the coefficients while Lasso drives some coefficients to zero, and Elastic Net seeks to harmonize the two." }, { "code": null, "e": 38251, "s": 37507, "text": "On the other end of the spectrum, where instead of overfitting, our model underfitted with both high training and testing errors. In order to fix this problem, we projected our feature space to a higher dimension using kernel functions in hopes that a prediction plane would be able to fit the data. This was performed through two methods — Kernel Ridge Regression and Support Vector Machines. The difference between the two is the formulation of the error/loss function, where SVM’s include a margin of error to minimize as well. However, the problem with these higher dimensional mapping models is that the interpretation of how the model achieved its prediction in terms of the feature variables is lost, making them both black-box methods." }, { "code": null, "e": 38602, "s": 38251, "text": "In practice, there is no best model to utilize. If you are wanting to present your model to businessmen with no background in machine learning then using LR or WLR to explain the importance of different features would be beneficial as they both are white-box methods, then reporting the scores of the black-box methods as they tend to perform better." } ]
Set element to center with Bootstrap
Use class center-block to set an element to center. You can try to run the following code to set the element to center Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet"> <script src = "/scripts/jquery.min.js"></script> <script src = "/bootstrap/js/bootstrap.min.js"></script> </head> <body> <div class = "row"> <div class = "center-block" style = "width:200px; background-color:#ccc; color: white;"> Element at center </div> </div> </body> </html>
[ { "code": null, "e": 1114, "s": 1062, "text": "Use class center-block to set an element to center." }, { "code": null, "e": 1181, "s": 1114, "text": "You can try to run the following code to set the element to center" }, { "code": null, "e": 1191, "s": 1181, "text": "Live Demo" }, { "code": null, "e": 1678, "s": 1191, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"row\">\n <div class = \"center-block\" style = \"width:200px; background-color:#ccc; color: white;\">\n Element at center\n </div>\n </div>\n </body>\n</html>" } ]
Google Maps Feature Extraction with Selenium | by Kyle Pastor | Towards Data Science
I plan this to be the first in a multi-part series of articles about the extraction of Google Maps data and doing some interesting path and time-based studies. A few examples are looking at traffic volumes over time and calculating a “Beauty Score” for a given route. The first step in this journey is to load image data from Google Maps automatically and extract features from those images. Let’s get started. As for my toolkit, we are using Python for everything and leveraging the packages for Selenium (web browser emulator used for automation), Pillow (image handling library) and Matplotlib (plotting data values). My working environment is with Kaggle which is an online data and notebook website which is super useful. To start I must first install the required software to allow us to emulate a browser in order to extract the image data from Google Maps (in addition to some other data). The first step is to download and unpack a distribution of Firefox which will be our automated browser. This is the one I used: http://ftp.mozilla.org/pub/firefox/releases/63.0.3/linux-x86_64/en-US/firefox-63.0.3.tar.bz2 Once extracted note the location of your directory. To make it clean I created a new working directory for this project: mkdir ~/working/firefox Now copy the extracted files into this new directory and set the permissions to allow execution by all. cp -a firefox-63.0.3.tar.bz2/. ~/working/firefoxchmod -R 777 ~/working/firefox Next, I needed to install a driver to allow for communication between python and firefox. While at it I also loaded the Selenium package. Using pip: pip install webdriverdownloaderpip install selenium Finally, I got to my python code. In the Kaggle notebook, I ran the following to actually install the driver. from webdriverdownloader import GeckoDriverDownloadergdd = GeckoDriverDownloader()gdd.download_and_install("v0.23.0") Last but not least install some of the extra packages needed for running the code apt-get install -y libgtk-3-0 libdbus-glib-1-2 xvfb# Setting up the virtual display for Firefoxexport DISPLAY=:99 Remember that I am going to run a web browser in the background and use it to load Google Maps and extract some data. To do this in Python first load the packages from Selenium and instance a Firefox session. # Import the libraries for seleniumfrom selenium import webdriver as selenium_webdriverfrom selenium.webdriver.firefox.options import Options as selenium_optionsfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities as selenium_DesiredCapabilities Next, I set up the browser options. I do not want an actual window of Firefox to get generated so instead I start it in “headless” mode. browser_options = selenium_options()browser_options.add_argument("--headless") Finally, I add the capabilities and instance the browser. # Even more setup!capabilities_argument = selenium_DesiredCapabilities().FIREFOXcapabilities_argument["marionette"] = True# This is the money. We now have the browser object readybrowser = selenium_webdriver.Firefox( options=browser_options, firefox_binary="~/working/firefox/firefox", capabilities=capabilities_argument) At last, I can start to grab some Google Maps data. The next stage was to figure out the Google Maps URL I needed to use so I could navigate to it in Selenium. The format is as follows: https://www.google.com/maps/@{LAT},{LNG},{Z}z Where: LAT: The latitude of the location we would like to see LNG: The longitude of the location Z: The zoom level on the map (bigger means closer) Now I decided to select somewhere near the Toronto waterfront so I could get some park data for the area. # Toronto Waterfront Coordinateslat = 43.640722lng = -79.3811892z = 17 I use this to generate a URL and navigate with my browser: # Build the URLurl = 'https://www.google.com/maps/@' + str(lat) + ',' + str(lng) + ',' + str(z) + 'z'# Setting up the browser window sizebrowser.set_window_size(1024,512)browser.get(url) At this point, the browser was holding all of the information for the website as if I had done it manually (Inspect in the browser). I wanted to take a look at the site so I just used the save_screenshot method in Selenium. browser.save_screenshot("before.png") This is what it saw. One cool thing about Selenium is that you can: A) Parse the HTML to extract any page data B) Execute javascript on the page One extra thing I wanted to do was get the proper scaling of the image. For example, I want to know the actual area of parkland in a given map. What’s nice is that Google Maps includes a scale bar in its render. This means I can select those elements to get the number of feet (what's shown on the actual page) as well as the width of the scale bar in pixels. Therefore I have the number of feet per pixel in the image! Since I am a Canadian I just converted this to meters: # Conversion factor from foot to meterfoot2meter = 0.3048# Doing some light cleanup of the string and converting to floatscale_in_feet = float(browser.find_element_by_id('widget-scale label').text.replace(' ft',''))# Now we have the scale in metersscale_in_meters = scale_in_feet*foot2meter# Get the number of pixels the scale is drawn on, again cleaningpixel_length = float(browser.find_element_by_class_name('widget scale-ruler').value_of_css_property("width").replace('px',''))# Taadaa we have the final scaling MetersPerPixel = scale_in_meters/pixel_length Next I had to clean up the image. As you can see there are some of the overlayed elements on the image (Search bar etc). If I want to extract features from the raw map then I had to get rid of them. # Remove omniboxjs_string = "var element = document.getElementById(\"omnibox container\"); element.remove();"browser.execute_script(js_string)# Remove username and iconsjs_string = "var element = document.getElementById(\"vasquette\"); element.remove();"browser.execute_script(js_string)# Remove bottom scaling barjs_string = "var element = document.getElementsByClassName(\"app viewcard-strip\"); element[0].remove();"browser.execute_script(js_string)# Remove attributions at the bottomjs_string = "var element = document.getElementsByClassName(\"scene footer-container\"); element[0].remove();"browser.execute_script(js_string)ow I take another screenshotbrowser.save_screenshot("waterfront.png") I have a clean image Now that I have my image I want to extract some information on it. For this specific example, I want to know what the area of the green parkland covers in both a percentage and absolute terms (which is why I needed the scaling above). On top of this I want to make a nice animation of how the image is getting scanned and extracting the green. Since I am making animations I want to store the images in separate folders to keep things clean. I do this for the scanning and line chart plotting: mkdir ~/working/framesmkdir ~/working/matplotlib Now I do the meat of the coding. I define a function that is able to scan over the pixels of the image and determine if they fall within a certain RGB range (with some slack). I also pass in an image object to allow for snapshots to be taken during the extraction. I basically overwrite all pixels to be white, and only if the pixel falls within the range I keep the original colours: # The most important part!def find_pixels(img,pixels,colour_set,slack, size): num_px = [] # List to hold the amount of pixels that match # Set the value you want for these variables r_min = colour_set[0]-slack r_max = colour_set[0]+slack g_min = colour_set[1]-slack g_max = colour_set[1]+slack b_min = colour_set[2]-slack b_max = colour_set[2]+slack # Loop over the pixel array for x in range(size[0][0]): num_px_col_count = 0 for y in range(size[0][1]): # Extract the pixel colour data r, g, b,a = pixels[x,y] # Set the pixel to be white by default pixels[x,y]=(int(255), int(255), int(255),int(0)) # Check the see if there is a match! if r >= r_min and r <= r_max and b >= b_min and b <= b_max and g >= g_min and g <= g_max: # If there is a match add one to count num_px_col_count = num_px_col_count + 1; # Colour the pixel back to the original pixels[x,y]=(colour_set[0], colour_set[1], colour_set[2],int(255)) # Append the count to the list num_px.append(num_px_col_count) # Save the image every 10 frames for animation if x % 10 == 0: img.save('~/working/frames/' + str(x)+ '.png')return num_px Now that the function is defined I can actually use it. Start with importing our image and animation libraries from PIL import Image,ImageDraw,ImageFontimport matplotlib.pyplot as plt Open the image, convert to RGBA and load the pixels into an array img = Image.open('~/working/waterfront.png')img = img.convert('RGBA')pixels = img.load() One thing that I had to do manually was determine the colour parkland is given in Google Maps. I just used a tool to select the pixel on the screen to extract this. Now I set it up and give it a slack. The slack is used as a buffer in case some pixels have small colour variability. I pass this into the function we defined above park_colour = [197,232,197];park_slack = 2;num_park = find_pixels(img,pixels,park_colour,park_slack,[img.size]) At this point, I actually have everything I need! Great work! Time to get to animations. Remember how num_park contains the number of pixels that match at each column? This means I can plot this and create yet another animation. Using the image size I create a matplotlib figure and set all the background, axis and elements to white to get a blank slate. # All this is to make a totally blank matplotlib imagefig=plt.figure(figsize=(1024/100,438/100))ax = fig.add_subplot(111)ax.set_facecolor("white")fig.patch.set_facecolor("white")fig.patch.set_alpha(0.0)for spine in ax.spines.values(): spine.set_edgecolor('white')plt.grid(False)plt.axis('off') For image processing I want the images to be of the same scale so I went ahead and set the scaling in the figure ax.set_xlim([-10,1024])ax.set_ylim([-10,438]) Finally, loop over every 10th elements and create a line plot. Once created simply save it! for i in range(0,1024,10): ax.plot(num_park[:i],color='#377e4d',linewidth=3, antialiased=True) plt.savefig('~/working/matplot/'+str(i)+'.png', transparent=True,dpi=130) I have all the images and data I need to make the final results. First I get the total_area from the extraction. Using the MetersPerPixel and the image size I can get the total area in km2 total_area = img.size[0]*img.size[1]*MetersPerPixel/(1000*1000) 0.432 km2 ~20% of image Next, use PIL to create an animated GIF. In the bottom example, I am looping over every 10th frame to capture load the pre-generated images from above and adding them into a list of frames. This frame list will get passed to the animation function to produce the final file. # Loop over every 10 framesframes = []for i in range(0,1024,10): # Load the other images we will overlay googlemap = Image.open('/kaggle/working/frames/'+ str(i)+".png") # Do resampling to get the smoothing effect googlemap = googlemap.resize(googlemap.size, resample=Image.ANTIALIAS)# Append the framesframes.append(googlemap)# Save the final .gifframes[0].save('googlemap.gif', format='GIF', append_images=frames[1::], save_all=True, duration=1, loop=0) As a final measure, I also overlay the animated matplotlib plot. The only difference is that we will use the .paste method of PIL to overlay the images. # Loop over every 10 framesframes = []for i in range(0,1024,10): # Load the other images we will overlay googlemap = Image.open('/kaggle/working/frames/'+ str(i)+".png") matplot = Image.open('/kaggle/working/matplot/'+str(i)+'.png') # Overlay the matplotlib plot animation frames (NB we include offsets for the image here has well (-175,-52) for alignment googlemap.paste(matplot, (-175, -52),matplot) # Do resampling to get the smoothing effect googlemap = googlemap.resize(googlemap.size, resample=Image.ANTIALIAS)# Append the framesframes.append(googlemap)# Save the final .gifframes[0].save('FINAL.gif', format='GIF', append_images=frames[1::], save_all=True, duration=1, loop=0) And there you have it! Now we can do some really interesting stuff like longitudinal traffic scanning or even look at a running route to see how cool the area around is!
[ { "code": null, "e": 582, "s": 171, "text": "I plan this to be the first in a multi-part series of articles about the extraction of Google Maps data and doing some interesting path and time-based studies. A few examples are looking at traffic volumes over time and calculating a “Beauty Score” for a given route. The first step in this journey is to load image data from Google Maps automatically and extract features from those images. Let’s get started." }, { "code": null, "e": 792, "s": 582, "text": "As for my toolkit, we are using Python for everything and leveraging the packages for Selenium (web browser emulator used for automation), Pillow (image handling library) and Matplotlib (plotting data values)." }, { "code": null, "e": 1069, "s": 792, "text": "My working environment is with Kaggle which is an online data and notebook website which is super useful. To start I must first install the required software to allow us to emulate a browser in order to extract the image data from Google Maps (in addition to some other data)." }, { "code": null, "e": 1197, "s": 1069, "text": "The first step is to download and unpack a distribution of Firefox which will be our automated browser. This is the one I used:" }, { "code": null, "e": 1290, "s": 1197, "text": "http://ftp.mozilla.org/pub/firefox/releases/63.0.3/linux-x86_64/en-US/firefox-63.0.3.tar.bz2" }, { "code": null, "e": 1411, "s": 1290, "text": "Once extracted note the location of your directory. To make it clean I created a new working directory for this project:" }, { "code": null, "e": 1435, "s": 1411, "text": "mkdir ~/working/firefox" }, { "code": null, "e": 1539, "s": 1435, "text": "Now copy the extracted files into this new directory and set the permissions to allow execution by all." }, { "code": null, "e": 1618, "s": 1539, "text": "cp -a firefox-63.0.3.tar.bz2/. ~/working/firefoxchmod -R 777 ~/working/firefox" }, { "code": null, "e": 1756, "s": 1618, "text": "Next, I needed to install a driver to allow for communication between python and firefox. While at it I also loaded the Selenium package." }, { "code": null, "e": 1767, "s": 1756, "text": "Using pip:" }, { "code": null, "e": 1819, "s": 1767, "text": "pip install webdriverdownloaderpip install selenium" }, { "code": null, "e": 1929, "s": 1819, "text": "Finally, I got to my python code. In the Kaggle notebook, I ran the following to actually install the driver." }, { "code": null, "e": 2047, "s": 1929, "text": "from webdriverdownloader import GeckoDriverDownloadergdd = GeckoDriverDownloader()gdd.download_and_install(\"v0.23.0\")" }, { "code": null, "e": 2129, "s": 2047, "text": "Last but not least install some of the extra packages needed for running the code" }, { "code": null, "e": 2243, "s": 2129, "text": "apt-get install -y libgtk-3-0 libdbus-glib-1-2 xvfb# Setting up the virtual display for Firefoxexport DISPLAY=:99" }, { "code": null, "e": 2452, "s": 2243, "text": "Remember that I am going to run a web browser in the background and use it to load Google Maps and extract some data. To do this in Python first load the packages from Selenium and instance a Firefox session." }, { "code": null, "e": 2730, "s": 2452, "text": "# Import the libraries for seleniumfrom selenium import webdriver as selenium_webdriverfrom selenium.webdriver.firefox.options import Options as selenium_optionsfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities as selenium_DesiredCapabilities" }, { "code": null, "e": 2867, "s": 2730, "text": "Next, I set up the browser options. I do not want an actual window of Firefox to get generated so instead I start it in “headless” mode." }, { "code": null, "e": 2946, "s": 2867, "text": "browser_options = selenium_options()browser_options.add_argument(\"--headless\")" }, { "code": null, "e": 3004, "s": 2946, "text": "Finally, I add the capabilities and instance the browser." }, { "code": null, "e": 3336, "s": 3004, "text": "# Even more setup!capabilities_argument = selenium_DesiredCapabilities().FIREFOXcapabilities_argument[\"marionette\"] = True# This is the money. We now have the browser object readybrowser = selenium_webdriver.Firefox( options=browser_options, firefox_binary=\"~/working/firefox/firefox\", capabilities=capabilities_argument)" }, { "code": null, "e": 3388, "s": 3336, "text": "At last, I can start to grab some Google Maps data." }, { "code": null, "e": 3522, "s": 3388, "text": "The next stage was to figure out the Google Maps URL I needed to use so I could navigate to it in Selenium. The format is as follows:" }, { "code": null, "e": 3568, "s": 3522, "text": "https://www.google.com/maps/@{LAT},{LNG},{Z}z" }, { "code": null, "e": 3575, "s": 3568, "text": "Where:" }, { "code": null, "e": 3630, "s": 3575, "text": "LAT: The latitude of the location we would like to see" }, { "code": null, "e": 3665, "s": 3630, "text": "LNG: The longitude of the location" }, { "code": null, "e": 3716, "s": 3665, "text": "Z: The zoom level on the map (bigger means closer)" }, { "code": null, "e": 3822, "s": 3716, "text": "Now I decided to select somewhere near the Toronto waterfront so I could get some park data for the area." }, { "code": null, "e": 3893, "s": 3822, "text": "# Toronto Waterfront Coordinateslat = 43.640722lng = -79.3811892z = 17" }, { "code": null, "e": 3952, "s": 3893, "text": "I use this to generate a URL and navigate with my browser:" }, { "code": null, "e": 4142, "s": 3952, "text": "# Build the URLurl = 'https://www.google.com/maps/@' + str(lat) + ',' + str(lng) + ',' + str(z) + 'z'# Setting up the browser window sizebrowser.set_window_size(1024,512)browser.get(url)" }, { "code": null, "e": 4366, "s": 4142, "text": "At this point, the browser was holding all of the information for the website as if I had done it manually (Inspect in the browser). I wanted to take a look at the site so I just used the save_screenshot method in Selenium." }, { "code": null, "e": 4404, "s": 4366, "text": "browser.save_screenshot(\"before.png\")" }, { "code": null, "e": 4425, "s": 4404, "text": "This is what it saw." }, { "code": null, "e": 4472, "s": 4425, "text": "One cool thing about Selenium is that you can:" }, { "code": null, "e": 4515, "s": 4472, "text": "A) Parse the HTML to extract any page data" }, { "code": null, "e": 4549, "s": 4515, "text": "B) Execute javascript on the page" }, { "code": null, "e": 4969, "s": 4549, "text": "One extra thing I wanted to do was get the proper scaling of the image. For example, I want to know the actual area of parkland in a given map. What’s nice is that Google Maps includes a scale bar in its render. This means I can select those elements to get the number of feet (what's shown on the actual page) as well as the width of the scale bar in pixels. Therefore I have the number of feet per pixel in the image!" }, { "code": null, "e": 5024, "s": 4969, "text": "Since I am a Canadian I just converted this to meters:" }, { "code": null, "e": 5591, "s": 5024, "text": "# Conversion factor from foot to meterfoot2meter = 0.3048# Doing some light cleanup of the string and converting to floatscale_in_feet = float(browser.find_element_by_id('widget-scale label').text.replace(' ft',''))# Now we have the scale in metersscale_in_meters = scale_in_feet*foot2meter# Get the number of pixels the scale is drawn on, again cleaningpixel_length = float(browser.find_element_by_class_name('widget scale-ruler').value_of_css_property(\"width\").replace('px',''))# Taadaa we have the final scaling MetersPerPixel = scale_in_meters/pixel_length" }, { "code": null, "e": 5790, "s": 5591, "text": "Next I had to clean up the image. As you can see there are some of the overlayed elements on the image (Search bar etc). If I want to extract features from the raw map then I had to get rid of them." }, { "code": null, "e": 6513, "s": 5790, "text": "# Remove omniboxjs_string = \"var element = document.getElementById(\\\"omnibox container\\\"); element.remove();\"browser.execute_script(js_string)# Remove username and iconsjs_string = \"var element = document.getElementById(\\\"vasquette\\\"); element.remove();\"browser.execute_script(js_string)# Remove bottom scaling barjs_string = \"var element = document.getElementsByClassName(\\\"app viewcard-strip\\\"); element[0].remove();\"browser.execute_script(js_string)# Remove attributions at the bottomjs_string = \"var element = document.getElementsByClassName(\\\"scene footer-container\\\"); element[0].remove();\"browser.execute_script(js_string)ow I take another screenshotbrowser.save_screenshot(\"waterfront.png\")" }, { "code": null, "e": 6534, "s": 6513, "text": "I have a clean image" }, { "code": null, "e": 6878, "s": 6534, "text": "Now that I have my image I want to extract some information on it. For this specific example, I want to know what the area of the green parkland covers in both a percentage and absolute terms (which is why I needed the scaling above). On top of this I want to make a nice animation of how the image is getting scanned and extracting the green." }, { "code": null, "e": 7028, "s": 6878, "text": "Since I am making animations I want to store the images in separate folders to keep things clean. I do this for the scanning and line chart plotting:" }, { "code": null, "e": 7077, "s": 7028, "text": "mkdir ~/working/framesmkdir ~/working/matplotlib" }, { "code": null, "e": 7462, "s": 7077, "text": "Now I do the meat of the coding. I define a function that is able to scan over the pixels of the image and determine if they fall within a certain RGB range (with some slack). I also pass in an image object to allow for snapshots to be taken during the extraction. I basically overwrite all pixels to be white, and only if the pixel falls within the range I keep the original colours:" }, { "code": null, "e": 8811, "s": 7462, "text": "# The most important part!def find_pixels(img,pixels,colour_set,slack, size): num_px = [] # List to hold the amount of pixels that match # Set the value you want for these variables r_min = colour_set[0]-slack r_max = colour_set[0]+slack g_min = colour_set[1]-slack g_max = colour_set[1]+slack b_min = colour_set[2]-slack b_max = colour_set[2]+slack # Loop over the pixel array for x in range(size[0][0]): num_px_col_count = 0 for y in range(size[0][1]): # Extract the pixel colour data r, g, b,a = pixels[x,y] # Set the pixel to be white by default pixels[x,y]=(int(255), int(255), int(255),int(0)) # Check the see if there is a match! if r >= r_min and r <= r_max and b >= b_min and b <= b_max and g >= g_min and g <= g_max: # If there is a match add one to count num_px_col_count = num_px_col_count + 1; # Colour the pixel back to the original pixels[x,y]=(colour_set[0], colour_set[1], colour_set[2],int(255)) # Append the count to the list num_px.append(num_px_col_count) # Save the image every 10 frames for animation if x % 10 == 0: img.save('~/working/frames/' + str(x)+ '.png')return num_px" }, { "code": null, "e": 8922, "s": 8811, "text": "Now that the function is defined I can actually use it. Start with importing our image and animation libraries" }, { "code": null, "e": 8995, "s": 8922, "text": "from PIL import Image,ImageDraw,ImageFontimport matplotlib.pyplot as plt" }, { "code": null, "e": 9061, "s": 8995, "text": "Open the image, convert to RGBA and load the pixels into an array" }, { "code": null, "e": 9150, "s": 9061, "text": "img = Image.open('~/working/waterfront.png')img = img.convert('RGBA')pixels = img.load()" }, { "code": null, "e": 9480, "s": 9150, "text": "One thing that I had to do manually was determine the colour parkland is given in Google Maps. I just used a tool to select the pixel on the screen to extract this. Now I set it up and give it a slack. The slack is used as a buffer in case some pixels have small colour variability. I pass this into the function we defined above" }, { "code": null, "e": 9592, "s": 9480, "text": "park_colour = [197,232,197];park_slack = 2;num_park = find_pixels(img,pixels,park_colour,park_slack,[img.size])" }, { "code": null, "e": 9948, "s": 9592, "text": "At this point, I actually have everything I need! Great work! Time to get to animations. Remember how num_park contains the number of pixels that match at each column? This means I can plot this and create yet another animation. Using the image size I create a matplotlib figure and set all the background, axis and elements to white to get a blank slate." }, { "code": null, "e": 10245, "s": 9948, "text": "# All this is to make a totally blank matplotlib imagefig=plt.figure(figsize=(1024/100,438/100))ax = fig.add_subplot(111)ax.set_facecolor(\"white\")fig.patch.set_facecolor(\"white\")fig.patch.set_alpha(0.0)for spine in ax.spines.values(): spine.set_edgecolor('white')plt.grid(False)plt.axis('off')" }, { "code": null, "e": 10358, "s": 10245, "text": "For image processing I want the images to be of the same scale so I went ahead and set the scaling in the figure" }, { "code": null, "e": 10404, "s": 10358, "text": "ax.set_xlim([-10,1024])ax.set_ylim([-10,438])" }, { "code": null, "e": 10496, "s": 10404, "text": "Finally, loop over every 10th elements and create a line plot. Once created simply save it!" }, { "code": null, "e": 10685, "s": 10496, "text": "for i in range(0,1024,10): ax.plot(num_park[:i],color='#377e4d',linewidth=3, antialiased=True) plt.savefig('~/working/matplot/'+str(i)+'.png', transparent=True,dpi=130)" }, { "code": null, "e": 10750, "s": 10685, "text": "I have all the images and data I need to make the final results." }, { "code": null, "e": 10874, "s": 10750, "text": "First I get the total_area from the extraction. Using the MetersPerPixel and the image size I can get the total area in km2" }, { "code": null, "e": 10938, "s": 10874, "text": "total_area = img.size[0]*img.size[1]*MetersPerPixel/(1000*1000)" }, { "code": null, "e": 10962, "s": 10938, "text": "0.432 km2 ~20% of image" }, { "code": null, "e": 11237, "s": 10962, "text": "Next, use PIL to create an animated GIF. In the bottom example, I am looping over every 10th frame to capture load the pre-generated images from above and adding them into a list of frames. This frame list will get passed to the animation function to produce the final file." }, { "code": null, "e": 11715, "s": 11237, "text": "# Loop over every 10 framesframes = []for i in range(0,1024,10): # Load the other images we will overlay googlemap = Image.open('/kaggle/working/frames/'+ str(i)+\".png\") # Do resampling to get the smoothing effect googlemap = googlemap.resize(googlemap.size, resample=Image.ANTIALIAS)# Append the framesframes.append(googlemap)# Save the final .gifframes[0].save('googlemap.gif', format='GIF', append_images=frames[1::], save_all=True, duration=1, loop=0)" }, { "code": null, "e": 11868, "s": 11715, "text": "As a final measure, I also overlay the animated matplotlib plot. The only difference is that we will use the .paste method of PIL to overlay the images." }, { "code": null, "e": 12583, "s": 11868, "text": "# Loop over every 10 framesframes = []for i in range(0,1024,10): # Load the other images we will overlay googlemap = Image.open('/kaggle/working/frames/'+ str(i)+\".png\") matplot = Image.open('/kaggle/working/matplot/'+str(i)+'.png') # Overlay the matplotlib plot animation frames (NB we include offsets for the image here has well (-175,-52) for alignment googlemap.paste(matplot, (-175, -52),matplot) # Do resampling to get the smoothing effect googlemap = googlemap.resize(googlemap.size, resample=Image.ANTIALIAS)# Append the framesframes.append(googlemap)# Save the final .gifframes[0].save('FINAL.gif', format='GIF', append_images=frames[1::], save_all=True, duration=1, loop=0)" } ]
How to Scrape the Web using Python with ScraPy Spiders | by Luciano Strika | Towards Data Science
Sometimes Kaggle is not enough, and you need to generate your own data set. Maybe you need pictures of spiders for this crazy Convolutional Neural Network you’re training, or maybe you want to scrape the NSFW subreddits for, um, scientific purposes. Whatever your reasons, scraping the web can give you very interesting data, and help you compile awesome data sets. In this article we’ll use ScraPy to scrape a Reddit subreddit and get pictures.Some will tell me using Reddit’s API is a much more practical method to get their data, and that’s strictly true. So true, I’ll probably write an article about it soon. But as long as we do it in a very small dose, and don’t overwork Reddit’s busy servers, it should be alright. So keep in mind, this tutorial is for educational purposes only, and if you ever need Reddit’s data you should use the official channels, like their awesome API. So how do we go about Scraping a website? Let’s start from the beginning. First we’ll go into reddit.com/robots.txt. It’s customary for a site to make their robots.txt file accessible from their main domain. It respects the following format: User-agent: <pattern>Disallow: <patterns> Where User-agent describes a type of device (we fall in *, the wildcard pattern), and Disallow points to a list of url-patterns we can’t crawl. I don’t see /r/* in there, so I think it’s ok to scrape a subreddit’s main page.I’d still advise you to use the API for any serious project, as a matter of etiquette. Not respecting a site’s robots.txt file may have legal ramifications, but it mainly just makes you look like a mean person, and we don’t want that. In order to scrape a website in Python, we’ll use ScraPy, its main scraping framework. Some people prefer BeautifulSoup, but I find ScraPy to be more dynamic. ScraPy’s basic units for scraping are called spiders, and we’ll start off this program by creating an empty one. So, first of all, we’ll install ScraPy: pip install --user scrapy And then we’ll start a ScraPy project: scrapy startproject project_name Here you can enter anything instead of project_name. What this command will do is create a directory with a lot of files and python scripts in it. Now for our last initialization command, we’ll create our first spider. To do that we’ll run scrapy’s genspider command, which takes a spider’s name and a domain url as its arguments. I’ll name mine kitten-getter (beware: spoilers) and crawl reddit.com/r/cats. scrapy genspider kitten_getter reddit.com/r/cats Now we’ll just go into the /spiders directory and not focus in the rest. As always, I’ve made my code available in this GitHub project. In the spiders directory, we’ll open the file called kitten_getter.py and paste this code: What’s happening here? Well, each spider needs 3 things: a parse method, a start_requests method, and a name. The spider’s name will be used whenever we start the spider from the console. Running the spider from the console will make it start from the start_requests routine. We make the routine do http requests on a list of urls, and call our parse method on their http responses. In order to run this, all we have to do is open our terminal in the project’s directory and run: scrapy crawl kitten_getter To set your spiders free! Let them roam the web, snatching its precious data. If you run that command, it will run the spider we just wrote, so it’ll make a request, get the HTML for the first url in the url_list we supplied, and parse it the way we asked it to. In this case, all we’re doing is writing the whole response straight into a (~140Kb in size) file called ‘kitten_response0’. If you open it, you’ll see it’s just the HTML code for the website we scraped. This’ll come in handy for our next goal. If you go to the link reddit.com/r/cats with the intention of scraping the subreddit for kitten pictures, you’ll notice there are two kinds of posts. Posts that link to their comments section when clicked. Posts that lead straight to a pic We noticed also that we can’t scrape anything that matches reddit.com/r/*/comments/* without violating robots.txt, so extracting a picture from a post would be wrong. We can however get the picture URLs if they’re directly linked from the subreddit’s main page. We see those links are always the href property in an <a> tag, so what we’ll do to get them is call the the response object’s xpath method. xPath is a way to move in a website’s HTML tree and get some of its elements. Scrapy also provides us with the css method, which allows for a different way of indexing and tagging elements. I personally find right clicking an element in the browser, hitting inspect and then copy xpath is a quick way to get started, and then I just play around with the output a bit. In this particular case, since all we need is the href value for each <a> element, we’ll call response.xpath(‘//a/@href’) on the response, which will return an iterator for every href value (an object from the ScraPy library). We then extract the string form of that value by calling the extract method, and check whether it’s actually a link to an image by seeing if it ends with ‘.png’ or ‘.jpg’. Here’s the whole improved parse method, which now also creates an html file to display all the images without downloading them: So we make our spider crawl again, and the output should look something like this: Crawled (200) <GET https://www.reddit.com/r/cats/> (referer: None)https://i.imgur.com/Au0aqkj.jpghttps://i.imgur.com/Xw90WFo.jpghttps://i.imgur.com/fOINLvP.jpg Where each link is a cute kitten’s picture. As a bonus, the file kittens.html should be overflowing with cuteness. That’s it! You’ve successfully crawled your first site! Suppose instead of making an HTML file, we wanted to download the images. What we’d do then is import Python’s requests library, and the unicodedata one. Requests is gonna do the grunt work, but we’ll need unicodedata since extracted strings are in unicode by default, and requests expects an ASCII one. Now instead of the parse method, we’ll pass our scrapy.Request function the following function as callback argument: All it does is download an image and save it as a JPG. It also auto increases an index attribute stored in the spider, which gives each image its name. ScraPy provides us with an interactive shell where we can try out different commands, expressions and xpaths. This is a much more productive way of iterating and debugging a spider than running the whole thing over and over with a crawl command. All we need to do to start the shell is running this: scrapy shell ‘http://reddit.com/r/cats’ Of course the URL can be replaced with any other. If we wanted to get more images, we could make the download_pictures method call scrapy.Request on the URL of the next page, which can be obtained from the href attribute of the ‘next page’ button. We could also make the spider take a subreddit as argument, or change the downloaded file extensions. All in all though, the best solution is usually the simplest one, and so using Reddit’s API will save us a lot of headaches. I hope you now feel empowered to make your own spider and, obtain your own data. Please tell me if you found this useful, and what’s a good data set you think you could generate using this tool — the more creative the better. Finally, there is an O’Reilly book I love. I found very useful when I started my Data Science journey, and it exposed me to a different, easier to use (though less flexible) Web Scraping framework. It’s called Data Science from Scratch with Python, and it’s probably half the reason I got my job. If you read this far, you may enjoy it! Follow me for more Python tutorials, tips and tricks!
[ { "code": null, "e": 248, "s": 172, "text": "Sometimes Kaggle is not enough, and you need to generate your own data set." }, { "code": null, "e": 538, "s": 248, "text": "Maybe you need pictures of spiders for this crazy Convolutional Neural Network you’re training, or maybe you want to scrape the NSFW subreddits for, um, scientific purposes. Whatever your reasons, scraping the web can give you very interesting data, and help you compile awesome data sets." }, { "code": null, "e": 1058, "s": 538, "text": "In this article we’ll use ScraPy to scrape a Reddit subreddit and get pictures.Some will tell me using Reddit’s API is a much more practical method to get their data, and that’s strictly true. So true, I’ll probably write an article about it soon. But as long as we do it in a very small dose, and don’t overwork Reddit’s busy servers, it should be alright. So keep in mind, this tutorial is for educational purposes only, and if you ever need Reddit’s data you should use the official channels, like their awesome API." }, { "code": null, "e": 1132, "s": 1058, "text": "So how do we go about Scraping a website? Let’s start from the beginning." }, { "code": null, "e": 1300, "s": 1132, "text": "First we’ll go into reddit.com/robots.txt. It’s customary for a site to make their robots.txt file accessible from their main domain. It respects the following format:" }, { "code": null, "e": 1342, "s": 1300, "text": "User-agent: <pattern>Disallow: <patterns>" }, { "code": null, "e": 1653, "s": 1342, "text": "Where User-agent describes a type of device (we fall in *, the wildcard pattern), and Disallow points to a list of url-patterns we can’t crawl. I don’t see /r/* in there, so I think it’s ok to scrape a subreddit’s main page.I’d still advise you to use the API for any serious project, as a matter of etiquette." }, { "code": null, "e": 1801, "s": 1653, "text": "Not respecting a site’s robots.txt file may have legal ramifications, but it mainly just makes you look like a mean person, and we don’t want that." }, { "code": null, "e": 1960, "s": 1801, "text": "In order to scrape a website in Python, we’ll use ScraPy, its main scraping framework. Some people prefer BeautifulSoup, but I find ScraPy to be more dynamic." }, { "code": null, "e": 2073, "s": 1960, "text": "ScraPy’s basic units for scraping are called spiders, and we’ll start off this program by creating an empty one." }, { "code": null, "e": 2113, "s": 2073, "text": "So, first of all, we’ll install ScraPy:" }, { "code": null, "e": 2139, "s": 2113, "text": "pip install --user scrapy" }, { "code": null, "e": 2178, "s": 2139, "text": "And then we’ll start a ScraPy project:" }, { "code": null, "e": 2212, "s": 2178, "text": "scrapy startproject project_name " }, { "code": null, "e": 2359, "s": 2212, "text": "Here you can enter anything instead of project_name. What this command will do is create a directory with a lot of files and python scripts in it." }, { "code": null, "e": 2620, "s": 2359, "text": "Now for our last initialization command, we’ll create our first spider. To do that we’ll run scrapy’s genspider command, which takes a spider’s name and a domain url as its arguments. I’ll name mine kitten-getter (beware: spoilers) and crawl reddit.com/r/cats." }, { "code": null, "e": 2669, "s": 2620, "text": "scrapy genspider kitten_getter reddit.com/r/cats" }, { "code": null, "e": 2805, "s": 2669, "text": "Now we’ll just go into the /spiders directory and not focus in the rest. As always, I’ve made my code available in this GitHub project." }, { "code": null, "e": 2896, "s": 2805, "text": "In the spiders directory, we’ll open the file called kitten_getter.py and paste this code:" }, { "code": null, "e": 3006, "s": 2896, "text": "What’s happening here? Well, each spider needs 3 things: a parse method, a start_requests method, and a name." }, { "code": null, "e": 3084, "s": 3006, "text": "The spider’s name will be used whenever we start the spider from the console." }, { "code": null, "e": 3172, "s": 3084, "text": "Running the spider from the console will make it start from the start_requests routine." }, { "code": null, "e": 3279, "s": 3172, "text": "We make the routine do http requests on a list of urls, and call our parse method on their http responses." }, { "code": null, "e": 3376, "s": 3279, "text": "In order to run this, all we have to do is open our terminal in the project’s directory and run:" }, { "code": null, "e": 3403, "s": 3376, "text": "scrapy crawl kitten_getter" }, { "code": null, "e": 3481, "s": 3403, "text": "To set your spiders free! Let them roam the web, snatching its precious data." }, { "code": null, "e": 3791, "s": 3481, "text": "If you run that command, it will run the spider we just wrote, so it’ll make a request, get the HTML for the first url in the url_list we supplied, and parse it the way we asked it to. In this case, all we’re doing is writing the whole response straight into a (~140Kb in size) file called ‘kitten_response0’." }, { "code": null, "e": 3911, "s": 3791, "text": "If you open it, you’ll see it’s just the HTML code for the website we scraped. This’ll come in handy for our next goal." }, { "code": null, "e": 4061, "s": 3911, "text": "If you go to the link reddit.com/r/cats with the intention of scraping the subreddit for kitten pictures, you’ll notice there are two kinds of posts." }, { "code": null, "e": 4117, "s": 4061, "text": "Posts that link to their comments section when clicked." }, { "code": null, "e": 4151, "s": 4117, "text": "Posts that lead straight to a pic" }, { "code": null, "e": 4553, "s": 4151, "text": "We noticed also that we can’t scrape anything that matches reddit.com/r/*/comments/* without violating robots.txt, so extracting a picture from a post would be wrong. We can however get the picture URLs if they’re directly linked from the subreddit’s main page. We see those links are always the href property in an <a> tag, so what we’ll do to get them is call the the response object’s xpath method." }, { "code": null, "e": 4921, "s": 4553, "text": "xPath is a way to move in a website’s HTML tree and get some of its elements. Scrapy also provides us with the css method, which allows for a different way of indexing and tagging elements. I personally find right clicking an element in the browser, hitting inspect and then copy xpath is a quick way to get started, and then I just play around with the output a bit." }, { "code": null, "e": 5015, "s": 4921, "text": "In this particular case, since all we need is the href value for each <a> element, we’ll call" }, { "code": null, "e": 5043, "s": 5015, "text": "response.xpath(‘//a/@href’)" }, { "code": null, "e": 5448, "s": 5043, "text": "on the response, which will return an iterator for every href value (an object from the ScraPy library). We then extract the string form of that value by calling the extract method, and check whether it’s actually a link to an image by seeing if it ends with ‘.png’ or ‘.jpg’. Here’s the whole improved parse method, which now also creates an html file to display all the images without downloading them:" }, { "code": null, "e": 5531, "s": 5448, "text": "So we make our spider crawl again, and the output should look something like this:" }, { "code": null, "e": 5691, "s": 5531, "text": "Crawled (200) <GET https://www.reddit.com/r/cats/> (referer: None)https://i.imgur.com/Au0aqkj.jpghttps://i.imgur.com/Xw90WFo.jpghttps://i.imgur.com/fOINLvP.jpg" }, { "code": null, "e": 5806, "s": 5691, "text": "Where each link is a cute kitten’s picture. As a bonus, the file kittens.html should be overflowing with cuteness." }, { "code": null, "e": 5862, "s": 5806, "text": "That’s it! You’ve successfully crawled your first site!" }, { "code": null, "e": 6166, "s": 5862, "text": "Suppose instead of making an HTML file, we wanted to download the images. What we’d do then is import Python’s requests library, and the unicodedata one. Requests is gonna do the grunt work, but we’ll need unicodedata since extracted strings are in unicode by default, and requests expects an ASCII one." }, { "code": null, "e": 6283, "s": 6166, "text": "Now instead of the parse method, we’ll pass our scrapy.Request function the following function as callback argument:" }, { "code": null, "e": 6435, "s": 6283, "text": "All it does is download an image and save it as a JPG. It also auto increases an index attribute stored in the spider, which gives each image its name." }, { "code": null, "e": 6735, "s": 6435, "text": "ScraPy provides us with an interactive shell where we can try out different commands, expressions and xpaths. This is a much more productive way of iterating and debugging a spider than running the whole thing over and over with a crawl command. All we need to do to start the shell is running this:" }, { "code": null, "e": 6775, "s": 6735, "text": "scrapy shell ‘http://reddit.com/r/cats’" }, { "code": null, "e": 6825, "s": 6775, "text": "Of course the URL can be replaced with any other." }, { "code": null, "e": 7125, "s": 6825, "text": "If we wanted to get more images, we could make the download_pictures method call scrapy.Request on the URL of the next page, which can be obtained from the href attribute of the ‘next page’ button. We could also make the spider take a subreddit as argument, or change the downloaded file extensions." }, { "code": null, "e": 7250, "s": 7125, "text": "All in all though, the best solution is usually the simplest one, and so using Reddit’s API will save us a lot of headaches." }, { "code": null, "e": 7476, "s": 7250, "text": "I hope you now feel empowered to make your own spider and, obtain your own data. Please tell me if you found this useful, and what’s a good data set you think you could generate using this tool — the more creative the better." }, { "code": null, "e": 7813, "s": 7476, "text": "Finally, there is an O’Reilly book I love. I found very useful when I started my Data Science journey, and it exposed me to a different, easier to use (though less flexible) Web Scraping framework. It’s called Data Science from Scratch with Python, and it’s probably half the reason I got my job. If you read this far, you may enjoy it!" } ]
Decision Tree in R Programming - GeeksforGeeks
03 Dec, 2021 Decision Trees are useful supervised Machine learning algorithms that have the ability to perform both regression and classification tasks. It is characterized by nodes and branches, where the tests on each attribute are represented at the nodes, the outcome of this procedure is represented at the branches and the class labels are represented at the leaf nodes. Hence it uses a tree-like model based on various decisions that are used to compute their probable outcomes. These types of tree-based algorithms are one of the most widely used algorithms due to the fact that these algorithms are easy to interpret and use. Apart from this, the predictive models developed by this algorithm are found to have good stability and a decent accuracy due to which they are very popular Decision stump: Used for generating a decision tree with just a single split hence also known as a one-level decision tree. It is known for its low predictive performance in most cases due to its simplicity. M5: Known for its precise classification accuracy and its ability to work well to a boosted decision tree and small datasets with too much noise. ID3(Iterative Dichroatiser 3): One of the core and widely used decision tree algorithms uses a top-down, greedy search approach through the given dataset and selects the best attribute for classifying the given dataset C4.5: Also known as the statistical classifier this type of decision tree is derived from its parent ID3. This generates decisions based on a bunch of predictors. C5.0: Being the successor of the C4.5 it broadly has two models namely the basic tree and rule-based model, and its nodes can only predict categorical targets. CHAID: Expanded as Chi-squared Automatic Interaction Detector, this algorithm basically studies the merging variables to justify the outcome on the dependent variable by structuring a predictive model MARS: Expanded as multivariate adaptive regression splines, this algorithm creates a series of piecewise linear models which is used to model irregularities and interactions among variables, they are known for their ability to handle numerical data with greater efficiency. Conditional Inference Trees: This is a type of decision tree that uses a conditional inference framework to recursively segregate the response variables, it’s known for its flexibility and strong foundations. CART: Expanded as Classification and Regression Trees, the values of the target variables are predicted if they are continuous else the necessary classes are identified if they are categorical. As it can be seen that there are many types of decision trees but they fall under two main categories based on the kind of target variable, they are: Categorical Variable Decision Tree: This refers to the decision trees whose target variables have limited value and belong to a particular group. Continuous Variable Decision Tree: This refers to the decision trees whose target variables can take values from a wide range of data types. Let us consider the scenario where a medical company wants to predict whether a person will die if he is exposed to the Virus. The important factor determining this outcome is the strength of his immune system, but the company doesn’t have this info. Since this is an important variable, a decision tree can be constructed to predict the immune strength based on factors like the sleep cycles, cortisol levels, supplement intaken, nutrients derived from food intake, and so on of the person which is all continuous variables. Partitioning: It refers to the process of splitting the data set into subsets. The decision of making strategic splits greatly affects the accuracy of the tree. Many algorithms are used by the tree to split a node into sub-nodes which results in an overall increase in the clarity of the node with respect to the target variable. Various Algorithms like the chi-square and Gini index are used for this purpose and the algorithm with the best efficiency is chosen. Pruning: This refers to the process wherein the branch nodes are turned into leaf nodes which results in the shortening of the branches of the tree. The essence behind this idea is that overfitting is avoided by simpler trees as most complex classification trees may fit the training data well but do an underwhelming job in classifying new values. Selection of the tree: The main goal of this process is to select the smallest tree that fits the data due to the reasons discussed in the pruning section. Entropy: Mainly used to determine the uniformity in the given sample. If the sample is completely uniform then entropy is 0, if it’s uniformly partitioned it is one. Higher the entropy more difficult it becomes to draw conclusions from that information. Information Gain: Statistical property which measures how well training examples are separated based on the target classification. The main idea behind constructing a decision tree is to find an attribute that returns the smallest entropy and the highest information gain. It is basically a measure in the decrease of the total entropy, and it is calculated by computing the total difference between the entropy before split and average entropy after the split of dataset based on the given attribute values. Let us now examine this concept with the help of an example, which in this case is the most widely used “readingSkills” dataset by visualizing a decision tree for it and examining its accuracy. R library(datasets)library(caTools)library(party)library(dplyr)library(magrittr) data("readingSkills")head(readingSkills) Output: As you can see clearly there 4 columns nativeSpeaker, age, shoeSize, and score. Thus basically we are going to find out whether a person is a native speaker or not using the other criteria and see the accuracy of the decision tree model developed in doing so. R sample_data = sample.split(readingSkills, SplitRatio = 0.8)train_data <- subset(readingSkills, sample_data == TRUE)test_data <- subset(readingSkills, sample_data == FALSE) Separating data into training and testing sets is an important part of evaluating data mining models. Hence it is separated into training and testing sets. After a model has been processed by using the training set, you test the model by making predictions against the test set. Because the data in the testing set already contains known values for the attribute that you want to predict, it is easy to determine whether the model’s guesses are correct. R model<- ctree(nativeSpeaker ~ ., train_data)plot(model) ctree(formula, data) where, formula describes the predictor and response variables and data is the data set used. In this case, nativeSpeaker is the response variable and the other predictor variables are represented by, hence when we plot the model we get the following output. Output: From the tree, it is clear that those who have a score less than or equal to 31.08 and whose age is less than or equal to 6 are not native speakers and for those whose score is greater than 31.086 under the same criteria, they are found to be native speakers. R # testing the people who are native speakers# and those who are notpredict_model<-predict(ctree_, test_data) # creates a table to count how many are classified# as native speakers and how many are notm_at <- table(test_data$nativeSpeaker, predict_model)m_at Output The model has correctly predicted 13 people to be non-native speakers but classified an additional 13 to be non-native, and the model by analogy has misclassified none of the passengers to be native speakers when actually they are not. R ac_Test < - sum(diag(table_mat)) / sum(table_mat)print(paste('Accuracy for test is found to be', ac_Test)) Output: Here the accuracy-test from the confusion matrix is calculated and is found to be 0.74. Hence this model is found to predict with an accuracy of 74 %. Thus Decision Trees are very useful algorithms as they are not only used to choose alternatives based on expected values but are also used for the classification of priorities and making predictions. It is up to us to determine the accuracy of using such models in the appropriate applications. Easy to understand and interpret. Does not require Data normalization Doesn’t facilitate the need for scaling of data The pre-processing stage requires lesser effort compared to other major algorithms, hence in a way optimizes the given problem Requires higher time to train the model It has considerable high complexity and takes more time to process the data When the decrease in user input parameter is very small it leads to the termination of the tree Calculations can get very complex at times sagar0719kumar surinderdawra388 kumar_satyam Picked R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change column name of a given DataFrame in R How to Replace specific values in column in R DataFrame ? Adding elements in a vector in R programming - append() method How to change Row Names of DataFrame in R ? Filter data by multiple conditions in R using Dplyr Change Color of Bars in Barchart using ggplot2 in R Loops in R (for, while, repeat) Convert Factor to Numeric and Numeric to Factor in R Programming How to Change Axis Scales in R Plots? Group by function in R using Dplyr
[ { "code": null, "e": 28653, "s": 28625, "text": "\n03 Dec, 2021" }, { "code": null, "e": 29433, "s": 28653, "text": "Decision Trees are useful supervised Machine learning algorithms that have the ability to perform both regression and classification tasks. It is characterized by nodes and branches, where the tests on each attribute are represented at the nodes, the outcome of this procedure is represented at the branches and the class labels are represented at the leaf nodes. Hence it uses a tree-like model based on various decisions that are used to compute their probable outcomes. These types of tree-based algorithms are one of the most widely used algorithms due to the fact that these algorithms are easy to interpret and use. Apart from this, the predictive models developed by this algorithm are found to have good stability and a decent accuracy due to which they are very popular " }, { "code": null, "e": 29641, "s": 29433, "text": "Decision stump: Used for generating a decision tree with just a single split hence also known as a one-level decision tree. It is known for its low predictive performance in most cases due to its simplicity." }, { "code": null, "e": 29787, "s": 29641, "text": "M5: Known for its precise classification accuracy and its ability to work well to a boosted decision tree and small datasets with too much noise." }, { "code": null, "e": 30006, "s": 29787, "text": "ID3(Iterative Dichroatiser 3): One of the core and widely used decision tree algorithms uses a top-down, greedy search approach through the given dataset and selects the best attribute for classifying the given dataset" }, { "code": null, "e": 30169, "s": 30006, "text": "C4.5: Also known as the statistical classifier this type of decision tree is derived from its parent ID3. This generates decisions based on a bunch of predictors." }, { "code": null, "e": 30329, "s": 30169, "text": "C5.0: Being the successor of the C4.5 it broadly has two models namely the basic tree and rule-based model, and its nodes can only predict categorical targets." }, { "code": null, "e": 30530, "s": 30329, "text": "CHAID: Expanded as Chi-squared Automatic Interaction Detector, this algorithm basically studies the merging variables to justify the outcome on the dependent variable by structuring a predictive model" }, { "code": null, "e": 30804, "s": 30530, "text": "MARS: Expanded as multivariate adaptive regression splines, this algorithm creates a series of piecewise linear models which is used to model irregularities and interactions among variables, they are known for their ability to handle numerical data with greater efficiency." }, { "code": null, "e": 31013, "s": 30804, "text": "Conditional Inference Trees: This is a type of decision tree that uses a conditional inference framework to recursively segregate the response variables, it’s known for its flexibility and strong foundations." }, { "code": null, "e": 31207, "s": 31013, "text": "CART: Expanded as Classification and Regression Trees, the values of the target variables are predicted if they are continuous else the necessary classes are identified if they are categorical." }, { "code": null, "e": 31359, "s": 31207, "text": "As it can be seen that there are many types of decision trees but they fall under two main categories based on the kind of target variable, they are: " }, { "code": null, "e": 31505, "s": 31359, "text": "Categorical Variable Decision Tree: This refers to the decision trees whose target variables have limited value and belong to a particular group." }, { "code": null, "e": 31646, "s": 31505, "text": "Continuous Variable Decision Tree: This refers to the decision trees whose target variables can take values from a wide range of data types." }, { "code": null, "e": 32173, "s": 31646, "text": "Let us consider the scenario where a medical company wants to predict whether a person will die if he is exposed to the Virus. The important factor determining this outcome is the strength of his immune system, but the company doesn’t have this info. Since this is an important variable, a decision tree can be constructed to predict the immune strength based on factors like the sleep cycles, cortisol levels, supplement intaken, nutrients derived from food intake, and so on of the person which is all continuous variables. " }, { "code": null, "e": 32637, "s": 32173, "text": "Partitioning: It refers to the process of splitting the data set into subsets. The decision of making strategic splits greatly affects the accuracy of the tree. Many algorithms are used by the tree to split a node into sub-nodes which results in an overall increase in the clarity of the node with respect to the target variable. Various Algorithms like the chi-square and Gini index are used for this purpose and the algorithm with the best efficiency is chosen." }, { "code": null, "e": 32986, "s": 32637, "text": "Pruning: This refers to the process wherein the branch nodes are turned into leaf nodes which results in the shortening of the branches of the tree. The essence behind this idea is that overfitting is avoided by simpler trees as most complex classification trees may fit the training data well but do an underwhelming job in classifying new values." }, { "code": null, "e": 33142, "s": 32986, "text": "Selection of the tree: The main goal of this process is to select the smallest tree that fits the data due to the reasons discussed in the pruning section." }, { "code": null, "e": 33396, "s": 33142, "text": "Entropy: Mainly used to determine the uniformity in the given sample. If the sample is completely uniform then entropy is 0, if it’s uniformly partitioned it is one. Higher the entropy more difficult it becomes to draw conclusions from that information." }, { "code": null, "e": 33905, "s": 33396, "text": "Information Gain: Statistical property which measures how well training examples are separated based on the target classification. The main idea behind constructing a decision tree is to find an attribute that returns the smallest entropy and the highest information gain. It is basically a measure in the decrease of the total entropy, and it is calculated by computing the total difference between the entropy before split and average entropy after the split of dataset based on the given attribute values." }, { "code": null, "e": 34099, "s": 33905, "text": "Let us now examine this concept with the help of an example, which in this case is the most widely used “readingSkills” dataset by visualizing a decision tree for it and examining its accuracy." }, { "code": null, "e": 34101, "s": 34099, "text": "R" }, { "code": "library(datasets)library(caTools)library(party)library(dplyr)library(magrittr) data(\"readingSkills\")head(readingSkills)", "e": 34221, "s": 34101, "text": null }, { "code": null, "e": 34230, "s": 34221, "text": "Output: " }, { "code": null, "e": 34490, "s": 34230, "text": "As you can see clearly there 4 columns nativeSpeaker, age, shoeSize, and score. Thus basically we are going to find out whether a person is a native speaker or not using the other criteria and see the accuracy of the decision tree model developed in doing so." }, { "code": null, "e": 34492, "s": 34490, "text": "R" }, { "code": "sample_data = sample.split(readingSkills, SplitRatio = 0.8)train_data <- subset(readingSkills, sample_data == TRUE)test_data <- subset(readingSkills, sample_data == FALSE)", "e": 34664, "s": 34492, "text": null }, { "code": null, "e": 35118, "s": 34664, "text": "Separating data into training and testing sets is an important part of evaluating data mining models. Hence it is separated into training and testing sets. After a model has been processed by using the training set, you test the model by making predictions against the test set. Because the data in the testing set already contains known values for the attribute that you want to predict, it is easy to determine whether the model’s guesses are correct." }, { "code": null, "e": 35120, "s": 35118, "text": "R" }, { "code": "model<- ctree(nativeSpeaker ~ ., train_data)plot(model)", "e": 35176, "s": 35120, "text": null }, { "code": null, "e": 35197, "s": 35176, "text": "ctree(formula, data)" }, { "code": null, "e": 35456, "s": 35197, "text": "where, formula describes the predictor and response variables and data is the data set used. In this case, nativeSpeaker is the response variable and the other predictor variables are represented by, hence when we plot the model we get the following output. " }, { "code": null, "e": 35466, "s": 35456, "text": "Output: " }, { "code": null, "e": 35726, "s": 35466, "text": "From the tree, it is clear that those who have a score less than or equal to 31.08 and whose age is less than or equal to 6 are not native speakers and for those whose score is greater than 31.086 under the same criteria, they are found to be native speakers." }, { "code": null, "e": 35728, "s": 35726, "text": "R" }, { "code": "# testing the people who are native speakers# and those who are notpredict_model<-predict(ctree_, test_data) # creates a table to count how many are classified# as native speakers and how many are notm_at <- table(test_data$nativeSpeaker, predict_model)m_at", "e": 35986, "s": 35728, "text": null }, { "code": null, "e": 35994, "s": 35986, "text": "Output " }, { "code": null, "e": 36230, "s": 35994, "text": "The model has correctly predicted 13 people to be non-native speakers but classified an additional 13 to be non-native, and the model by analogy has misclassified none of the passengers to be native speakers when actually they are not." }, { "code": null, "e": 36232, "s": 36230, "text": "R" }, { "code": "ac_Test < - sum(diag(table_mat)) / sum(table_mat)print(paste('Accuracy for test is found to be', ac_Test))", "e": 36339, "s": 36232, "text": null }, { "code": null, "e": 36348, "s": 36339, "text": "Output: " }, { "code": null, "e": 36499, "s": 36348, "text": "Here the accuracy-test from the confusion matrix is calculated and is found to be 0.74. Hence this model is found to predict with an accuracy of 74 %." }, { "code": null, "e": 36795, "s": 36499, "text": "Thus Decision Trees are very useful algorithms as they are not only used to choose alternatives based on expected values but are also used for the classification of priorities and making predictions. It is up to us to determine the accuracy of using such models in the appropriate applications. " }, { "code": null, "e": 36829, "s": 36795, "text": "Easy to understand and interpret." }, { "code": null, "e": 36865, "s": 36829, "text": "Does not require Data normalization" }, { "code": null, "e": 36913, "s": 36865, "text": "Doesn’t facilitate the need for scaling of data" }, { "code": null, "e": 37040, "s": 36913, "text": "The pre-processing stage requires lesser effort compared to other major algorithms, hence in a way optimizes the given problem" }, { "code": null, "e": 37080, "s": 37040, "text": "Requires higher time to train the model" }, { "code": null, "e": 37156, "s": 37080, "text": "It has considerable high complexity and takes more time to process the data" }, { "code": null, "e": 37252, "s": 37156, "text": "When the decrease in user input parameter is very small it leads to the termination of the tree" }, { "code": null, "e": 37295, "s": 37252, "text": "Calculations can get very complex at times" }, { "code": null, "e": 37310, "s": 37295, "text": "sagar0719kumar" }, { "code": null, "e": 37327, "s": 37310, "text": "surinderdawra388" }, { "code": null, "e": 37340, "s": 37327, "text": "kumar_satyam" }, { "code": null, "e": 37347, "s": 37340, "text": "Picked" }, { "code": null, "e": 37358, "s": 37347, "text": "R Language" }, { "code": null, "e": 37456, "s": 37358, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37465, "s": 37456, "text": "Comments" }, { "code": null, "e": 37478, "s": 37465, "text": "Old Comments" }, { "code": null, "e": 37523, "s": 37478, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 37581, "s": 37523, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 37644, "s": 37581, "text": "Adding elements in a vector in R programming - append() method" }, { "code": null, "e": 37688, "s": 37644, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 37740, "s": 37688, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 37792, "s": 37740, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 37824, "s": 37792, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 37889, "s": 37824, "text": "Convert Factor to Numeric and Numeric to Factor in R Programming" }, { "code": null, "e": 37927, "s": 37889, "text": "How to Change Axis Scales in R Plots?" } ]
Possible number of Rectangle and Squares with the given set of elements - GeeksforGeeks
23 Mar, 2021 Given ‘N’ number of sticks of length a1, a2, a3...an. The task is to count the number of squares and rectangles possible. Note: One stick should be used only once i.e. either in any of the squares or rectangles.Examples: Input: arr[] = {1, 2, 1, 2} Output: 1 Rectangle with sides 1 1 2 2 Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9} Output: 0 No square or rectangle is possible Approach: Below is the step by step algorithm to solve this problem : Initialize the number of sticks.Initialize all the sticks with it’s lengths in an array.Sort the array in an increasing order.Calculate the number of pairs of sticks with the same length.Divide the total number of pairs by 2, which will be the total possible rectangle and square. Initialize the number of sticks. Initialize all the sticks with it’s lengths in an array. Sort the array in an increasing order. Calculate the number of pairs of sticks with the same length. Divide the total number of pairs by 2, which will be the total possible rectangle and square. Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to find the possible// rectangles and squaresint rectangleSquare(int arr[], int n){ // sort all the sticks sort(arr, arr + n); int count = 0; // calculate all the pair of // sticks with same length for (int i = 0; i < n - 1; i++) { if (arr[i] == arr[i + 1]) { count++; i++; } } // divide the total number of pair // which will be the number of possible // rectangle and square return count / 2;} // Driver codeint main(){ // initialize all the stick lengths int arr[] = { 2, 2, 4, 4, 4, 4, 6, 6, 6, 7, 7, 9, 9 }; int n = sizeof(arr) / sizeof(arr[0]); cout << rectangleSquare(arr, n); return 0;} // Java implementation of above approachimport java.util.Arrays; class GFG{ // Function to find the possible // rectangles and squares static int rectangleSquare(int arr[], int n) { // sort all the sticks Arrays.sort(arr); int count = 0; // calculate all the pair of // sticks with same length for (int i = 0; i < n - 1; i++) { if (arr[i] == arr[i + 1]) { count++; i++; } } // divide the total number of pair // which will be the number of possible // rectangle and square return count / 2; } // Driver code public static void main(String[] args) { // initialize all the stick lengths int arr[] = {2, 2, 4, 4, 4, 4, 6, 6, 6, 7, 7, 9, 9}; int n = arr.length; System.out.println(rectangleSquare(arr, n)); }} // This code is contributed// by PrinciRaj1992 # Python3 implementation of above approach # Function to find the possible# rectangles and squaresdef rectangleSquare( arr, n): # sort all the sticks arr.sort() count = 0 #print(" xx",arr[6]) # calculate all the pair of # sticks with same length k=0 for i in range(n-1): if(k==1): k=0 continue if (arr[i] == arr[i + 1]): count=count+1 k=1 # divide the total number of pair # which will be the number of possible # rectangle and square return count/2 # Driver code if __name__=='__main__': # initialize all the stick lengths arr = [2, 2, 4, 4, 4, 4, 6, 6, 6, 7, 7, 9, 9] n = len(arr) print(rectangleSquare(arr, n)) # this code is written by ash264 // C# implementation of above approachusing System; class GFG{ // Function to find the possible // rectangles and squares static int rectangleSquare(int []arr, int n) { // sort all the sticks Array.Sort(arr); int count = 0; // calculate all the pair of // sticks with same length for (int i = 0; i < n - 1; i++) { if (arr[i] == arr[i + 1]) { count++; i++; } } // divide the total number of pair // which will be the number of possible // rectangle and square return count / 2; } // Driver code public static void Main(String[] args) { // initialize all the stick lengths int []arr = {2, 2, 4, 4, 4, 4, 6, 6, 6, 7, 7, 9, 9}; int n = arr.Length; Console.WriteLine(rectangleSquare(arr, n)); }} // This code has been contributed// by Rajput-Ji <?php// PHP implementation of above approach // Function to find the possible// rectangles and squaresfunction rectangleSquare($arr, $n){ // sort all the sticks sort($arr); $count = 0; // calculate all the pair of // sticks with same length for ($i = 0; $i < $n - 1; $i++) { if ($arr[$i] == $arr[$i + 1]) { $count++; $i++; } } // divide the total number of pair // which will be the number of possible // rectangle and square return ($count / 2);} // Driver code // initialize all the stick lengths$arr = array(2, 2, 4, 4, 4, 4, 6, 6, 6, 7, 7, 9, 9 );$n = sizeof($arr); echo rectangleSquare($arr, $n); // This code is contributed by Sachin.?> <script> // javascript implementation of above approach // Function to find the possible// rectangles and squaresfunction rectangleSquare(arr , n){ // sort all the sticks arr.sort(); var count = 0; // calculate all the pair of // sticks with same length for (i = 0; i < n - 1; i++) { if (arr[i] == arr[i + 1]) { count++; i++; } } // divide the total number of pair // which will be the number of possible // rectangle and square return count / 2;} // Driver code// initialize all the stick lengthsvar arr = [2, 2, 4, 4, 4, 4, 6, 6, 6, 7, 7, 9, 9];var n = arr.length;document.write(rectangleSquare(arr, n)); // This code is contributed by 29AjayKumar </script> 3 ash264 princiraj1992 Rajput-Ji Sach_Code 29AjayKumar Sorting Quiz Technical Scripter 2018 Arrays C++ Programs Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Trapping Rain Water Program to find sum of elements in a given array Reversal algorithm for array rotation Window Sliding Technique Find duplicates in O(n) time and O(1) extra space | Set 1 Header files in C/C++ and its uses How to return multiple values from a function in C or C++? C++ Program for QuickSort C++ program for hashing with chaining delete keyword in C++
[ { "code": null, "e": 24741, "s": 24713, "text": "\n23 Mar, 2021" }, { "code": null, "e": 24964, "s": 24741, "text": "Given ‘N’ number of sticks of length a1, a2, a3...an. The task is to count the number of squares and rectangles possible. Note: One stick should be used only once i.e. either in any of the squares or rectangles.Examples: " }, { "code": null, "e": 25120, "s": 24964, "text": "Input: arr[] = {1, 2, 1, 2}\nOutput: 1\nRectangle with sides 1 1 2 2\n\nInput: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}\nOutput: 0\nNo square or rectangle is possible" }, { "code": null, "e": 25193, "s": 25122, "text": "Approach: Below is the step by step algorithm to solve this problem : " }, { "code": null, "e": 25474, "s": 25193, "text": "Initialize the number of sticks.Initialize all the sticks with it’s lengths in an array.Sort the array in an increasing order.Calculate the number of pairs of sticks with the same length.Divide the total number of pairs by 2, which will be the total possible rectangle and square." }, { "code": null, "e": 25507, "s": 25474, "text": "Initialize the number of sticks." }, { "code": null, "e": 25564, "s": 25507, "text": "Initialize all the sticks with it’s lengths in an array." }, { "code": null, "e": 25603, "s": 25564, "text": "Sort the array in an increasing order." }, { "code": null, "e": 25665, "s": 25603, "text": "Calculate the number of pairs of sticks with the same length." }, { "code": null, "e": 25759, "s": 25665, "text": "Divide the total number of pairs by 2, which will be the total possible rectangle and square." }, { "code": null, "e": 25808, "s": 25759, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 25812, "s": 25808, "text": "C++" }, { "code": null, "e": 25817, "s": 25812, "text": "Java" }, { "code": null, "e": 25825, "s": 25817, "text": "Python3" }, { "code": null, "e": 25828, "s": 25825, "text": "C#" }, { "code": null, "e": 25832, "s": 25828, "text": "PHP" }, { "code": null, "e": 25843, "s": 25832, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to find the possible// rectangles and squaresint rectangleSquare(int arr[], int n){ // sort all the sticks sort(arr, arr + n); int count = 0; // calculate all the pair of // sticks with same length for (int i = 0; i < n - 1; i++) { if (arr[i] == arr[i + 1]) { count++; i++; } } // divide the total number of pair // which will be the number of possible // rectangle and square return count / 2;} // Driver codeint main(){ // initialize all the stick lengths int arr[] = { 2, 2, 4, 4, 4, 4, 6, 6, 6, 7, 7, 9, 9 }; int n = sizeof(arr) / sizeof(arr[0]); cout << rectangleSquare(arr, n); return 0;}", "e": 26624, "s": 25843, "text": null }, { "code": "// Java implementation of above approachimport java.util.Arrays; class GFG{ // Function to find the possible // rectangles and squares static int rectangleSquare(int arr[], int n) { // sort all the sticks Arrays.sort(arr); int count = 0; // calculate all the pair of // sticks with same length for (int i = 0; i < n - 1; i++) { if (arr[i] == arr[i + 1]) { count++; i++; } } // divide the total number of pair // which will be the number of possible // rectangle and square return count / 2; } // Driver code public static void main(String[] args) { // initialize all the stick lengths int arr[] = {2, 2, 4, 4, 4, 4, 6, 6, 6, 7, 7, 9, 9}; int n = arr.length; System.out.println(rectangleSquare(arr, n)); }} // This code is contributed// by PrinciRaj1992", "e": 27588, "s": 26624, "text": null }, { "code": "# Python3 implementation of above approach # Function to find the possible# rectangles and squaresdef rectangleSquare( arr, n): # sort all the sticks arr.sort() count = 0 #print(\" xx\",arr[6]) # calculate all the pair of # sticks with same length k=0 for i in range(n-1): if(k==1): k=0 continue if (arr[i] == arr[i + 1]): count=count+1 k=1 # divide the total number of pair # which will be the number of possible # rectangle and square return count/2 # Driver code if __name__=='__main__': # initialize all the stick lengths arr = [2, 2, 4, 4, 4, 4, 6, 6, 6, 7, 7, 9, 9] n = len(arr) print(rectangleSquare(arr, n)) # this code is written by ash264", "e": 28373, "s": 27588, "text": null }, { "code": "// C# implementation of above approachusing System; class GFG{ // Function to find the possible // rectangles and squares static int rectangleSquare(int []arr, int n) { // sort all the sticks Array.Sort(arr); int count = 0; // calculate all the pair of // sticks with same length for (int i = 0; i < n - 1; i++) { if (arr[i] == arr[i + 1]) { count++; i++; } } // divide the total number of pair // which will be the number of possible // rectangle and square return count / 2; } // Driver code public static void Main(String[] args) { // initialize all the stick lengths int []arr = {2, 2, 4, 4, 4, 4, 6, 6, 6, 7, 7, 9, 9}; int n = arr.Length; Console.WriteLine(rectangleSquare(arr, n)); }} // This code has been contributed// by Rajput-Ji", "e": 29347, "s": 28373, "text": null }, { "code": "<?php// PHP implementation of above approach // Function to find the possible// rectangles and squaresfunction rectangleSquare($arr, $n){ // sort all the sticks sort($arr); $count = 0; // calculate all the pair of // sticks with same length for ($i = 0; $i < $n - 1; $i++) { if ($arr[$i] == $arr[$i + 1]) { $count++; $i++; } } // divide the total number of pair // which will be the number of possible // rectangle and square return ($count / 2);} // Driver code // initialize all the stick lengths$arr = array(2, 2, 4, 4, 4, 4, 6, 6, 6, 7, 7, 9, 9 );$n = sizeof($arr); echo rectangleSquare($arr, $n); // This code is contributed by Sachin.?>", "e": 30087, "s": 29347, "text": null }, { "code": "<script> // javascript implementation of above approach // Function to find the possible// rectangles and squaresfunction rectangleSquare(arr , n){ // sort all the sticks arr.sort(); var count = 0; // calculate all the pair of // sticks with same length for (i = 0; i < n - 1; i++) { if (arr[i] == arr[i + 1]) { count++; i++; } } // divide the total number of pair // which will be the number of possible // rectangle and square return count / 2;} // Driver code// initialize all the stick lengthsvar arr = [2, 2, 4, 4, 4, 4, 6, 6, 6, 7, 7, 9, 9];var n = arr.length;document.write(rectangleSquare(arr, n)); // This code is contributed by 29AjayKumar </script>", "e": 30831, "s": 30087, "text": null }, { "code": null, "e": 30833, "s": 30831, "text": "3" }, { "code": null, "e": 30842, "s": 30835, "text": "ash264" }, { "code": null, "e": 30856, "s": 30842, "text": "princiraj1992" }, { "code": null, "e": 30866, "s": 30856, "text": "Rajput-Ji" }, { "code": null, "e": 30876, "s": 30866, "text": "Sach_Code" }, { "code": null, "e": 30888, "s": 30876, "text": "29AjayKumar" }, { "code": null, "e": 30901, "s": 30888, "text": "Sorting Quiz" }, { "code": null, "e": 30925, "s": 30901, "text": "Technical Scripter 2018" }, { "code": null, "e": 30932, "s": 30925, "text": "Arrays" }, { "code": null, "e": 30945, "s": 30932, "text": "C++ Programs" }, { "code": null, "e": 30952, "s": 30945, "text": "Arrays" }, { "code": null, "e": 31050, "s": 30952, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31059, "s": 31050, "text": "Comments" }, { "code": null, "e": 31072, "s": 31059, "text": "Old Comments" }, { "code": null, "e": 31092, "s": 31072, "text": "Trapping Rain Water" }, { "code": null, "e": 31141, "s": 31092, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 31179, "s": 31141, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 31204, "s": 31179, "text": "Window Sliding Technique" }, { "code": null, "e": 31262, "s": 31204, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 31297, "s": 31262, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 31356, "s": 31297, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 31382, "s": 31356, "text": "C++ Program for QuickSort" }, { "code": null, "e": 31420, "s": 31382, "text": "C++ program for hashing with chaining" } ]
Creating a sqlite database from CSV with Python - GeeksforGeeks
26 Dec, 2020 Prerequisites: Pandas SQLite SQLite is a software library that implements a lightweight relational database management system. It does not require a server to operate unlike other RDBMS such as PostgreSQL, MySQL, Oracle, etc. and applications directly interact with a SQLite database. SQLite is often used for small applications, particularly in embedded systems and mobile applications. To interact with a SQLite database in Python, the sqlite3 module is required. Import module Create a database and establish connection- To establish a connection, we use the sqlite3.connect() function which returns a connection object. Pass the name of the database to be created inside this function. The complete state of a SQLite database is stored in a file with .db extension. If the path is not specified then the new database is created in the current working directory. Syntax: sqlite3.connect(‘database_name.db’) Import csv using read_csv() Syntax: pandas.read_csv(‘file_name.csv’) Write the contents to a new table- The function to_sql() creates a new table from records of the dataframe. Pass the table name and connection object inside this function. The column names of the table are same as the header of the CSV file. By default, the dataframe index is written as a column. Simply toggle the index parameter to False in order to remove this column. Additionally, the if_exists parameter specifies the behavior in case the table name is already being used. It can either raise error (fail), append new values or replace the existing table. pandas.DataFrame.to_sql(table_name, connection_object, if_exists, index) Check the table contents- Create a cursor object and execute the standard SELECT statement to fetch the contents of the newly created table. Close connection Csv file in use: stud_data.csv Program: Python3 # Import required librariesimport sqlite3import pandas as pd # Connect to SQLite databaseconn = sqlite3.connect(r'C:\User\SQLite\University.db') # Load CSV data into Pandas DataFramestud_data = pd.read_csv('stud_data.csv')# Write the data to a sqlite tablestud_data.to_sql('student', conn, if_exists='replace', index=False) # Create a cursor objectcur = conn.cursor()# Fetch and display resultfor row in cur.execute('SELECT * FROM student'): print(row)# Close connection to SQLite databaseconn.close() Output: Picked python-csv Python-database Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Python OOPs Concepts Python | Get unique values from a list Check if element exists in list in Python Python Classes and Objects Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Pandas dataframe.groupby() Create a directory in Python
[ { "code": null, "e": 24212, "s": 24184, "text": "\n26 Dec, 2020" }, { "code": null, "e": 24228, "s": 24212, "text": "Prerequisites: " }, { "code": null, "e": 24235, "s": 24228, "text": "Pandas" }, { "code": null, "e": 24242, "s": 24235, "text": "SQLite" }, { "code": null, "e": 24680, "s": 24242, "text": "SQLite is a software library that implements a lightweight relational database management system. It does not require a server to operate unlike other RDBMS such as PostgreSQL, MySQL, Oracle, etc. and applications directly interact with a SQLite database. SQLite is often used for small applications, particularly in embedded systems and mobile applications. To interact with a SQLite database in Python, the sqlite3 module is required. " }, { "code": null, "e": 24694, "s": 24680, "text": "Import module" }, { "code": null, "e": 24738, "s": 24694, "text": "Create a database and establish connection-" }, { "code": null, "e": 25081, "s": 24738, "text": "To establish a connection, we use the sqlite3.connect() function which returns a connection object. Pass the name of the database to be created inside this function. The complete state of a SQLite database is stored in a file with .db extension. If the path is not specified then the new database is created in the current working directory. " }, { "code": null, "e": 25089, "s": 25081, "text": "Syntax:" }, { "code": null, "e": 25125, "s": 25089, "text": "sqlite3.connect(‘database_name.db’)" }, { "code": null, "e": 25153, "s": 25125, "text": "Import csv using read_csv()" }, { "code": null, "e": 25161, "s": 25153, "text": "Syntax:" }, { "code": null, "e": 25194, "s": 25161, "text": "pandas.read_csv(‘file_name.csv’)" }, { "code": null, "e": 25229, "s": 25194, "text": "Write the contents to a new table-" }, { "code": null, "e": 25757, "s": 25229, "text": "The function to_sql() creates a new table from records of the dataframe. Pass the table name and connection object inside this function. The column names of the table are same as the header of the CSV file. By default, the dataframe index is written as a column. Simply toggle the index parameter to False in order to remove this column. Additionally, the if_exists parameter specifies the behavior in case the table name is already being used. It can either raise error (fail), append new values or replace the existing table." }, { "code": null, "e": 25830, "s": 25757, "text": "pandas.DataFrame.to_sql(table_name, connection_object, if_exists, index)" }, { "code": null, "e": 25856, "s": 25830, "text": "Check the table contents-" }, { "code": null, "e": 25972, "s": 25856, "text": "Create a cursor object and execute the standard SELECT statement to fetch the contents of the newly created table. " }, { "code": null, "e": 25989, "s": 25972, "text": "Close connection" }, { "code": null, "e": 26020, "s": 25989, "text": "Csv file in use: stud_data.csv" }, { "code": null, "e": 26029, "s": 26020, "text": "Program:" }, { "code": null, "e": 26037, "s": 26029, "text": "Python3" }, { "code": "# Import required librariesimport sqlite3import pandas as pd # Connect to SQLite databaseconn = sqlite3.connect(r'C:\\User\\SQLite\\University.db') # Load CSV data into Pandas DataFramestud_data = pd.read_csv('stud_data.csv')# Write the data to a sqlite tablestud_data.to_sql('student', conn, if_exists='replace', index=False) # Create a cursor objectcur = conn.cursor()# Fetch and display resultfor row in cur.execute('SELECT * FROM student'): print(row)# Close connection to SQLite databaseconn.close()", "e": 26545, "s": 26037, "text": null }, { "code": null, "e": 26553, "s": 26545, "text": "Output:" }, { "code": null, "e": 26560, "s": 26553, "text": "Picked" }, { "code": null, "e": 26571, "s": 26560, "text": "python-csv" }, { "code": null, "e": 26587, "s": 26571, "text": "Python-database" }, { "code": null, "e": 26594, "s": 26587, "text": "Python" }, { "code": null, "e": 26692, "s": 26594, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26701, "s": 26692, "text": "Comments" }, { "code": null, "e": 26714, "s": 26701, "text": "Old Comments" }, { "code": null, "e": 26746, "s": 26714, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26802, "s": 26746, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26823, "s": 26802, "text": "Python OOPs Concepts" }, { "code": null, "e": 26862, "s": 26823, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26904, "s": 26862, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26931, "s": 26904, "text": "Python Classes and Objects" }, { "code": null, "e": 26962, "s": 26931, "text": "Python | os.path.join() method" }, { "code": null, "e": 27004, "s": 26962, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27040, "s": 27004, "text": "Python | Pandas dataframe.groupby()" } ]
XGBoost and Imbalanced Classes: Predicting Hotel Cancellations | by Michael Grogan | Towards Data Science
For this reason, boosting is referred to as an ensemble method. In this example, boosting techniques are used to determine whether a customer will cancel their hotel booking or not. The training data is imported from an AWS S3 bucket as follows: import boto3import botocoreimport pandas as pdfrom sagemaker import get_execution_rolerole = get_execution_role()bucket = 'yourbucketname'data_key_train = 'H1full.csv'data_location_train = 's3://{}/{}'.format(bucket, data_key_train)train_df = pd.read_csv(data_location_train) Hotel cancellations represent the response (or dependent) variable, where 1 = cancel, 0 = follow through with booking. The features for analysis are as follows. leadtime = train_df['LeadTime']arrivaldateyear = train_df['ArrivalDateYear']arrivaldateweekno = train_df['ArrivalDateWeekNumber']arrivaldatedayofmonth = train_df['ArrivalDateDayOfMonth']staysweekendnights = train_df['StaysInWeekendNights']staysweeknights = train_df['StaysInWeekNights']adults = train_df['Adults']children = train_df['Children']babies = train_df['Babies']isrepeatedguest = train_df['IsRepeatedGuest'] previouscancellations = train_df['PreviousCancellations']previousbookingsnotcanceled = train_df['PreviousBookingsNotCanceled']bookingchanges = train_df['BookingChanges']agent = train_df['Agent']company = train_df['Company']dayswaitinglist = train_df['DaysInWaitingList']adr = train_df['ADR']rcps = train_df['RequiredCarParkingSpaces']totalsqr = train_df['TotalOfSpecialRequests'] arrivaldatemonth = train_df.ArrivalDateMonth.astype("category").cat.codesarrivaldatemonthcat=pd.Series(arrivaldatemonth)mealcat=train_df.Meal.astype("category").cat.codesmealcat=pd.Series(mealcat)countrycat=train_df.Country.astype("category").cat.codescountrycat=pd.Series(countrycat)marketsegmentcat=train_df.MarketSegment.astype("category").cat.codesmarketsegmentcat=pd.Series(marketsegmentcat)distributionchannelcat=train_df.DistributionChannel.astype("category").cat.codesdistributionchannelcat=pd.Series(distributionchannelcat)reservedroomtypecat=train_df.ReservedRoomType.astype("category").cat.codesreservedroomtypecat=pd.Series(reservedroomtypecat)assignedroomtypecat=train_df.AssignedRoomType.astype("category").cat.codesassignedroomtypecat=pd.Series(assignedroomtypecat)deposittypecat=train_df.DepositType.astype("category").cat.codesdeposittypecat=pd.Series(deposittypecat)customertypecat=train_df.CustomerType.astype("category").cat.codescustomertypecat=pd.Series(customertypecat)reservationstatuscat=train_df.ReservationStatus.astype("category").cat.codesreservationstatuscat=pd.Series(reservationstatuscat) The identified features to be included in the analysis using both the ExtraTreesClassifier and forward and backward feature selection methods are as follows: Lead time Country of origin Market segment Deposit type Customer type Required car parking spaces Arrival Date: Year Arrival Date: Month Arrival Date: Week Number Arrival Date: Day of Month XGBoost is a boosting technique that has become renowned for its execution speed and model performance, and is increasingly being relied upon as a default boosting method — this method implements the gradient boosting decision tree algorithm which works in a similar manner to adaptive boosting, but instance weights are no longer tweaked at every iteration as in the case of AdaBoost. Instead, an attempt is made to fit the new predictor to the residual errors that the previous predictor made. When comparing the accuracy scores, we see that numerous readings are provided in each confusion matrix. However, a particularly important distinction exists between precision and recall. Precision = ((True Positive)/(True Positive + False Positive))Recall = ((True Positive)/(True Positive + False Negative)) The two readings are often at odds with each other, i.e. it is often not possible to increase precision without reducing recall, and vice versa. An assessment as to the ideal metric to use depends in large part on the specific data under analysis. For example, cancer detection screenings that have false negatives (i.e. indicating patients do not have cancer when in fact they do), is a big no-no. Under this scenario, recall is the ideal metric. However, for emails — one might prefer to avoid false positives, i.e. sending an important email to the spam folder when in fact it is legitimate. The f1-score takes both precision and recall into account when devising a more general score. Which would be more important for predicting hotel cancellations? Well, from the point of view of a hotel — they would likely wish to identify customers who are ultimately going to cancel their booking with greater accuracy — this allows the hotel to better allocate rooms and resources. Identifying customers who are not going to cancel their bookings may not necessarily add value to the hotel’s analysis, as the hotel knows that a significant proportion of customers will ultimately follow through with their bookings in any case. The data is firstly split into training and validation data for the H1 dataset, with the H2 dataset being used as the test set for comparing the XGBoost predictions with actual cancellation incidences. Here is an implementation of the XGBoost algorithm: import xgboost as xgbxgb_model = xgb.XGBClassifier(learning_rate=0.001, max_depth = 1, n_estimators = 100, scale_pos_weight=5)xgb_model.fit(x_train, y_train) Note that the scale_pos_weight parameter in this instance is set to 5. The reason for this is to impose greater penalties for errors on the minor class, in this case any incidences of 1 in the response variable, i.e. hotel cancellations. The higher the weight, the greater penalty is imposed on errors on the minor class. The reason for doing this is because there are more 0s than 1s in the dataset — i.e. more customers follow through on their bookings than cancel. Therefore, in order to have an unbiased model, errors on the minor class need to be penalised more severely. Here is the accuracy on the training and validation set: >>> print("Accuracy on training set: {:.3f}".format(xgb_model.score(x_train, y_train)))>>> print("Accuracy on validation set: {:.3f}".format(xgb_model.score(x_val, y_val)))Accuracy on training set: 0.415Accuracy on validation set: 0.414 The predictions are generated: >>> xgb_predict=xgb_model.predict(x_val)>>> xgb_predictarray([1, 1, 1, ..., 1, 1, 1]) Here is a confusion matrix comparing the predicted vs. actual cancellations on the validation set: >>> from sklearn.metrics import classification_report,confusion_matrix>>> print(confusion_matrix(y_val,xgb_predict))>>> print(classification_report(y_val,xgb_predict))[[1393 5873] [ 0 2749]] precision recall f1-score support 0 1.00 0.19 0.32 7266 1 0.32 1.00 0.48 2749 accuracy 0.41 10015 macro avg 0.66 0.60 0.40 10015weighted avg 0.81 0.41 0.37 10015 Note that while the accuracy in terms of the f1-score (41%) is quite low — the recall score for class 1 (cancellations) is 100%. This means that the model is generating many false positives which reduces the overall accuracy — but this has had the effect of increasing recall to 100%, i.e. the model is 100% successful at identifying all the customers who will cancel their booking, even if this results in some false positives. As previously, the test set is also imported from the relevant S3 bucket: data_key_test = 'H2full.csv'data_location_test = 's3://{}/{}'.format(bucket, data_key_test)h2data = pd.read_csv(data_location_test) Here is the subsequent classification performance of the XGBoost model on H2, which is the test set in this instance. >>> from sklearn.metrics import classification_report,confusion_matrix>>> print(confusion_matrix(b,prh2))>>> print(classification_report(b,prh2))[[ 1926 44302] [ 0 33102]] precision recall f1-score support 0 1.00 0.04 0.08 46228 1 0.43 1.00 0.60 33102 accuracy 0.44 79330 macro avg 0.71 0.52 0.34 79330weighted avg 0.76 0.44 0.30 79330 The accuracy as indicated by the f1-score is slightly higher at 44%, but the recall accuracy for class 1 is at 100% once again. In this instance, it is observed that using a scale_pos_weight of 5 resulted in a 100% recall while lowering the f1-score accuracy very significantly to 44%. However, a recall of 100% can also be unreliable. For instance, suppose that the scale_pos_weight was set even higher — which meant that almost all of the predictions indicated a response of 1, i.e. all customers were predicted to cancel their booking. This model has no inherent value if all the customers are predicted to cancel, since there is no longer any way of identifying the unique attributes of customers who are likely to cancel their booking versus those who do not. In this regard, a more balanced solution is to have a high recall while also ensuring that the overall accuracy does not fall excessively low. Here are the confusion matrix results for when respective weights of 2, 3, 4, and 5 are used. [[36926 9302] [12484 20618]] precision recall f1-score support 0 0.75 0.80 0.77 46228 1 0.69 0.62 0.65 33102 accuracy 0.73 79330 macro avg 0.72 0.71 0.71 79330weighted avg 0.72 0.73 0.72 79330 [[12650 33578] [ 1972 31130]] precision recall f1-score support 0 0.87 0.27 0.42 46228 1 0.48 0.94 0.64 33102 accuracy 0.55 79330 macro avg 0.67 0.61 0.53 79330weighted avg 0.70 0.55 0.51 79330 [[ 1926 44302] [ 0 33102]] precision recall f1-score support 0 1.00 0.04 0.08 46228 1 0.43 1.00 0.60 33102 accuracy 0.44 79330 macro avg 0.71 0.52 0.34 79330weighted avg 0.76 0.44 0.30 79330 [[ 1926 44302] [ 0 33102]] precision recall f1-score support 0 1.00 0.04 0.08 46228 1 0.43 1.00 0.60 33102 accuracy 0.44 79330 macro avg 0.71 0.52 0.34 79330weighted avg 0.76 0.44 0.30 79330 When the scale_pos_weight is set to 3, recall comes in at 94% while accuracy is at 55%. When the scale_pos_weight parameter is set to 5, recall is at 100% while the f1-score accuracy falls to 44%. Additionally, note that increasing the parameter from 4 to 5 does not result in any change in either recall or overall accuracy. In this regard, using a weight of 3 allows for a high recall, while still allowing overall classification accuracy to remain above 50% and allows the hotel a baseline to differentiate between the attributes of customers who cancel their booking and those who do not. In this example, you have seen the use of various boosting methods to predict hotel cancellations. As mentioned, the boosting method in this instance was set to impose greater penalties on the minor class, which had the result of lowering the overall accuracy as measure by the f1-score since there were more false positives present. However, the recall score increased vastly as a result — if it is assumed that false positives are more tolerable than false negatives in this situation — then one could argue that the model has performed quite well on this basis. For reference, an SVM model run on the same dataset demonstrated an overall accuracy of 63%, while recall on class 1 decreased to 75%. The datasets and notebooks for this example are available at the MGCodesandStats GitHub repository, along with further research on this topic. Disclaimer: This article is written on an “as is” basis and without warranty. It was written with the intention of providing an overview of data science concepts, and should not be interpreted as professional advice in any way. Antonio, Almedia and Nunes (2019). Hotel Booking Demand Datasets Classification: Precision and Recall Hands-On Machine Learning with Scikit-Learn & TensorFlow by Aurélien Geron Machine Learning Mastery: A Gentle Introduction to XGBoost for Applied Machine Learning What is LightGBM, How to implement it? How to fine tune the parameters?
[ { "code": null, "e": 235, "s": 171, "text": "For this reason, boosting is referred to as an ensemble method." }, { "code": null, "e": 353, "s": 235, "text": "In this example, boosting techniques are used to determine whether a customer will cancel their hotel booking or not." }, { "code": null, "e": 417, "s": 353, "text": "The training data is imported from an AWS S3 bucket as follows:" }, { "code": null, "e": 693, "s": 417, "text": "import boto3import botocoreimport pandas as pdfrom sagemaker import get_execution_rolerole = get_execution_role()bucket = 'yourbucketname'data_key_train = 'H1full.csv'data_location_train = 's3://{}/{}'.format(bucket, data_key_train)train_df = pd.read_csv(data_location_train)" }, { "code": null, "e": 812, "s": 693, "text": "Hotel cancellations represent the response (or dependent) variable, where 1 = cancel, 0 = follow through with booking." }, { "code": null, "e": 854, "s": 812, "text": "The features for analysis are as follows." }, { "code": null, "e": 1651, "s": 854, "text": "leadtime = train_df['LeadTime']arrivaldateyear = train_df['ArrivalDateYear']arrivaldateweekno = train_df['ArrivalDateWeekNumber']arrivaldatedayofmonth = train_df['ArrivalDateDayOfMonth']staysweekendnights = train_df['StaysInWeekendNights']staysweeknights = train_df['StaysInWeekNights']adults = train_df['Adults']children = train_df['Children']babies = train_df['Babies']isrepeatedguest = train_df['IsRepeatedGuest'] previouscancellations = train_df['PreviousCancellations']previousbookingsnotcanceled = train_df['PreviousBookingsNotCanceled']bookingchanges = train_df['BookingChanges']agent = train_df['Agent']company = train_df['Company']dayswaitinglist = train_df['DaysInWaitingList']adr = train_df['ADR']rcps = train_df['RequiredCarParkingSpaces']totalsqr = train_df['TotalOfSpecialRequests']" }, { "code": null, "e": 2772, "s": 1651, "text": "arrivaldatemonth = train_df.ArrivalDateMonth.astype(\"category\").cat.codesarrivaldatemonthcat=pd.Series(arrivaldatemonth)mealcat=train_df.Meal.astype(\"category\").cat.codesmealcat=pd.Series(mealcat)countrycat=train_df.Country.astype(\"category\").cat.codescountrycat=pd.Series(countrycat)marketsegmentcat=train_df.MarketSegment.astype(\"category\").cat.codesmarketsegmentcat=pd.Series(marketsegmentcat)distributionchannelcat=train_df.DistributionChannel.astype(\"category\").cat.codesdistributionchannelcat=pd.Series(distributionchannelcat)reservedroomtypecat=train_df.ReservedRoomType.astype(\"category\").cat.codesreservedroomtypecat=pd.Series(reservedroomtypecat)assignedroomtypecat=train_df.AssignedRoomType.astype(\"category\").cat.codesassignedroomtypecat=pd.Series(assignedroomtypecat)deposittypecat=train_df.DepositType.astype(\"category\").cat.codesdeposittypecat=pd.Series(deposittypecat)customertypecat=train_df.CustomerType.astype(\"category\").cat.codescustomertypecat=pd.Series(customertypecat)reservationstatuscat=train_df.ReservationStatus.astype(\"category\").cat.codesreservationstatuscat=pd.Series(reservationstatuscat)" }, { "code": null, "e": 2930, "s": 2772, "text": "The identified features to be included in the analysis using both the ExtraTreesClassifier and forward and backward feature selection methods are as follows:" }, { "code": null, "e": 2940, "s": 2930, "text": "Lead time" }, { "code": null, "e": 2958, "s": 2940, "text": "Country of origin" }, { "code": null, "e": 2973, "s": 2958, "text": "Market segment" }, { "code": null, "e": 2986, "s": 2973, "text": "Deposit type" }, { "code": null, "e": 3000, "s": 2986, "text": "Customer type" }, { "code": null, "e": 3028, "s": 3000, "text": "Required car parking spaces" }, { "code": null, "e": 3047, "s": 3028, "text": "Arrival Date: Year" }, { "code": null, "e": 3067, "s": 3047, "text": "Arrival Date: Month" }, { "code": null, "e": 3093, "s": 3067, "text": "Arrival Date: Week Number" }, { "code": null, "e": 3120, "s": 3093, "text": "Arrival Date: Day of Month" }, { "code": null, "e": 3616, "s": 3120, "text": "XGBoost is a boosting technique that has become renowned for its execution speed and model performance, and is increasingly being relied upon as a default boosting method — this method implements the gradient boosting decision tree algorithm which works in a similar manner to adaptive boosting, but instance weights are no longer tweaked at every iteration as in the case of AdaBoost. Instead, an attempt is made to fit the new predictor to the residual errors that the previous predictor made." }, { "code": null, "e": 3721, "s": 3616, "text": "When comparing the accuracy scores, we see that numerous readings are provided in each confusion matrix." }, { "code": null, "e": 3804, "s": 3721, "text": "However, a particularly important distinction exists between precision and recall." }, { "code": null, "e": 3926, "s": 3804, "text": "Precision = ((True Positive)/(True Positive + False Positive))Recall = ((True Positive)/(True Positive + False Negative))" }, { "code": null, "e": 4071, "s": 3926, "text": "The two readings are often at odds with each other, i.e. it is often not possible to increase precision without reducing recall, and vice versa." }, { "code": null, "e": 4374, "s": 4071, "text": "An assessment as to the ideal metric to use depends in large part on the specific data under analysis. For example, cancer detection screenings that have false negatives (i.e. indicating patients do not have cancer when in fact they do), is a big no-no. Under this scenario, recall is the ideal metric." }, { "code": null, "e": 4521, "s": 4374, "text": "However, for emails — one might prefer to avoid false positives, i.e. sending an important email to the spam folder when in fact it is legitimate." }, { "code": null, "e": 4615, "s": 4521, "text": "The f1-score takes both precision and recall into account when devising a more general score." }, { "code": null, "e": 4681, "s": 4615, "text": "Which would be more important for predicting hotel cancellations?" }, { "code": null, "e": 5149, "s": 4681, "text": "Well, from the point of view of a hotel — they would likely wish to identify customers who are ultimately going to cancel their booking with greater accuracy — this allows the hotel to better allocate rooms and resources. Identifying customers who are not going to cancel their bookings may not necessarily add value to the hotel’s analysis, as the hotel knows that a significant proportion of customers will ultimately follow through with their bookings in any case." }, { "code": null, "e": 5351, "s": 5149, "text": "The data is firstly split into training and validation data for the H1 dataset, with the H2 dataset being used as the test set for comparing the XGBoost predictions with actual cancellation incidences." }, { "code": null, "e": 5403, "s": 5351, "text": "Here is an implementation of the XGBoost algorithm:" }, { "code": null, "e": 5645, "s": 5403, "text": "import xgboost as xgbxgb_model = xgb.XGBClassifier(learning_rate=0.001, max_depth = 1, n_estimators = 100, scale_pos_weight=5)xgb_model.fit(x_train, y_train)" }, { "code": null, "e": 6113, "s": 5645, "text": "Note that the scale_pos_weight parameter in this instance is set to 5. The reason for this is to impose greater penalties for errors on the minor class, in this case any incidences of 1 in the response variable, i.e. hotel cancellations. The higher the weight, the greater penalty is imposed on errors on the minor class. The reason for doing this is because there are more 0s than 1s in the dataset — i.e. more customers follow through on their bookings than cancel." }, { "code": null, "e": 6222, "s": 6113, "text": "Therefore, in order to have an unbiased model, errors on the minor class need to be penalised more severely." }, { "code": null, "e": 6279, "s": 6222, "text": "Here is the accuracy on the training and validation set:" }, { "code": null, "e": 6516, "s": 6279, "text": ">>> print(\"Accuracy on training set: {:.3f}\".format(xgb_model.score(x_train, y_train)))>>> print(\"Accuracy on validation set: {:.3f}\".format(xgb_model.score(x_val, y_val)))Accuracy on training set: 0.415Accuracy on validation set: 0.414" }, { "code": null, "e": 6547, "s": 6516, "text": "The predictions are generated:" }, { "code": null, "e": 6633, "s": 6547, "text": ">>> xgb_predict=xgb_model.predict(x_val)>>> xgb_predictarray([1, 1, 1, ..., 1, 1, 1])" }, { "code": null, "e": 6732, "s": 6633, "text": "Here is a confusion matrix comparing the predicted vs. actual cancellations on the validation set:" }, { "code": null, "e": 7243, "s": 6732, "text": ">>> from sklearn.metrics import classification_report,confusion_matrix>>> print(confusion_matrix(y_val,xgb_predict))>>> print(classification_report(y_val,xgb_predict))[[1393 5873] [ 0 2749]] precision recall f1-score support 0 1.00 0.19 0.32 7266 1 0.32 1.00 0.48 2749 accuracy 0.41 10015 macro avg 0.66 0.60 0.40 10015weighted avg 0.81 0.41 0.37 10015" }, { "code": null, "e": 7672, "s": 7243, "text": "Note that while the accuracy in terms of the f1-score (41%) is quite low — the recall score for class 1 (cancellations) is 100%. This means that the model is generating many false positives which reduces the overall accuracy — but this has had the effect of increasing recall to 100%, i.e. the model is 100% successful at identifying all the customers who will cancel their booking, even if this results in some false positives." }, { "code": null, "e": 7746, "s": 7672, "text": "As previously, the test set is also imported from the relevant S3 bucket:" }, { "code": null, "e": 7878, "s": 7746, "text": "data_key_test = 'H2full.csv'data_location_test = 's3://{}/{}'.format(bucket, data_key_test)h2data = pd.read_csv(data_location_test)" }, { "code": null, "e": 7996, "s": 7878, "text": "Here is the subsequent classification performance of the XGBoost model on H2, which is the test set in this instance." }, { "code": null, "e": 8489, "s": 7996, "text": ">>> from sklearn.metrics import classification_report,confusion_matrix>>> print(confusion_matrix(b,prh2))>>> print(classification_report(b,prh2))[[ 1926 44302] [ 0 33102]] precision recall f1-score support 0 1.00 0.04 0.08 46228 1 0.43 1.00 0.60 33102 accuracy 0.44 79330 macro avg 0.71 0.52 0.34 79330weighted avg 0.76 0.44 0.30 79330" }, { "code": null, "e": 8617, "s": 8489, "text": "The accuracy as indicated by the f1-score is slightly higher at 44%, but the recall accuracy for class 1 is at 100% once again." }, { "code": null, "e": 8775, "s": 8617, "text": "In this instance, it is observed that using a scale_pos_weight of 5 resulted in a 100% recall while lowering the f1-score accuracy very significantly to 44%." }, { "code": null, "e": 9028, "s": 8775, "text": "However, a recall of 100% can also be unreliable. For instance, suppose that the scale_pos_weight was set even higher — which meant that almost all of the predictions indicated a response of 1, i.e. all customers were predicted to cancel their booking." }, { "code": null, "e": 9254, "s": 9028, "text": "This model has no inherent value if all the customers are predicted to cancel, since there is no longer any way of identifying the unique attributes of customers who are likely to cancel their booking versus those who do not." }, { "code": null, "e": 9397, "s": 9254, "text": "In this regard, a more balanced solution is to have a high recall while also ensuring that the overall accuracy does not fall excessively low." }, { "code": null, "e": 9491, "s": 9397, "text": "Here are the confusion matrix results for when respective weights of 2, 3, 4, and 5 are used." }, { "code": null, "e": 9839, "s": 9491, "text": "[[36926 9302] [12484 20618]] precision recall f1-score support 0 0.75 0.80 0.77 46228 1 0.69 0.62 0.65 33102 accuracy 0.73 79330 macro avg 0.72 0.71 0.71 79330weighted avg 0.72 0.73 0.72 79330" }, { "code": null, "e": 10187, "s": 9839, "text": "[[12650 33578] [ 1972 31130]] precision recall f1-score support 0 0.87 0.27 0.42 46228 1 0.48 0.94 0.64 33102 accuracy 0.55 79330 macro avg 0.67 0.61 0.53 79330weighted avg 0.70 0.55 0.51 79330" }, { "code": null, "e": 10535, "s": 10187, "text": "[[ 1926 44302] [ 0 33102]] precision recall f1-score support 0 1.00 0.04 0.08 46228 1 0.43 1.00 0.60 33102 accuracy 0.44 79330 macro avg 0.71 0.52 0.34 79330weighted avg 0.76 0.44 0.30 79330" }, { "code": null, "e": 10883, "s": 10535, "text": "[[ 1926 44302] [ 0 33102]] precision recall f1-score support 0 1.00 0.04 0.08 46228 1 0.43 1.00 0.60 33102 accuracy 0.44 79330 macro avg 0.71 0.52 0.34 79330weighted avg 0.76 0.44 0.30 79330" }, { "code": null, "e": 11209, "s": 10883, "text": "When the scale_pos_weight is set to 3, recall comes in at 94% while accuracy is at 55%. When the scale_pos_weight parameter is set to 5, recall is at 100% while the f1-score accuracy falls to 44%. Additionally, note that increasing the parameter from 4 to 5 does not result in any change in either recall or overall accuracy." }, { "code": null, "e": 11476, "s": 11209, "text": "In this regard, using a weight of 3 allows for a high recall, while still allowing overall classification accuracy to remain above 50% and allows the hotel a baseline to differentiate between the attributes of customers who cancel their booking and those who do not." }, { "code": null, "e": 12176, "s": 11476, "text": "In this example, you have seen the use of various boosting methods to predict hotel cancellations. As mentioned, the boosting method in this instance was set to impose greater penalties on the minor class, which had the result of lowering the overall accuracy as measure by the f1-score since there were more false positives present. However, the recall score increased vastly as a result — if it is assumed that false positives are more tolerable than false negatives in this situation — then one could argue that the model has performed quite well on this basis. For reference, an SVM model run on the same dataset demonstrated an overall accuracy of 63%, while recall on class 1 decreased to 75%." }, { "code": null, "e": 12319, "s": 12176, "text": "The datasets and notebooks for this example are available at the MGCodesandStats GitHub repository, along with further research on this topic." }, { "code": null, "e": 12547, "s": 12319, "text": "Disclaimer: This article is written on an “as is” basis and without warranty. It was written with the intention of providing an overview of data science concepts, and should not be interpreted as professional advice in any way." }, { "code": null, "e": 12612, "s": 12547, "text": "Antonio, Almedia and Nunes (2019). Hotel Booking Demand Datasets" }, { "code": null, "e": 12649, "s": 12612, "text": "Classification: Precision and Recall" }, { "code": null, "e": 12725, "s": 12649, "text": "Hands-On Machine Learning with Scikit-Learn & TensorFlow by Aurélien Geron" }, { "code": null, "e": 12813, "s": 12725, "text": "Machine Learning Mastery: A Gentle Introduction to XGBoost for Applied Machine Learning" } ]
Extreme Event Forecasting with LSTM Autoencoders | by Marco Cerliani | Towards Data Science
Dealing with extreme event prediction is a frequent nightmare for every Data Scientist. Looking around I found very interesting resources that deal with this problem. Personally, I literally fall in love with the approach released by Uber Researchers. In their papers (two versions are available here and here) they developed an ML solution for daily future prediction of traveler demand. Their methodology stole my attention for its geniality, good explanation, and easy implementation. So my purpose is to reproduce their discovery in pythonic language. I’m very satisfied with this challenge and in the end, I improved my knowledge of regression forecasting. The most important takeaways from this post can be summarized as: Develop a stable approach to evaluate and compare Keras models (avoiding at the same time the problem of weights seed generator); Implement a simple and clever LSTM Autoencoder for new features creation; Improve forecast prediction performance for time series with easy tricks (see step above); Deal with the nested dataset, i.e. problems where we have observations that belong to different entities (for example time series of different stores/engines/people and so on)... in this sense, we develop only a high-performance model for all! But Keep Kalm and let’s proceed step by step. At Uber accurate prediction for completed trips (particularly during special events) provides a series of important benefits: more efficient driver allocation resulting in a decreased wait time for the riders, budget planning and other related tasks. In order to reach high accurate predictions of driver demand for ride-sharing, Uber Researchers developed a high-performance model for time series forecasting. They are able to fit (one-shot) a single model with a lot of heterogeneous time series, coming from different locations/cities. This process permits us to extract relevant time patterns. In the end, they were able to forecast demand, generalizing for different locations/cities, outperforming the classical forecasting methods. For this task Uber made use of an internal dataset of daily trips among different cities, including additional features; i.e. weather information and city-level information. They aimed to forecast the next day’s demand from a fixed window of past observations. Unfortunately, we don’t have at our disposal this kind of data, so we, as Kaggle Fans, chose the nice Avocado Prices Dataset. This data shows historical avocado prices, of two different species, and sales volume in multiple US markets. Our choice was due to the need for a nested dataset with temporal dependency: we have time series for each US market, 54 in total, a number that grows to 108 if we consider one time series for each type (conventional and organic). This data structure is highlighted as important by Uber Researchers because it permits our model to discover important invisible relations. Also, the correlation among series brings advantages for our LSTM Autoencoder during the process of feature extraction. To build our model we utilized the time series of prices at our disposal up to the end of 2017. The first 2 months of 2018 are stored and used as a test set. For our analysis, we will take into consideration also all the provided regressors. The observations are shown with a weakly frequency so our purpose is: given a fixed past window (4 weeks) of features, predict the upcoming weakly price. Due to the absence of exponential growth and trending behavior, we don’t need to scale our price series. In order to solve our prediction task, we replicate the novel model architecture, proposed by Uber, which provides a single model for heterogeneous forecasting. As the below figure shows, the model first primes the network by auto feature extraction, training an LSTM Autoencoder, which is critical to capture complex time-series dynamics at scale. Features vectors are then concatenated with the new input and fed to LSTM Forecaster for prediction. Our forecasting workflow is easy to imagine: we have our initial windows of weekly prices (plus other features) for different markets. We start to train our LSTM Autoencoder on them; next, we remove the encoder and utilize it as a features creator. The second and final step required to train a prediction LSTM model for forecasting. Based on real/existing regressors and the previous artificial generated features, we are able to provide next week’s avocado price prediction. We easily recreate this logic with Keras. Our LSTM Autoencoder is composed of a simple LSTM encoder layer, followed by another simple LSTM decoder. You will understand the utility of dropout during the evaluation, at this point they are harmless, trust me! inputs_ae = Input(shape=(sequence_length, n_features))encoded_ae = LSTM(128, return_sequences=True, dropout=0.5)(inputs_ae, training=True)decoded_ae = LSTM(32, return_sequences=True, dropout=0.5)(encoded_ae, training=True)out_ae = TimeDistributed(Dense(1))(decoded_ae)sequence_autoencoder = Model(inputs_ae, out_ae) We compute features extraction and concatenate the result with other variables. At this point I made a little deviation from the Uber solution: they suggest manipulating the feature vectors extracted by our encoder aggregating them via an ensemble technique (e.g., averaging). I decided to let them original and free. I make this choice because it permits me to achieve better results in my experiments. In the end, the prediction model is another simple LSTM based neural network: inputs = Input(shape=(sequence_length, n_features))lstm = LSTM(128, return_sequences=True, dropout=0.5)(inputs, training=True)lstm = LSTM(32, return_sequences=False, dropout=0.5)(lstm, training=True)dense = Dense(50)(lstm)out = Dense(1)(dense) Finally, we are almost ready to see some results and make predictions. The last steps involve the creation of a rival model and the consequence definition of a robust forecasting methodology for results comparison. Personally, the best way to evaluate two different procedures is to replicate them as much as possible, in order to mark attention only at the points of real interest. In this implementation, I want to show evidence of LSTM Autoencoder power as a tool for relevant feature creation for time series forecasting. In this sense, to evaluate the goodness of our methodology, I decided to develop a new model for price forecasting with the same structure as our previous forecasting NN. The only difference between them is the features they received as input. The first one receives the encoder output plus the external regressors; the second one receives past raw prices plus the external regressors. Time series forecasting is critical in nature for the extreme variability of the domain of interest. In addition, if you try to build a model based on Neural Network your results are also subject to internal weight initialization. To overcome this drawback a number of approaches exist for uncertainty estimation: from Bayesian to those based on the bootstrap theory. In their work Uber Researchers combine Bootstrap and Bayesian approaches to produce a simple, robust and tight uncertainty bound with good coverage and provable convergence properties. This technique is extremely simple and practical... indirectly we have already implemented it! As you can see in the figure below, during the feedforward process, dropout is applied to all layers in both the encoder and the prediction network. As a result, the random dropout in the encoder perturbs the input intelligently in the embedding space, which accounts for potential model misspecification and gets further propagated through the prediction network. Pythonic speaking we have simply to add trainable dropout layers in our Neural Network and reactivate them during prediction (Keras used to cut dropout during prediction). For the final evaluation, we must iterate the calling of the prediction function and store the results. I also compute the scoring of the prediction at each interaction (I chose Mean Absolute Error). We must set the number of times we compute evaluation (100 times in our case). With the scores stored, we are able to compute the mean, the standard deviation, and the relative uncertainty of MAE. We replicate the same procedure for our ‘rival model’ made by only the LSTM prediction network. After averaging scores and computing uncertainty, the final results are better for the LSTM Autoencoder + LSTM Forecaster instead of the single LSTM Forecaster. In this post, I replicate an end-to-end neural network architecture developed at Uber for special event forecasting. I want to emphasize: the power of LSTM Autoencoder in the role of feature extractor; the scalability of this solution to generalize well avoiding training multiple models for every time series; the ability to provide a stable and profitable method for neural networks evaluation. I also remark that this kind of solution suits well when you have at your disposal an adequate number of time series that share common behaviors... It’s not important that these are immediately visible, the Autoencoder makes this for us. CHECK MY GITHUB REPO Keep in touch: Linkedin REFERENCES [1] Deep and Confident Prediction for Time Series at Uber: Lingxue Zhu, Nikolay Laptev [2] Time-series Extreme Event Forecasting with Neural Networks at Uber: Nikolay Laptev, Jason Yosinski, Li Erran Li, Slawek Smyl
[ { "code": null, "e": 834, "s": 172, "text": "Dealing with extreme event prediction is a frequent nightmare for every Data Scientist. Looking around I found very interesting resources that deal with this problem. Personally, I literally fall in love with the approach released by Uber Researchers. In their papers (two versions are available here and here) they developed an ML solution for daily future prediction of traveler demand. Their methodology stole my attention for its geniality, good explanation, and easy implementation. So my purpose is to reproduce their discovery in pythonic language. I’m very satisfied with this challenge and in the end, I improved my knowledge of regression forecasting." }, { "code": null, "e": 900, "s": 834, "text": "The most important takeaways from this post can be summarized as:" }, { "code": null, "e": 1030, "s": 900, "text": "Develop a stable approach to evaluate and compare Keras models (avoiding at the same time the problem of weights seed generator);" }, { "code": null, "e": 1104, "s": 1030, "text": "Implement a simple and clever LSTM Autoencoder for new features creation;" }, { "code": null, "e": 1195, "s": 1104, "text": "Improve forecast prediction performance for time series with easy tricks (see step above);" }, { "code": null, "e": 1439, "s": 1195, "text": "Deal with the nested dataset, i.e. problems where we have observations that belong to different entities (for example time series of different stores/engines/people and so on)... in this sense, we develop only a high-performance model for all!" }, { "code": null, "e": 1485, "s": 1439, "text": "But Keep Kalm and let’s proceed step by step." }, { "code": null, "e": 1736, "s": 1485, "text": "At Uber accurate prediction for completed trips (particularly during special events) provides a series of important benefits: more efficient driver allocation resulting in a decreased wait time for the riders, budget planning and other related tasks." }, { "code": null, "e": 2224, "s": 1736, "text": "In order to reach high accurate predictions of driver demand for ride-sharing, Uber Researchers developed a high-performance model for time series forecasting. They are able to fit (one-shot) a single model with a lot of heterogeneous time series, coming from different locations/cities. This process permits us to extract relevant time patterns. In the end, they were able to forecast demand, generalizing for different locations/cities, outperforming the classical forecasting methods." }, { "code": null, "e": 2485, "s": 2224, "text": "For this task Uber made use of an internal dataset of daily trips among different cities, including additional features; i.e. weather information and city-level information. They aimed to forecast the next day’s demand from a fixed window of past observations." }, { "code": null, "e": 2721, "s": 2485, "text": "Unfortunately, we don’t have at our disposal this kind of data, so we, as Kaggle Fans, chose the nice Avocado Prices Dataset. This data shows historical avocado prices, of two different species, and sales volume in multiple US markets." }, { "code": null, "e": 3212, "s": 2721, "text": "Our choice was due to the need for a nested dataset with temporal dependency: we have time series for each US market, 54 in total, a number that grows to 108 if we consider one time series for each type (conventional and organic). This data structure is highlighted as important by Uber Researchers because it permits our model to discover important invisible relations. Also, the correlation among series brings advantages for our LSTM Autoencoder during the process of feature extraction." }, { "code": null, "e": 3608, "s": 3212, "text": "To build our model we utilized the time series of prices at our disposal up to the end of 2017. The first 2 months of 2018 are stored and used as a test set. For our analysis, we will take into consideration also all the provided regressors. The observations are shown with a weakly frequency so our purpose is: given a fixed past window (4 weeks) of features, predict the upcoming weakly price." }, { "code": null, "e": 3713, "s": 3608, "text": "Due to the absence of exponential growth and trending behavior, we don’t need to scale our price series." }, { "code": null, "e": 4163, "s": 3713, "text": "In order to solve our prediction task, we replicate the novel model architecture, proposed by Uber, which provides a single model for heterogeneous forecasting. As the below figure shows, the model first primes the network by auto feature extraction, training an LSTM Autoencoder, which is critical to capture complex time-series dynamics at scale. Features vectors are then concatenated with the new input and fed to LSTM Forecaster for prediction." }, { "code": null, "e": 4640, "s": 4163, "text": "Our forecasting workflow is easy to imagine: we have our initial windows of weekly prices (plus other features) for different markets. We start to train our LSTM Autoencoder on them; next, we remove the encoder and utilize it as a features creator. The second and final step required to train a prediction LSTM model for forecasting. Based on real/existing regressors and the previous artificial generated features, we are able to provide next week’s avocado price prediction." }, { "code": null, "e": 4682, "s": 4640, "text": "We easily recreate this logic with Keras." }, { "code": null, "e": 4897, "s": 4682, "text": "Our LSTM Autoencoder is composed of a simple LSTM encoder layer, followed by another simple LSTM decoder. You will understand the utility of dropout during the evaluation, at this point they are harmless, trust me!" }, { "code": null, "e": 5213, "s": 4897, "text": "inputs_ae = Input(shape=(sequence_length, n_features))encoded_ae = LSTM(128, return_sequences=True, dropout=0.5)(inputs_ae, training=True)decoded_ae = LSTM(32, return_sequences=True, dropout=0.5)(encoded_ae, training=True)out_ae = TimeDistributed(Dense(1))(decoded_ae)sequence_autoencoder = Model(inputs_ae, out_ae)" }, { "code": null, "e": 5617, "s": 5213, "text": "We compute features extraction and concatenate the result with other variables. At this point I made a little deviation from the Uber solution: they suggest manipulating the feature vectors extracted by our encoder aggregating them via an ensemble technique (e.g., averaging). I decided to let them original and free. I make this choice because it permits me to achieve better results in my experiments." }, { "code": null, "e": 5695, "s": 5617, "text": "In the end, the prediction model is another simple LSTM based neural network:" }, { "code": null, "e": 5939, "s": 5695, "text": "inputs = Input(shape=(sequence_length, n_features))lstm = LSTM(128, return_sequences=True, dropout=0.5)(inputs, training=True)lstm = LSTM(32, return_sequences=False, dropout=0.5)(lstm, training=True)dense = Dense(50)(lstm)out = Dense(1)(dense)" }, { "code": null, "e": 6154, "s": 5939, "text": "Finally, we are almost ready to see some results and make predictions. The last steps involve the creation of a rival model and the consequence definition of a robust forecasting methodology for results comparison." }, { "code": null, "e": 6636, "s": 6154, "text": "Personally, the best way to evaluate two different procedures is to replicate them as much as possible, in order to mark attention only at the points of real interest. In this implementation, I want to show evidence of LSTM Autoencoder power as a tool for relevant feature creation for time series forecasting. In this sense, to evaluate the goodness of our methodology, I decided to develop a new model for price forecasting with the same structure as our previous forecasting NN." }, { "code": null, "e": 6851, "s": 6636, "text": "The only difference between them is the features they received as input. The first one receives the encoder output plus the external regressors; the second one receives past raw prices plus the external regressors." }, { "code": null, "e": 7219, "s": 6851, "text": "Time series forecasting is critical in nature for the extreme variability of the domain of interest. In addition, if you try to build a model based on Neural Network your results are also subject to internal weight initialization. To overcome this drawback a number of approaches exist for uncertainty estimation: from Bayesian to those based on the bootstrap theory." }, { "code": null, "e": 7404, "s": 7219, "text": "In their work Uber Researchers combine Bootstrap and Bayesian approaches to produce a simple, robust and tight uncertainty bound with good coverage and provable convergence properties." }, { "code": null, "e": 7864, "s": 7404, "text": "This technique is extremely simple and practical... indirectly we have already implemented it! As you can see in the figure below, during the feedforward process, dropout is applied to all layers in both the encoder and the prediction network. As a result, the random dropout in the encoder perturbs the input intelligently in the embedding space, which accounts for potential model misspecification and gets further propagated through the prediction network." }, { "code": null, "e": 8036, "s": 7864, "text": "Pythonic speaking we have simply to add trainable dropout layers in our Neural Network and reactivate them during prediction (Keras used to cut dropout during prediction)." }, { "code": null, "e": 8433, "s": 8036, "text": "For the final evaluation, we must iterate the calling of the prediction function and store the results. I also compute the scoring of the prediction at each interaction (I chose Mean Absolute Error). We must set the number of times we compute evaluation (100 times in our case). With the scores stored, we are able to compute the mean, the standard deviation, and the relative uncertainty of MAE." }, { "code": null, "e": 8690, "s": 8433, "text": "We replicate the same procedure for our ‘rival model’ made by only the LSTM prediction network. After averaging scores and computing uncertainty, the final results are better for the LSTM Autoencoder + LSTM Forecaster instead of the single LSTM Forecaster." }, { "code": null, "e": 9087, "s": 8690, "text": "In this post, I replicate an end-to-end neural network architecture developed at Uber for special event forecasting. I want to emphasize: the power of LSTM Autoencoder in the role of feature extractor; the scalability of this solution to generalize well avoiding training multiple models for every time series; the ability to provide a stable and profitable method for neural networks evaluation." }, { "code": null, "e": 9325, "s": 9087, "text": "I also remark that this kind of solution suits well when you have at your disposal an adequate number of time series that share common behaviors... It’s not important that these are immediately visible, the Autoencoder makes this for us." }, { "code": null, "e": 9346, "s": 9325, "text": "CHECK MY GITHUB REPO" }, { "code": null, "e": 9370, "s": 9346, "text": "Keep in touch: Linkedin" }, { "code": null, "e": 9381, "s": 9370, "text": "REFERENCES" }, { "code": null, "e": 9468, "s": 9381, "text": "[1] Deep and Confident Prediction for Time Series at Uber: Lingxue Zhu, Nikolay Laptev" } ]
C++ tricks for competitive programming
Here we will see some good tricks of C++ programming language that can help us in different area. Like if we want to participate in some competitive programming events, then these tricks will help us to reduce the time for writing codes. Let us see some of these examples one by one. Checking whether a number is odd or even without using % operator. This trick is simple. We can perform bitwise AND operation with the number and 1. If the result is non-zero then this is odd, otherwise this is even. The logic is too simple. All odd numbers have 1 at the LSb. So after performing AND with 1, it will mask all characters except LSb so we can get the desired results easily. if ((n & 1) != 0){ //this is odd } else { //This is even } Fast multiply and divide using shift operator. If we want to multiply a number with a number like 2n then we can simple shift the number to the left n times. Similarly, if we want to divide a number by 2n then shift the number to right n times. x = 40; y = x << 2; //x will be multiplied with 4, so y = 160 cout << x; x = 40; y = x >> 2; //x will be divided by 4, so y = 10 cout << x; We can swap two numbers without using third variables. This can be done using + and – operators. But we can do it using bitwise XOR operators also. You can check the numbers manually to make sure. //swap x and y x ^= y; y ^= x; x ^= y; Sometimes there are some constrains that, we cannot use the strlen() function in our code. In that case we create our own strlen() function. If the case is only accessing the characters, then we really don’t need to do this. We can check whether the character at position i is valid (non-zero) or not. If this is non-zero we can traverse, otherwise stop. for(int i = 0; s[i]; i++) { cout << s[i]; } Most often we use push_back() function in STL to add new element in some containers like vector etc. Without using that, we can use emplace_back() also. This function is much faster. This does not allocate memory somewhere else, it appends allocated memory in the container. C++ provides inbuilt GCD function. We can use them in different cases. The syntax is like below. __gcd(x, y) //find GCD of x and y The maximum size of an array in main function is of the order of 10^6. But if the array is declared globally, we can declare the size up to 10^7. We can calculate most significant digit of any number using log operation. See the following logic to get the idea n = 4578; double k = log10(n); k = k – floor(k); int x = pow(10, k); //x is the most significant digit Directly calculate number of digits using log operation. We do not use any loop for this. n = 4578; int digit_count = floot(log10(n)) + 1 We can check the number is power of 2 or not directly using this logic. x = 1024; bool check = x && (!(x & (x-1))); //if this is true, then power of two. Some inbuilt algorithms are there in C++, that can check the following conditions. all_of(left, left + n, isPositive()); //check all are positive or not any_of(left, left + n, isPositive()); //check at least one positive or not. none_of(left, left + n, isPositive()); //check no elements are positive Copy function to copy elements from one container to another. int src[5] = {10, 20, 30, 40, 50}; int des[5]; copy_n(src, 5, dest); There is an algorithm called itoa(). This algorithm can be used to create a range of sequentially increasing values as if by assigning initial value to *first, then using the value by using post increment operator. int arr[5] = {0}; char str[5] = {0}; itoa(arr, arr+5, 15); //it will generate {15, 16, 17, 18, 19} itoa(str, str+5, ‘A’); //it will generate {‘A’, ‘B’, ‘C’, ‘D’, ‘E’} Assign value in Binary form. We can use 0b prefix with some binary number to denote that the number is provided in binary. int x = 0b1101; //then x will hold 13 In C++, we can use keywords without using conditional operators. Like keyword ‘and’ can be used in the place of ‘&’. x = 10; if(x < 10 and x > 5) cout << “True” << endl; else cout << “False” << endl; //This will return True
[ { "code": null, "e": 1346, "s": 1062, "text": "Here we will see some good tricks of C++ programming language that can help us in different area. Like if we want to participate in some competitive programming events, then these tricks will help us to reduce the time for writing codes. Let us see some of these examples one by one." }, { "code": null, "e": 1736, "s": 1346, "text": "Checking whether a number is odd or even without using % operator. This trick is simple. We can perform bitwise AND operation with the number and 1. If the result is non-zero then this is odd, otherwise this is even. The logic is too simple. All odd numbers have 1 at the LSb. So after performing AND with 1, it will mask all characters except LSb so we can get the desired results easily." }, { "code": null, "e": 1801, "s": 1736, "text": "if ((n & 1) != 0){\n //this is odd\n} else {\n //This is even\n}" }, { "code": null, "e": 2046, "s": 1801, "text": "Fast multiply and divide using shift operator. If we want to multiply a number with a number like 2n then we can simple shift the number to the left n times. Similarly, if we want to divide a number by 2n then shift the number to right n times." }, { "code": null, "e": 2186, "s": 2046, "text": "x = 40;\ny = x << 2; //x will be multiplied with 4, so y = 160\ncout << x;\nx = 40;\ny = x >> 2; //x will be divided by 4, so y = 10\ncout << x;" }, { "code": null, "e": 2383, "s": 2186, "text": "We can swap two numbers without using third variables. This can be done using + and – operators. But we can do it using bitwise XOR operators also. You can check the numbers manually to make sure." }, { "code": null, "e": 2422, "s": 2383, "text": "//swap x and y\nx ^= y;\ny ^= x;\nx ^= y;" }, { "code": null, "e": 2777, "s": 2422, "text": "Sometimes there are some constrains that, we cannot use the strlen() function in our code. In that case we create our own strlen() function. If the case is only accessing the characters, then we really don’t need to do this. We can check whether the character at position i is valid (non-zero) or not. If this is non-zero we can traverse, otherwise stop." }, { "code": null, "e": 2824, "s": 2777, "text": "for(int i = 0; s[i]; i++) {\n cout << s[i];\n}" }, { "code": null, "e": 3099, "s": 2824, "text": "Most often we use push_back() function in STL to add new element in some containers like vector etc. Without using that, we can use emplace_back() also. This function is much faster. This does not allocate memory somewhere else, it appends allocated memory in the container." }, { "code": null, "e": 3196, "s": 3099, "text": "C++ provides inbuilt GCD function. We can use them in different cases. The syntax is like below." }, { "code": null, "e": 3230, "s": 3196, "text": "__gcd(x, y) //find GCD of x and y" }, { "code": null, "e": 3376, "s": 3230, "text": "The maximum size of an array in main function is of the order of 10^6. But if the array is declared globally, we can declare the size up to 10^7." }, { "code": null, "e": 3491, "s": 3376, "text": "We can calculate most significant digit of any number using log operation. See the following logic to get the idea" }, { "code": null, "e": 3594, "s": 3491, "text": "n = 4578;\ndouble k = log10(n);\nk = k – floor(k);\nint x = pow(10, k); //x is the most significant digit" }, { "code": null, "e": 3684, "s": 3594, "text": "Directly calculate number of digits using log operation. We do not use any loop for this." }, { "code": null, "e": 3732, "s": 3684, "text": "n = 4578;\nint digit_count = floot(log10(n)) + 1" }, { "code": null, "e": 3804, "s": 3732, "text": "We can check the number is power of 2 or not directly using this logic." }, { "code": null, "e": 3886, "s": 3804, "text": "x = 1024;\nbool check = x && (!(x & (x-1))); //if this is true, then power of two." }, { "code": null, "e": 3969, "s": 3886, "text": "Some inbuilt algorithms are there in C++, that can check the following conditions." }, { "code": null, "e": 4187, "s": 3969, "text": "all_of(left, left + n, isPositive()); //check all are positive or not\nany_of(left, left + n, isPositive()); //check at least one positive or not.\nnone_of(left, left + n, isPositive()); //check no elements are positive" }, { "code": null, "e": 4249, "s": 4187, "text": "Copy function to copy elements from one container to another." }, { "code": null, "e": 4318, "s": 4249, "text": "int src[5] = {10, 20, 30, 40, 50};\nint des[5];\ncopy_n(src, 5, dest);" }, { "code": null, "e": 4533, "s": 4318, "text": "There is an algorithm called itoa(). This algorithm can be used to create a range of sequentially increasing values as if by assigning initial value to *first, then using the value by using post increment operator." }, { "code": null, "e": 4700, "s": 4533, "text": "int arr[5] = {0};\nchar str[5] = {0};\nitoa(arr, arr+5, 15); //it will generate {15, 16, 17, 18, 19}\nitoa(str, str+5, ‘A’); //it will generate {‘A’, ‘B’, ‘C’, ‘D’, ‘E’}" }, { "code": null, "e": 4823, "s": 4700, "text": "Assign value in Binary form. We can use 0b prefix with some binary number to denote that the number is provided in binary." }, { "code": null, "e": 4861, "s": 4823, "text": "int x = 0b1101; //then x will hold 13" }, { "code": null, "e": 4978, "s": 4861, "text": "In C++, we can use keywords without using conditional operators. Like keyword ‘and’ can be used in the place of ‘&’." }, { "code": null, "e": 5094, "s": 4978, "text": "x = 10;\nif(x < 10 and x > 5)\n cout << “True” << endl;\nelse\n cout << “False” << endl;\n //This will return True" } ]
C++ Program to Implement Wheel Sieve to Generate Prime Numbers Between Given Range
Wheel Sieve method is used to find prime number between a given range. Wheel factorization is a graphical method for manually performing a preliminary to the Sieve of Eratosthenes that separates prime numbers from composites. In this method, Prime numbers in the innermost circle have their Multiples in similar positions as themselves in the other circles, forming spokes of primes and their multiples. Multiple of these prime numbers in the innermost circle form spokes of composite numbers in the outer circles. Begin Define max number gen_sieve_primes() Declare c Assign c = 2 For p = 2 to max number If prime[p]==0 prime[p]=1 Mul = p multiply c For Mul less than max number prime[Mul] = -1 Increment c Mul = p multiply c Done Done Print_all_prime() Assign c=0 For i = 0 to max number if (prime[i] == 1) Increment c If c less than 4 Switch(c) Case 1 Print 1st prime number Case 2 Print 2nd prime number Case 3 Print 3rd prime number Else Print nth prime number End #include <iostream> using namespace std; #define MAX_NUMBER 40 int prime[MAX_NUMBER]; void gen_sieve_prime(void) { for (int p = 2; p < MAX_NUMBER; p++) { if (prime[p] == 0) prime[p] = 1; int c = 2; int mul = p * c; for (; mul < MAX_NUMBER;) { prime[mul] = -1; c++; mul = p * c; } } } void print_all_prime() { int c = 0; for (int i = 0; i < MAX_NUMBER; i++) { if (prime[i] == 1) { c++; if (c < 4) { switch (c) { case 1: cout << c << "st prime is: " << i << endl; break; case 2: cout << c << "nd prime is: " << i << endl; break; case 3: cout << c << "rd prime is: " << i << endl; break; default: break; } }else cout << c << "th prime is: " << i << endl; } } } int main() { gen_sieve_prime(); print_all_prime(); return 0; } 1st prime is: 2 2nd prime is: 3 3rd prime is: 5 4th prime is: 7 5th prime is: 11 6th prime is: 13 7th prime is: 17 8th prime is: 19 9th prime is: 23 10th prime is: 29 11th prime is: 31 12th prime is: 37
[ { "code": null, "e": 1288, "s": 1062, "text": "Wheel Sieve method is used to find prime number between a given range. Wheel factorization is a graphical method for manually performing a preliminary to the Sieve of Eratosthenes that separates prime numbers from composites." }, { "code": null, "e": 1577, "s": 1288, "text": "In this method, Prime numbers in the innermost circle have their Multiples in similar positions as themselves in the other circles, forming spokes of primes and their multiples. Multiple of these prime numbers in the innermost circle form spokes of composite numbers in the outer circles." }, { "code": null, "e": 2217, "s": 1577, "text": "Begin\n Define max number\n gen_sieve_primes()\n Declare c\n Assign c = 2\n For p = 2 to max number\n If prime[p]==0\n prime[p]=1\n Mul = p multiply c\n For Mul less than max number\n prime[Mul] = -1\n Increment c\n Mul = p multiply c\n Done\n Done\n Print_all_prime()\n Assign c=0\n For i = 0 to max number\n if (prime[i] == 1)\n Increment c\n If c less than 4\n Switch(c)\n Case 1\n Print 1st prime number\n Case 2\n Print 2nd prime number\n Case 3\n Print 3rd prime number\n Else\n Print nth prime number\nEnd" }, { "code": null, "e": 3285, "s": 2217, "text": "#include <iostream>\nusing namespace std;\n#define MAX_NUMBER 40\nint prime[MAX_NUMBER];\nvoid gen_sieve_prime(void) {\n for (int p = 2; p < MAX_NUMBER; p++) {\n if (prime[p] == 0)\n prime[p] = 1;\n int c = 2;\n int mul = p * c;\n for (; mul < MAX_NUMBER;) {\n prime[mul] = -1;\n c++;\n mul = p * c;\n }\n }\n}\nvoid print_all_prime() {\n int c = 0;\n for (int i = 0; i < MAX_NUMBER; i++) {\n if (prime[i] == 1) {\n c++;\n if (c < 4) {\n switch (c) {\n case 1:\n cout << c << \"st prime is: \" << i << endl;\n break;\n case 2:\n cout << c << \"nd prime is: \" << i << endl;\n break;\n case 3:\n cout << c << \"rd prime is: \" << i << endl;\n break;\n default:\n break;\n }\n }else\n cout << c << \"th prime is: \" << i << endl;\n }\n }\n}\nint main() {\n gen_sieve_prime();\n print_all_prime();\n return 0;\n}" }, { "code": null, "e": 3488, "s": 3285, "text": "1st prime is: 2\n2nd prime is: 3\n3rd prime is: 5\n4th prime is: 7\n5th prime is: 11\n6th prime is: 13\n7th prime is: 17\n8th prime is: 19\n9th prime is: 23\n10th prime is: 29\n11th prime is: 31\n12th prime is: 37" } ]
Funnel charts with Python. A great option for representing... | by Thiago Carvalho | Towards Data Science
Funnel charts are mostly used for representing a sequential process, allowing the viewers to compare and see how the numbers change through the stages. In this article, we’ll explore how to build a funnel chart from scratch using Matplotlib, and then we’ll have a look at an easier implementation with Plotly. There is no method for instantly creating funnel charts in Matplotlib, so let’s start with a simple horizontal bar chart and build from there. import matplotlib.pyplot as plty = [5,4,3,2,1]x = [80,73,58,42,23]plt.barh(y, x) That’s actually quite close to what we want, so why not stop here and use a bar chart instead? It may be even easier to compare the values with a simple bar chart, but choosing the funnel-shaped one can make the relationship between the bars more explicit and make our visualization more appealing. Ok, so we’ll need to plot one bar at a time and use the ‘left’ parameter to adjust its position in the chart. Let’s check how this works. y = [5,4,3,2,1]x = [80,73,58,42,23]x_max = 100x_min = 0for idx, val in enumerate(x): plt.barh(y[idx], x[idx], left = idx+5)plt.xlim(x_min, x_max) We have the bars' size, which is x and the range of the x-axis, which is 100. The difference between those values is the blank space, and to center the bars, we need to have the same amount of blank space on each side. So we can say that:left = (size of the bar - x-axis range) / 2 Let’s see how this looks. y = [5,4,3,2,1]x = [80,73,58,42,23]x_max = 100x_min = 0for idx, val in enumerate(x): left = (x_max - val)/2 plt.barh(y[idx], x[idx], left = left, color='grey')plt.xlim(x_min, x_max) Great! But the axis information doesn’t mean much now that the bars don’t have the same starting point. We need to print the values on the bars and connect them. y = [5,4,3,2,1]x = [80,73,58,42,23]x_max = 100x_min = 0fig, ax = plt.subplots(1, figsize=(12,6))for idx, val in enumerate(x): left = (x_max - val)/2 plt.barh(y[idx], x[idx], left = left, color='grey', height=1, edgecolor='black') # value plt.text(50, y[idx], x[idx], ha='center', fontproperties=font, fontsize=16, color='#2A2A2A')plt.axis('off')plt.xlim(x_min, x_max) Alright, we could add a title, some labels for the bars, and call it a day. But let’s give our viewers some eye-candy and add a shadow connecting the bars instead of just stacking them. That will make our chart and the connection between the bars more clear. First, let’s define all the variables we’ll need from matplotlib import font_manager as fm# funnel charty = [5,4,3,2,1]x = [80,73,58,42,23]labels = ['Hot Leads', 'Samples Sent', 'Quotes', 'Negotiations', 'Sales']x_max = 100x_min = 0x_range = x_max - x_minfpath = "fonts/NotoSans-Regular.ttf"font = fm.FontProperties(fname=fpath) Now, let’s add some more details to our plot. fig, ax = plt.subplots(1, figsize=(12,6))for idx, val in enumerate(x): left = (x_range - val)/2 plt.barh(y[idx], x[idx], left = left, color='#808B96', height=.8, edgecolor='black') # label plt.text(50, y[idx]+0.1, labels[idx], ha='center', fontproperties=font, fontsize=16, color='#2A2A2A') # value plt.text(50, y[idx]-0.3, x[idx], ha='center', fontproperties=font, fontsize=16, color='#2A2A2A') plt.xlim(x_min, x_max)plt.axis('off')plt.title('Beskar Forging Services Inc.', fontproperties=font, loc='center', fontsize=24, color='#2A2A2A')plt.show() *Font from https://fonts.google.com/specimen/Noto+Sans We’ll plot a line from one side to the other of the bars. We can use the value of left to find the start and end of the bar and the y-value to find its center. fig, ax = plt.subplots(1, figsize=(12,6))for idx, val in enumerate(x): left = (x_range - val)/2 plt.barh(y[idx], x[idx], left = left, color='#808B96', height=.8, edgecolor='black') # label plt.text(50, y[idx]+0.1, labels[idx], ha='center', fontproperties=font, fontsize=16, color='#2A2A2A') # value plt.text(50, y[idx]-0.3, x[idx], ha='center', fontproperties=font, fontsize=16, color='#2A2A2A') plt.plot([left, 100-left], [y[idx], y[idx]])plt.xlim(x_min, x_max)plt.axis('off')plt.title('Beskar Forging Services Inc.', fontproperties=font, loc='center', fontsize=24, color='#2A2A2A')plt.show() Now let’s move this line to the bottom of the bar, and since we won’t have a connection after the last bar, we can skip drawing a shadow for it. We defined the bars' height as 0.8, so to move the lines to the bottom, we could decrease y to 0.4. We’ll also need the coordinates of the top of the next bar. fig, ax = plt.subplots(1, figsize=(12,6))for idx, val in enumerate(x): left = (x_range - val)/2 plt.barh(y[idx], x[idx], left = left, color='#808B96', height=.8, edgecolor='black') # label plt.text(50, y[idx]+0.1, labels[idx], ha='center', fontproperties=font, fontsize=16, color='#2A2A2A') # value plt.text(50, y[idx]-0.3, x[idx], ha='center', fontproperties=font, fontsize=16, color='#2A2A2A') if idx != len(x)-1: next_left = (x_range - x[idx+1])/2 plt.plot([left, 100-left], [y[idx]-0.4, y[idx]-0.4]) plt.plot([next_left, 100-next_left], [y[idx+1]+0.4, y[idx+1]+0.4])plt.xlim(x_min, x_max)plt.axis('off')plt.title('Beskar Forging Services Inc.', fontproperties=font, loc='center', fontsize=24, color='#2A2A2A')plt.show() We found all the points we need to draw. Now we can connect those points and see if we get the shape we’re looking for. Don’t forget to repeat the first point at the end to close the polygon. fig, ax = plt.subplots(1, figsize=(12,6))for idx, val in enumerate(x): left = (x_range - val)/2 plt.barh(y[idx], x[idx], left = left, color='#808B96', height=.8, edgecolor='black') # label plt.text(50, y[idx]+0.1, labels[idx], ha='center', fontproperties=font, fontsize=16, color='#2A2A2A') # value plt.text(50, y[idx]-0.3, x[idx], ha='center', fontproperties=font, fontsize=16, color='#2A2A2A') if idx != len(x)-1: next_left = (x_range - x[idx+1])/2 shadow_x = [left, next_left, 100-next_left, 100-left, left] shadow_y = [y[idx]-0.4, y[idx+1]+0.4, y[idx+1]+0.4, y[idx]-0.4, y[idx]-0.4] plt.plot(shadow_x, shadow_y)plt.xlim(x_min, x_max)plt.axis('off')plt.title('Beskar Forging Services Inc.', fontproperties=font, loc='center', fontsize=24, color='#2A2A2A')plt.show() Perfect. All that’s left to do is change the .plot to .fill and we have our funnel chart ready. fig, ax = plt.subplots(1, figsize=(12,6))for idx, val in enumerate(x): left = (x_range - val)/2 plt.barh(y[idx], x[idx], left = left, color='#808B96', height=.8) # label plt.text(50, y[idx]+0.1, labels[idx], ha='center', fontproperties=font, fontsize=16, color='#2A2A2A') # value plt.text(50, y[idx]-0.3, x[idx], ha='center', fontproperties=font, fontsize=16, color='#2A2A2A') if idx != len(x)-1: next_left = (x_range - x[idx+1])/2 shadow_x = [left, next_left, 100-next_left, 100-left, left] shadow_y = [y[idx]-0.4, y[idx+1]+0.4, y[idx+1]+0.4, y[idx]-0.4, y[idx]-0.4] plt.fill(shadow_x, shadow_y, color='grey', alpha=0.6)plt.xlim(x_min, x_max)plt.axis('off')plt.title('Beskar Forging Services Inc.', fontproperties=font, loc='center', fontsize=24, color='#2A2A2A')plt.show() There it is! Drawing a funnel chart with Matplotlib can go from simple to complex very quickly. But that’s the fun of Matplotlib; we have the freedom to draw pretty much anything. Now to an easier way of achieving the same results, let’s check how to draw a funnel chart with Plotly. import plotly.express as pxdata = dict(values=[80,73,58,42,23], labels=['Hot Leads', 'Samples Sent', 'Quotes', 'Negotiations', 'Sales'])fig = px.funnel(data, y='labels', x='values')fig.show() That’s awesome. Plotly has a method for drawing funnel charts, so we only need the data, and it does all the rest. Plotly also offers many options to customize the charts. We may not have so much control over the visualization as we did before, but it’s way more convenient to plot it like this. data = dict(Quantity=[80, 73, 58, 42, 23, 180, 120, 82, 51, 33, 109, 78, 62, 44, 22], Stage=['Hot Leads', 'Samples Sent', 'Quotes', 'Negotiations', 'Sales']*3, Location=['Tatooine']*5 + ['Mandalore']*5 + ['Nevarro']*5) fig = px.funnel(data, y='Stage', x='Quantity', color='Location', color_discrete_map={"Tatooine": "#374B53", "Mandalore": "#617588", "Nevarro": "#A4B7C8"}, template="simple_white", title='Beskar Forging Services Inc.', labels={"Stage": ""})fig.show() And that’s it! We saw how to build a funnel chart from scratch with Matplotlib and how this simple visualization can get complicated. We also checked a more convenient way of drawing this chart with Plotly and got a peek at some of the ways we can customize it. Thanks for reading my article. I hope you enjoyed it. More tutorials on DataViz with Python.
[ { "code": null, "e": 199, "s": 47, "text": "Funnel charts are mostly used for representing a sequential process, allowing the viewers to compare and see how the numbers change through the stages." }, { "code": null, "e": 357, "s": 199, "text": "In this article, we’ll explore how to build a funnel chart from scratch using Matplotlib, and then we’ll have a look at an easier implementation with Plotly." }, { "code": null, "e": 500, "s": 357, "text": "There is no method for instantly creating funnel charts in Matplotlib, so let’s start with a simple horizontal bar chart and build from there." }, { "code": null, "e": 581, "s": 500, "text": "import matplotlib.pyplot as plty = [5,4,3,2,1]x = [80,73,58,42,23]plt.barh(y, x)" }, { "code": null, "e": 676, "s": 581, "text": "That’s actually quite close to what we want, so why not stop here and use a bar chart instead?" }, { "code": null, "e": 880, "s": 676, "text": "It may be even easier to compare the values with a simple bar chart, but choosing the funnel-shaped one can make the relationship between the bars more explicit and make our visualization more appealing." }, { "code": null, "e": 1018, "s": 880, "text": "Ok, so we’ll need to plot one bar at a time and use the ‘left’ parameter to adjust its position in the chart. Let’s check how this works." }, { "code": null, "e": 1167, "s": 1018, "text": "y = [5,4,3,2,1]x = [80,73,58,42,23]x_max = 100x_min = 0for idx, val in enumerate(x): plt.barh(y[idx], x[idx], left = idx+5)plt.xlim(x_min, x_max)" }, { "code": null, "e": 1245, "s": 1167, "text": "We have the bars' size, which is x and the range of the x-axis, which is 100." }, { "code": null, "e": 1386, "s": 1245, "text": "The difference between those values is the blank space, and to center the bars, we need to have the same amount of blank space on each side." }, { "code": null, "e": 1449, "s": 1386, "text": "So we can say that:left = (size of the bar - x-axis range) / 2" }, { "code": null, "e": 1475, "s": 1449, "text": "Let’s see how this looks." }, { "code": null, "e": 1663, "s": 1475, "text": "y = [5,4,3,2,1]x = [80,73,58,42,23]x_max = 100x_min = 0for idx, val in enumerate(x): left = (x_max - val)/2 plt.barh(y[idx], x[idx], left = left, color='grey')plt.xlim(x_min, x_max)" }, { "code": null, "e": 1767, "s": 1663, "text": "Great! But the axis information doesn’t mean much now that the bars don’t have the same starting point." }, { "code": null, "e": 1825, "s": 1767, "text": "We need to print the values on the bars and connect them." }, { "code": null, "e": 2217, "s": 1825, "text": "y = [5,4,3,2,1]x = [80,73,58,42,23]x_max = 100x_min = 0fig, ax = plt.subplots(1, figsize=(12,6))for idx, val in enumerate(x): left = (x_max - val)/2 plt.barh(y[idx], x[idx], left = left, color='grey', height=1, edgecolor='black') # value plt.text(50, y[idx], x[idx], ha='center', fontproperties=font, fontsize=16, color='#2A2A2A')plt.axis('off')plt.xlim(x_min, x_max)" }, { "code": null, "e": 2293, "s": 2217, "text": "Alright, we could add a title, some labels for the bars, and call it a day." }, { "code": null, "e": 2476, "s": 2293, "text": "But let’s give our viewers some eye-candy and add a shadow connecting the bars instead of just stacking them. That will make our chart and the connection between the bars more clear." }, { "code": null, "e": 2525, "s": 2476, "text": "First, let’s define all the variables we’ll need" }, { "code": null, "e": 2805, "s": 2525, "text": "from matplotlib import font_manager as fm# funnel charty = [5,4,3,2,1]x = [80,73,58,42,23]labels = ['Hot Leads', 'Samples Sent', 'Quotes', 'Negotiations', 'Sales']x_max = 100x_min = 0x_range = x_max - x_minfpath = \"fonts/NotoSans-Regular.ttf\"font = fm.FontProperties(fname=fpath)" }, { "code": null, "e": 2851, "s": 2805, "text": "Now, let’s add some more details to our plot." }, { "code": null, "e": 3459, "s": 2851, "text": "fig, ax = plt.subplots(1, figsize=(12,6))for idx, val in enumerate(x): left = (x_range - val)/2 plt.barh(y[idx], x[idx], left = left, color='#808B96', height=.8, edgecolor='black') # label plt.text(50, y[idx]+0.1, labels[idx], ha='center', fontproperties=font, fontsize=16, color='#2A2A2A') # value plt.text(50, y[idx]-0.3, x[idx], ha='center', fontproperties=font, fontsize=16, color='#2A2A2A') plt.xlim(x_min, x_max)plt.axis('off')plt.title('Beskar Forging Services Inc.', fontproperties=font, loc='center', fontsize=24, color='#2A2A2A')plt.show()" }, { "code": null, "e": 3514, "s": 3459, "text": "*Font from https://fonts.google.com/specimen/Noto+Sans" }, { "code": null, "e": 3674, "s": 3514, "text": "We’ll plot a line from one side to the other of the bars. We can use the value of left to find the start and end of the bar and the y-value to find its center." }, { "code": null, "e": 4317, "s": 3674, "text": "fig, ax = plt.subplots(1, figsize=(12,6))for idx, val in enumerate(x): left = (x_range - val)/2 plt.barh(y[idx], x[idx], left = left, color='#808B96', height=.8, edgecolor='black') # label plt.text(50, y[idx]+0.1, labels[idx], ha='center', fontproperties=font, fontsize=16, color='#2A2A2A') # value plt.text(50, y[idx]-0.3, x[idx], ha='center', fontproperties=font, fontsize=16, color='#2A2A2A') plt.plot([left, 100-left], [y[idx], y[idx]])plt.xlim(x_min, x_max)plt.axis('off')plt.title('Beskar Forging Services Inc.', fontproperties=font, loc='center', fontsize=24, color='#2A2A2A')plt.show()" }, { "code": null, "e": 4462, "s": 4317, "text": "Now let’s move this line to the bottom of the bar, and since we won’t have a connection after the last bar, we can skip drawing a shadow for it." }, { "code": null, "e": 4562, "s": 4462, "text": "We defined the bars' height as 0.8, so to move the lines to the bottom, we could decrease y to 0.4." }, { "code": null, "e": 4622, "s": 4562, "text": "We’ll also need the coordinates of the top of the next bar." }, { "code": null, "e": 5450, "s": 4622, "text": "fig, ax = plt.subplots(1, figsize=(12,6))for idx, val in enumerate(x): left = (x_range - val)/2 plt.barh(y[idx], x[idx], left = left, color='#808B96', height=.8, edgecolor='black') # label plt.text(50, y[idx]+0.1, labels[idx], ha='center', fontproperties=font, fontsize=16, color='#2A2A2A') # value plt.text(50, y[idx]-0.3, x[idx], ha='center', fontproperties=font, fontsize=16, color='#2A2A2A') if idx != len(x)-1: next_left = (x_range - x[idx+1])/2 plt.plot([left, 100-left], [y[idx]-0.4, y[idx]-0.4]) plt.plot([next_left, 100-next_left], [y[idx+1]+0.4, y[idx+1]+0.4])plt.xlim(x_min, x_max)plt.axis('off')plt.title('Beskar Forging Services Inc.', fontproperties=font, loc='center', fontsize=24, color='#2A2A2A')plt.show()" }, { "code": null, "e": 5570, "s": 5450, "text": "We found all the points we need to draw. Now we can connect those points and see if we get the shape we’re looking for." }, { "code": null, "e": 5642, "s": 5570, "text": "Don’t forget to repeat the first point at the end to close the polygon." }, { "code": null, "e": 6536, "s": 5642, "text": "fig, ax = plt.subplots(1, figsize=(12,6))for idx, val in enumerate(x): left = (x_range - val)/2 plt.barh(y[idx], x[idx], left = left, color='#808B96', height=.8, edgecolor='black') # label plt.text(50, y[idx]+0.1, labels[idx], ha='center', fontproperties=font, fontsize=16, color='#2A2A2A') # value plt.text(50, y[idx]-0.3, x[idx], ha='center', fontproperties=font, fontsize=16, color='#2A2A2A') if idx != len(x)-1: next_left = (x_range - x[idx+1])/2 shadow_x = [left, next_left, 100-next_left, 100-left, left] shadow_y = [y[idx]-0.4, y[idx+1]+0.4, y[idx+1]+0.4, y[idx]-0.4, y[idx]-0.4] plt.plot(shadow_x, shadow_y)plt.xlim(x_min, x_max)plt.axis('off')plt.title('Beskar Forging Services Inc.', fontproperties=font, loc='center', fontsize=24, color='#2A2A2A')plt.show()" }, { "code": null, "e": 6632, "s": 6536, "text": "Perfect. All that’s left to do is change the .plot to .fill and we have our funnel chart ready." }, { "code": null, "e": 7545, "s": 6632, "text": "fig, ax = plt.subplots(1, figsize=(12,6))for idx, val in enumerate(x): left = (x_range - val)/2 plt.barh(y[idx], x[idx], left = left, color='#808B96', height=.8) # label plt.text(50, y[idx]+0.1, labels[idx], ha='center', fontproperties=font, fontsize=16, color='#2A2A2A') # value plt.text(50, y[idx]-0.3, x[idx], ha='center', fontproperties=font, fontsize=16, color='#2A2A2A') if idx != len(x)-1: next_left = (x_range - x[idx+1])/2 shadow_x = [left, next_left, 100-next_left, 100-left, left] shadow_y = [y[idx]-0.4, y[idx+1]+0.4, y[idx+1]+0.4, y[idx]-0.4, y[idx]-0.4] plt.fill(shadow_x, shadow_y, color='grey', alpha=0.6)plt.xlim(x_min, x_max)plt.axis('off')plt.title('Beskar Forging Services Inc.', fontproperties=font, loc='center', fontsize=24, color='#2A2A2A')plt.show()" }, { "code": null, "e": 7558, "s": 7545, "text": "There it is!" }, { "code": null, "e": 7641, "s": 7558, "text": "Drawing a funnel chart with Matplotlib can go from simple to complex very quickly." }, { "code": null, "e": 7725, "s": 7641, "text": "But that’s the fun of Matplotlib; we have the freedom to draw pretty much anything." }, { "code": null, "e": 7829, "s": 7725, "text": "Now to an easier way of achieving the same results, let’s check how to draw a funnel chart with Plotly." }, { "code": null, "e": 8052, "s": 7829, "text": "import plotly.express as pxdata = dict(values=[80,73,58,42,23], labels=['Hot Leads', 'Samples Sent', 'Quotes', 'Negotiations', 'Sales'])fig = px.funnel(data, y='labels', x='values')fig.show()" }, { "code": null, "e": 8167, "s": 8052, "text": "That’s awesome. Plotly has a method for drawing funnel charts, so we only need the data, and it does all the rest." }, { "code": null, "e": 8224, "s": 8167, "text": "Plotly also offers many options to customize the charts." }, { "code": null, "e": 8348, "s": 8224, "text": "We may not have so much control over the visualization as we did before, but it’s way more convenient to plot it like this." }, { "code": null, "e": 9041, "s": 8348, "text": "data = dict(Quantity=[80, 73, 58, 42, 23, 180, 120, 82, 51, 33, 109, 78, 62, 44, 22], Stage=['Hot Leads', 'Samples Sent', 'Quotes', 'Negotiations', 'Sales']*3, Location=['Tatooine']*5 + ['Mandalore']*5 + ['Nevarro']*5) fig = px.funnel(data, y='Stage', x='Quantity', color='Location', color_discrete_map={\"Tatooine\": \"#374B53\", \"Mandalore\": \"#617588\", \"Nevarro\": \"#A4B7C8\"}, template=\"simple_white\", title='Beskar Forging Services Inc.', labels={\"Stage\": \"\"})fig.show()" }, { "code": null, "e": 9303, "s": 9041, "text": "And that’s it! We saw how to build a funnel chart from scratch with Matplotlib and how this simple visualization can get complicated. We also checked a more convenient way of drawing this chart with Plotly and got a peek at some of the ways we can customize it." }, { "code": null, "e": 9357, "s": 9303, "text": "Thanks for reading my article. I hope you enjoyed it." } ]
Python Forensics - Cracking an Encryption
In this chapter, we will learn about cracking a text data fetched during analysis and evidence. A plain text in cryptography is some normal readable text, such as a message. A cipher text, on the other hand, is the output of an encryption algorithm fetched after you enter plain text. Simple algorithm of how we turn a plain text message into a cipher text is the Caesar cipher, invented by Julius Caesar to keep the plain text secret from his enemies. This cipher involves shifting every letter in the message "forward" by three places in the alphabet. Following is a demo illustration. a → D b → E c → F .... w → Z x → A y → B z → C A message entered when you run a Python script gives all the possibilities of characters, which is used for pattern evidence. The types of pattern evidences used are as follows − Tire Tracks and Marks Impressions Fingerprints Every biometric data comprises of vector data, which we need to crack to gather full-proof evidence. The following Python code shows how you can produce a cipher text from plain text − import sys def decrypt(k,cipher): plaintext = '' for each in cipher: p = (ord(each)-k) % 126 if p < 32: p+=95 plaintext += chr(p) print plaintext def main(argv): if (len(sys.argv) != 1): sys.exit('Usage: cracking.py') cipher = raw_input('Enter message: ') for i in range(1,95,1): decrypt(i,cipher) if __name__ == "__main__": main(sys.argv[1:]) Now, check the output of this code. When we enter a simple text "Radhika", the program will produce the following cipher text. 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": 2088, "s": 1992, "text": "In this chapter, we will learn about cracking a text data fetched during analysis and evidence." }, { "code": null, "e": 2277, "s": 2088, "text": "A plain text in cryptography is some normal readable text, such as a message. A cipher text, on the other hand, is the output of an encryption algorithm fetched after you enter plain text." }, { "code": null, "e": 2546, "s": 2277, "text": "Simple algorithm of how we turn a plain text message into a cipher text is the Caesar cipher, invented by Julius Caesar to keep the plain text secret from his enemies. This cipher involves shifting every letter in the message \"forward\" by three places in the alphabet." }, { "code": null, "e": 2580, "s": 2546, "text": "Following is a demo illustration." }, { "code": null, "e": 2586, "s": 2580, "text": "a → D" }, { "code": null, "e": 2592, "s": 2586, "text": "b → E" }, { "code": null, "e": 2598, "s": 2592, "text": "c → F" }, { "code": null, "e": 2603, "s": 2598, "text": "...." }, { "code": null, "e": 2609, "s": 2603, "text": "w → Z" }, { "code": null, "e": 2615, "s": 2609, "text": "x → A" }, { "code": null, "e": 2621, "s": 2615, "text": "y → B" }, { "code": null, "e": 2627, "s": 2621, "text": "z → C" }, { "code": null, "e": 2753, "s": 2627, "text": "A message entered when you run a Python script gives all the possibilities of characters, which is used for pattern evidence." }, { "code": null, "e": 2806, "s": 2753, "text": "The types of pattern evidences used are as follows −" }, { "code": null, "e": 2828, "s": 2806, "text": "Tire Tracks and Marks" }, { "code": null, "e": 2840, "s": 2828, "text": "Impressions" }, { "code": null, "e": 2853, "s": 2840, "text": "Fingerprints" }, { "code": null, "e": 2954, "s": 2853, "text": "Every biometric data comprises of vector data, which we need to crack to gather full-proof evidence." }, { "code": null, "e": 3038, "s": 2954, "text": "The following Python code shows how you can produce a cipher text from plain text −" }, { "code": null, "e": 3503, "s": 3038, "text": "import sys\n\ndef decrypt(k,cipher): \n plaintext = '' \n \n for each in cipher: \n p = (ord(each)-k) % 126 \n \n if p < 32: \n p+=95 \n plaintext += chr(p) \n print plaintext \n\ndef main(argv):\n if (len(sys.argv) != 1): \n sys.exit('Usage: cracking.py') \n cipher = raw_input('Enter message: ') \n \n for i in range(1,95,1): \n decrypt(i,cipher)\n \nif __name__ == \"__main__\": \n main(sys.argv[1:])" }, { "code": null, "e": 3630, "s": 3503, "text": "Now, check the output of this code. When we enter a simple text \"Radhika\", the program will produce the following cipher text." }, { "code": null, "e": 3667, "s": 3630, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3683, "s": 3667, "text": " Malhar Lathkar" }, { "code": null, "e": 3716, "s": 3683, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3735, "s": 3716, "text": " Arnab Chakraborty" }, { "code": null, "e": 3770, "s": 3735, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3792, "s": 3770, "text": " In28Minutes Official" }, { "code": null, "e": 3826, "s": 3792, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3854, "s": 3826, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3889, "s": 3854, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3903, "s": 3889, "text": " Lets Kode It" }, { "code": null, "e": 3936, "s": 3903, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3953, "s": 3936, "text": " Abhilash Nelson" }, { "code": null, "e": 3960, "s": 3953, "text": " Print" }, { "code": null, "e": 3971, "s": 3960, "text": " Add Notes" } ]
Deep Neural Networks for Regression Problems | by Mohammed AL-Ma'amari | Towards Data Science
Neural networks are well known for classification problems, for example, they are used in handwritten digits classification, but the question is will it be fruitful if we used them for regression problems? In this article I will use a deep neural network to predict house pricing using a dataset from Kaggle . You can download the dataset from Here I highly recommend you to try running the code using my notebook on Google colab [Here] 1- Process the dataset2- Make the deep neural network3- Train the DNN4- Test the DNN5- Compare the result from the DNN to another ML algorithm First of all, we will import the needed dependencies : We will not go deep in processing the dataset, all we want to do is getting the dataset ready to be fed into our models . We will get rid of any features with missing values, then we will encode the categorical features, that’s it. Load train and test data into pandas DataFrames Combine train and test data to process them together combined.describe() let’s define a function to get the columns that don’t have any missing values Get the columns that do not have any missing values . Let’s see how many columns we got [out]:Number of numerical columns with no nan values : 25 Number of nun-numerical columns with no nan values : 20 The correlation between the features From the correlation heat map above, we see that about 15 features are highly correlated with the target. One Hot Encode The Categorical Features : We will encode the categorical features using one hot encoding. [out]:There were 45 columns before encoding categorical features There are 149 columns after encoding categorical features Now, split back combined dataFrame to training data and test data Define a sequential model Add some dense layers Use ‘relu’ as the activation function for the hidden layers Use a ‘normal’ initializer as the kernal_intializer Initializers define the way to set the initial random weights of Keras layers. We will use mean_absolute_error as a loss function Define the output layer with only one node Use ‘linear ’as the activation function for the output layer [Out]:_________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense_1 (Dense) (None, 128) 19200 _________________________________________________________________ dense_2 (Dense) (None, 256) 33024 _________________________________________________________________ dense_3 (Dense) (None, 256) 65792 _________________________________________________________________ dense_4 (Dense) (None, 256) 65792 _________________________________________________________________ dense_5 (Dense) (None, 1) 257 ================================================================= Total params: 184,065 Trainable params: 184,065 Non-trainable params: 0 _________________________________________________________________ Define a checkpoint callback : [out]:Train on 1168 samples, validate on 292 samplesEpoch 1/5001168/1168 [==============================] - 0s 266us/step - loss: 19251.8903 - mean_absolute_error: 19251.8903 - val_loss: 23041.8968 - val_mean_absolute_error: 23041.8968 Epoch 00001: val_loss did not improve from 21730.93555 Epoch 2/500 1168/1168 [==============================] - 0s 268us/step - loss: 18180.4985 - mean_absolute_error: 18180.4985 - val_loss: 22197.7991 - val_mean_absolute_error: 22197.7991 Epoch 00002: val_loss did not improve from 21730.93555...Epoch 00500: val_loss did not improve from 18738.19831<keras.callbacks.History at 0x7f4324aa80b8> We see that the validation loss of the best model is 18738.19 We will submit the predictions on the test data to Kaggle and see how good our model is. Not bad at all, with some more preprocessing, and more training, we can do better. Now, let us try another ML algorithm to compare the results. We will use random forest regressor and XGBRegressor. Split training data to training and validation data We will try Random forest model first: Random forest validation MAE = 19089.71589041096 Make a submission file and submit it to Kaggle to see the result : Now, let us try XGBoost model : [out]: XGBoost validation MAE = 17869.75410958904 Make a submission file and submit it to Kaggle to see the result : Isn’t that a surprise, I really did not think that neural networks will beat random forests and XGBoost algorithms, but let us try not to be too optimistic, remember that we did not configure any hyperparameters on random forest and XGBoost models, I believe if we did so, these two models would outscore neural networks. We load and processed the dataset We got familiar with the dataset by plotting some histograms and a correlation heat map of the features We used a deep neural network with three hidden layers each one has 256 nodes. We used a linear activation function on the output layer We trained the model then test it on Kaggle. We also tested two other models Our deep neural network was able to outscore these two models We believe that these two models could beat the deep neural network model if we tweak their hyperparameters. Try to put more effort on processing the dataset Try other types of neural networks Try to tweak the hyperparameters of the two models that we used If you really want to get better at regression problems, follow this tutorial: [Stacked Regressions : Top 4% on LeaderBoard | Kaggle] Regression Tutorial with the Keras Deep Learning Library in Python You can follow me on Twitter @ModMaamari AI Generates Taylor Swift’s Song Lyrics Introduction to Random Forest Algorithm with Python Machine Learning Crash Course with TensorFlow APIs Summary How To Make A CNN Using Tensorflow and Keras ? How to Choose the Best Machine Learning Model ?
[ { "code": null, "e": 378, "s": 172, "text": "Neural networks are well known for classification problems, for example, they are used in handwritten digits classification, but the question is will it be fruitful if we used them for regression problems?" }, { "code": null, "e": 482, "s": 378, "text": "In this article I will use a deep neural network to predict house pricing using a dataset from Kaggle ." }, { "code": null, "e": 521, "s": 482, "text": "You can download the dataset from Here" }, { "code": null, "e": 609, "s": 521, "text": "I highly recommend you to try running the code using my notebook on Google colab [Here]" }, { "code": null, "e": 752, "s": 609, "text": "1- Process the dataset2- Make the deep neural network3- Train the DNN4- Test the DNN5- Compare the result from the DNN to another ML algorithm" }, { "code": null, "e": 807, "s": 752, "text": "First of all, we will import the needed dependencies :" }, { "code": null, "e": 929, "s": 807, "text": "We will not go deep in processing the dataset, all we want to do is getting the dataset ready to be fed into our models ." }, { "code": null, "e": 1039, "s": 929, "text": "We will get rid of any features with missing values, then we will encode the categorical features, that’s it." }, { "code": null, "e": 1087, "s": 1039, "text": "Load train and test data into pandas DataFrames" }, { "code": null, "e": 1140, "s": 1087, "text": "Combine train and test data to process them together" }, { "code": null, "e": 1160, "s": 1140, "text": "combined.describe()" }, { "code": null, "e": 1238, "s": 1160, "text": "let’s define a function to get the columns that don’t have any missing values" }, { "code": null, "e": 1292, "s": 1238, "text": "Get the columns that do not have any missing values ." }, { "code": null, "e": 1326, "s": 1292, "text": "Let’s see how many columns we got" }, { "code": null, "e": 1440, "s": 1326, "text": "[out]:Number of numerical columns with no nan values : 25 Number of nun-numerical columns with no nan values : 20" }, { "code": null, "e": 1477, "s": 1440, "text": "The correlation between the features" }, { "code": null, "e": 1583, "s": 1477, "text": "From the correlation heat map above, we see that about 15 features are highly correlated with the target." }, { "code": null, "e": 1625, "s": 1583, "text": "One Hot Encode The Categorical Features :" }, { "code": null, "e": 1689, "s": 1625, "text": "We will encode the categorical features using one hot encoding." }, { "code": null, "e": 1812, "s": 1689, "text": "[out]:There were 45 columns before encoding categorical features There are 149 columns after encoding categorical features" }, { "code": null, "e": 1878, "s": 1812, "text": "Now, split back combined dataFrame to training data and test data" }, { "code": null, "e": 1904, "s": 1878, "text": "Define a sequential model" }, { "code": null, "e": 1926, "s": 1904, "text": "Add some dense layers" }, { "code": null, "e": 1986, "s": 1926, "text": "Use ‘relu’ as the activation function for the hidden layers" }, { "code": null, "e": 2038, "s": 1986, "text": "Use a ‘normal’ initializer as the kernal_intializer" }, { "code": null, "e": 2117, "s": 2038, "text": "Initializers define the way to set the initial random weights of Keras layers." }, { "code": null, "e": 2168, "s": 2117, "text": "We will use mean_absolute_error as a loss function" }, { "code": null, "e": 2211, "s": 2168, "text": "Define the output layer with only one node" }, { "code": null, "e": 2272, "s": 2211, "text": "Use ‘linear ’as the activation function for the output layer" }, { "code": null, "e": 3274, "s": 2272, "text": "[Out]:_________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense_1 (Dense) (None, 128) 19200 _________________________________________________________________ dense_2 (Dense) (None, 256) 33024 _________________________________________________________________ dense_3 (Dense) (None, 256) 65792 _________________________________________________________________ dense_4 (Dense) (None, 256) 65792 _________________________________________________________________ dense_5 (Dense) (None, 1) 257 ================================================================= Total params: 184,065 Trainable params: 184,065 Non-trainable params: 0 _________________________________________________________________" }, { "code": null, "e": 3305, "s": 3274, "text": "Define a checkpoint callback :" }, { "code": null, "e": 3938, "s": 3305, "text": "[out]:Train on 1168 samples, validate on 292 samplesEpoch 1/5001168/1168 [==============================] - 0s 266us/step - loss: 19251.8903 - mean_absolute_error: 19251.8903 - val_loss: 23041.8968 - val_mean_absolute_error: 23041.8968 Epoch 00001: val_loss did not improve from 21730.93555 Epoch 2/500 1168/1168 [==============================] - 0s 268us/step - loss: 18180.4985 - mean_absolute_error: 18180.4985 - val_loss: 22197.7991 - val_mean_absolute_error: 22197.7991 Epoch 00002: val_loss did not improve from 21730.93555...Epoch 00500: val_loss did not improve from 18738.19831<keras.callbacks.History at 0x7f4324aa80b8>" }, { "code": null, "e": 4000, "s": 3938, "text": "We see that the validation loss of the best model is 18738.19" }, { "code": null, "e": 4089, "s": 4000, "text": "We will submit the predictions on the test data to Kaggle and see how good our model is." }, { "code": null, "e": 4172, "s": 4089, "text": "Not bad at all, with some more preprocessing, and more training, we can do better." }, { "code": null, "e": 4233, "s": 4172, "text": "Now, let us try another ML algorithm to compare the results." }, { "code": null, "e": 4287, "s": 4233, "text": "We will use random forest regressor and XGBRegressor." }, { "code": null, "e": 4339, "s": 4287, "text": "Split training data to training and validation data" }, { "code": null, "e": 4378, "s": 4339, "text": "We will try Random forest model first:" }, { "code": null, "e": 4428, "s": 4378, "text": "Random forest validation MAE = 19089.71589041096" }, { "code": null, "e": 4495, "s": 4428, "text": "Make a submission file and submit it to Kaggle to see the result :" }, { "code": null, "e": 4527, "s": 4495, "text": "Now, let us try XGBoost model :" }, { "code": null, "e": 4578, "s": 4527, "text": "[out]: XGBoost validation MAE = 17869.75410958904" }, { "code": null, "e": 4645, "s": 4578, "text": "Make a submission file and submit it to Kaggle to see the result :" }, { "code": null, "e": 4967, "s": 4645, "text": "Isn’t that a surprise, I really did not think that neural networks will beat random forests and XGBoost algorithms, but let us try not to be too optimistic, remember that we did not configure any hyperparameters on random forest and XGBoost models, I believe if we did so, these two models would outscore neural networks." }, { "code": null, "e": 5001, "s": 4967, "text": "We load and processed the dataset" }, { "code": null, "e": 5105, "s": 5001, "text": "We got familiar with the dataset by plotting some histograms and a correlation heat map of the features" }, { "code": null, "e": 5184, "s": 5105, "text": "We used a deep neural network with three hidden layers each one has 256 nodes." }, { "code": null, "e": 5241, "s": 5184, "text": "We used a linear activation function on the output layer" }, { "code": null, "e": 5286, "s": 5241, "text": "We trained the model then test it on Kaggle." }, { "code": null, "e": 5318, "s": 5286, "text": "We also tested two other models" }, { "code": null, "e": 5380, "s": 5318, "text": "Our deep neural network was able to outscore these two models" }, { "code": null, "e": 5489, "s": 5380, "text": "We believe that these two models could beat the deep neural network model if we tweak their hyperparameters." }, { "code": null, "e": 5538, "s": 5489, "text": "Try to put more effort on processing the dataset" }, { "code": null, "e": 5573, "s": 5538, "text": "Try other types of neural networks" }, { "code": null, "e": 5637, "s": 5573, "text": "Try to tweak the hyperparameters of the two models that we used" }, { "code": null, "e": 5716, "s": 5637, "text": "If you really want to get better at regression problems, follow this tutorial:" }, { "code": null, "e": 5771, "s": 5716, "text": "[Stacked Regressions : Top 4% on LeaderBoard | Kaggle]" }, { "code": null, "e": 5838, "s": 5771, "text": "Regression Tutorial with the Keras Deep Learning Library in Python" }, { "code": null, "e": 5879, "s": 5838, "text": "You can follow me on Twitter @ModMaamari" }, { "code": null, "e": 5919, "s": 5879, "text": "AI Generates Taylor Swift’s Song Lyrics" }, { "code": null, "e": 5971, "s": 5919, "text": "Introduction to Random Forest Algorithm with Python" }, { "code": null, "e": 6030, "s": 5971, "text": "Machine Learning Crash Course with TensorFlow APIs Summary" }, { "code": null, "e": 6077, "s": 6030, "text": "How To Make A CNN Using Tensorflow and Keras ?" } ]
HTML - textarea Tag
The HTML <textarea> tag is used within a form to declare a textarea element - a control that allows the user to input text over multiple rows. <!DOCTYPE html> <html> <head> <title>HTML textarea Tag</title> </head> <body> <form action = "/cgi-bin/hello_get.cgi" method = "get"> Fill the Detail: <br /> <textarea rows = "5" cols = "50" name = "description"> Enter your name </textarea> <input type = "submit" value = "submit" /> </form> </body> </html> This will produce the following result − This tag supports all the global attributes described in − HTML Attribute Reference The HTML <textarea> tag also supports the following additional attributes − This tag supports all the event attributes described in − HTML Events Reference 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2517, "s": 2374, "text": "The HTML <textarea> tag is used within a form to declare a textarea element - a control that allows the user to input text over multiple rows." }, { "code": null, "e": 2936, "s": 2517, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML textarea Tag</title>\n </head>\n\n <body>\n <form action = \"/cgi-bin/hello_get.cgi\" method = \"get\">\n Fill the Detail: \n <br />\n \n <textarea rows = \"5\" cols = \"50\" name = \"description\">\n Enter your name\n </textarea>\n \n <input type = \"submit\" value = \"submit\" />\n </form>\n </body>\n\n</html>" }, { "code": null, "e": 2977, "s": 2936, "text": "This will produce the following result −" }, { "code": null, "e": 3061, "s": 2977, "text": "This tag supports all the global attributes described in − HTML Attribute Reference" }, { "code": null, "e": 3137, "s": 3061, "text": "The HTML <textarea> tag also supports the following additional attributes −" }, { "code": null, "e": 3217, "s": 3137, "text": "This tag supports all the event attributes described in − HTML Events Reference" }, { "code": null, "e": 3250, "s": 3217, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 3264, "s": 3250, "text": " Anadi Sharma" }, { "code": null, "e": 3299, "s": 3264, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3313, "s": 3299, "text": " Anadi Sharma" }, { "code": null, "e": 3348, "s": 3313, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3365, "s": 3348, "text": " Frahaan Hussain" }, { "code": null, "e": 3400, "s": 3365, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3431, "s": 3400, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3464, "s": 3431, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 3495, "s": 3464, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3530, "s": 3495, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3561, "s": 3530, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3568, "s": 3561, "text": " Print" }, { "code": null, "e": 3579, "s": 3568, "text": " Add Notes" } ]
AWT GridLayout Class
The class GridLayout arranges components in a rectangular grid. Following is the declaration for java.awt.GridLayout class: public class GridLayout extends Object implements LayoutManager, Serializable GridLayout() Creates a grid layout with a default of one column per component, in a single row. GridLayout(int rows, int cols) Creates a grid layout with the specified number of rows and columns. GridLayout(int rows, int cols, int hgap, int vgap) Creates a grid layout with the specified number of rows and columns. void addLayoutComponent(String name, Component comp) Adds the specified component with the specified name to the layout. int getColumns() Gets the number of columns in this layout. int getHgap() Gets the horizontal gap between components. int getRows() Gets the number of rows in this layout. int getVgap() Gets the vertical gap between components. void layoutContainer(Container parent) Lays out the specified container using this layout. Dimension minimumLayoutSize(Container parent) Determines the minimum size of the container argument using this grid layout. Dimension preferredLayoutSize(Container parent) Determines the preferred size of the container argument using this grid layout. void removeLayoutComponent(Component comp) Removes the specified component from the layout. void setColumns(int cols) Sets the number of columns in this layout to the specified value. void setHgap(int hgap) Sets the horizontal gap between components to the specified value. void setRows(int rows) Sets the number of rows in this layout to the specified value. void setVgap(int vgap) Sets the vertical gap between components to the specified value. String toString() Returns the string representation of this grid layout's values. This class inherits methods from the following classes: java.lang.Object java.lang.Object Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui > package com.tutorialspoint.gui; import java.awt.*; import java.awt.event.*; public class AwtLayoutDemo { private Frame mainFrame; private Label headerLabel; private Label statusLabel; private Panel controlPanel; private Label msglabel; public AwtLayoutDemo(){ prepareGUI(); } public static void main(String[] args){ AwtLayoutDemo awtLayoutDemo = new AwtLayoutDemo(); awtLayoutDemo.showGridLayoutDemo(); } private void prepareGUI(){ mainFrame = new Frame("Java AWT Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); headerLabel = new Label(); headerLabel.setAlignment(Label.CENTER); statusLabel = new Label(); statusLabel.setAlignment(Label.CENTER); statusLabel.setSize(350,100); msglabel = new Label(); msglabel.setAlignment(Label.CENTER); msglabel.setText("Welcome to TutorialsPoint AWT Tutorial."); controlPanel = new Panel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showGridLayoutDemo(){ headerLabel.setText("Layout in action: GridLayout"); Panel panel = new Panel(); panel.setBackground(Color.darkGray); panel.setSize(300,300); GridLayout layout = new GridLayout(0,3); layout.setHgap(10); layout.setVgap(10); panel.setLayout(layout); panel.add(new Button("Button 1")); panel.add(new Button("Button 2")); panel.add(new Button("Button 3")); panel.add(new Button("Button 4")); panel.add(new Button("Button 5")); controlPanel.add(panel); mainFrame.setVisible(true); } } Compile the program using command prompt. Go to D:/ > AWT and type the following command. D:\AWT>javac com\tutorialspoint\gui\AwtlayoutDemo.java If no error comes that means compilation is successful. Run the program using following command. D:\AWT>java com.tutorialspoint.gui.AwtlayoutDemo Verify the following output 13 Lectures 2 hours EduOLC Print Add Notes Bookmark this page
[ { "code": null, "e": 1811, "s": 1747, "text": "The class GridLayout arranges components in a rectangular grid." }, { "code": null, "e": 1871, "s": 1811, "text": "Following is the declaration for java.awt.GridLayout class:" }, { "code": null, "e": 1958, "s": 1871, "text": "public class GridLayout\n extends Object\n implements LayoutManager, Serializable" }, { "code": null, "e": 1971, "s": 1958, "text": "GridLayout()" }, { "code": null, "e": 2054, "s": 1971, "text": "Creates a grid layout with a default of one column per component, in a single row." }, { "code": null, "e": 2086, "s": 2054, "text": "GridLayout(int rows, int cols) " }, { "code": null, "e": 2155, "s": 2086, "text": "Creates a grid layout with the specified number of rows and columns." }, { "code": null, "e": 2207, "s": 2155, "text": "GridLayout(int rows, int cols, int hgap, int vgap) " }, { "code": null, "e": 2276, "s": 2207, "text": "Creates a grid layout with the specified number of rows and columns." }, { "code": null, "e": 2330, "s": 2276, "text": "void addLayoutComponent(String name, Component comp) " }, { "code": null, "e": 2398, "s": 2330, "text": "Adds the specified component with the specified name to the layout." }, { "code": null, "e": 2416, "s": 2398, "text": "int getColumns() " }, { "code": null, "e": 2459, "s": 2416, "text": "Gets the number of columns in this layout." }, { "code": null, "e": 2474, "s": 2459, "text": "int getHgap() " }, { "code": null, "e": 2518, "s": 2474, "text": "Gets the horizontal gap between components." }, { "code": null, "e": 2534, "s": 2518, "text": "int getRows() \n" }, { "code": null, "e": 2574, "s": 2534, "text": "Gets the number of rows in this layout." }, { "code": null, "e": 2589, "s": 2574, "text": "int getVgap() " }, { "code": null, "e": 2631, "s": 2589, "text": "Gets the vertical gap between components." }, { "code": null, "e": 2671, "s": 2631, "text": "void layoutContainer(Container parent) " }, { "code": null, "e": 2723, "s": 2671, "text": "Lays out the specified container using this layout." }, { "code": null, "e": 2770, "s": 2723, "text": "Dimension minimumLayoutSize(Container parent) " }, { "code": null, "e": 2848, "s": 2770, "text": "Determines the minimum size of the container argument using this grid layout." }, { "code": null, "e": 2897, "s": 2848, "text": "Dimension preferredLayoutSize(Container parent) " }, { "code": null, "e": 2977, "s": 2897, "text": "Determines the preferred size of the container argument using this grid layout." }, { "code": null, "e": 3021, "s": 2977, "text": "void removeLayoutComponent(Component comp) " }, { "code": null, "e": 3070, "s": 3021, "text": "Removes the specified component from the layout." }, { "code": null, "e": 3097, "s": 3070, "text": "void setColumns(int cols) " }, { "code": null, "e": 3163, "s": 3097, "text": "Sets the number of columns in this layout to the specified value." }, { "code": null, "e": 3187, "s": 3163, "text": "void setHgap(int hgap) " }, { "code": null, "e": 3254, "s": 3187, "text": "Sets the horizontal gap between components to the specified value." }, { "code": null, "e": 3278, "s": 3254, "text": "void setRows(int rows) " }, { "code": null, "e": 3341, "s": 3278, "text": "Sets the number of rows in this layout to the specified value." }, { "code": null, "e": 3365, "s": 3341, "text": "void setVgap(int vgap) " }, { "code": null, "e": 3430, "s": 3365, "text": "Sets the vertical gap between components to the specified value." }, { "code": null, "e": 3449, "s": 3430, "text": "String toString() " }, { "code": null, "e": 3513, "s": 3449, "text": "Returns the string representation of this grid layout's values." }, { "code": null, "e": 3569, "s": 3513, "text": "This class inherits methods from the following classes:" }, { "code": null, "e": 3586, "s": 3569, "text": "java.lang.Object" }, { "code": null, "e": 3603, "s": 3586, "text": "java.lang.Object" }, { "code": null, "e": 3717, "s": 3603, "text": "Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >" }, { "code": null, "e": 5739, "s": 3717, "text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class AwtLayoutDemo {\n private Frame mainFrame;\n private Label headerLabel;\n private Label statusLabel;\n private Panel controlPanel;\n private Label msglabel;\n\n public AwtLayoutDemo(){\n prepareGUI();\n }\n\n public static void main(String[] args){\n AwtLayoutDemo awtLayoutDemo = new AwtLayoutDemo(); \n awtLayoutDemo.showGridLayoutDemo(); \n }\n \n private void prepareGUI(){\n mainFrame = new Frame(\"Java AWT Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n headerLabel = new Label();\n headerLabel.setAlignment(Label.CENTER);\n statusLabel = new Label(); \n statusLabel.setAlignment(Label.CENTER);\n statusLabel.setSize(350,100);\n\n msglabel = new Label();\n msglabel.setAlignment(Label.CENTER);\n msglabel.setText(\"Welcome to TutorialsPoint AWT Tutorial.\");\n\n controlPanel = new Panel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n\n private void showGridLayoutDemo(){\n headerLabel.setText(\"Layout in action: GridLayout\"); \n\n Panel panel = new Panel();\n panel.setBackground(Color.darkGray);\n panel.setSize(300,300);\n GridLayout layout = new GridLayout(0,3);\n layout.setHgap(10);\n layout.setVgap(10);\n \n panel.setLayout(layout); \n panel.add(new Button(\"Button 1\"));\n panel.add(new Button(\"Button 2\")); \n panel.add(new Button(\"Button 3\")); \n panel.add(new Button(\"Button 4\")); \n panel.add(new Button(\"Button 5\")); \n controlPanel.add(panel);\n mainFrame.setVisible(true); \n }\n}" }, { "code": null, "e": 5830, "s": 5739, "text": "Compile the program using command prompt. Go to D:/ > AWT and type the following command." }, { "code": null, "e": 5885, "s": 5830, "text": "D:\\AWT>javac com\\tutorialspoint\\gui\\AwtlayoutDemo.java" }, { "code": null, "e": 5982, "s": 5885, "text": "If no error comes that means compilation is successful. Run the program using following command." }, { "code": null, "e": 6031, "s": 5982, "text": "D:\\AWT>java com.tutorialspoint.gui.AwtlayoutDemo" }, { "code": null, "e": 6059, "s": 6031, "text": "Verify the following output" }, { "code": null, "e": 6092, "s": 6059, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 6100, "s": 6092, "text": " EduOLC" }, { "code": null, "e": 6107, "s": 6100, "text": " Print" }, { "code": null, "e": 6118, "s": 6107, "text": " Add Notes" } ]
Finding Floor and Ceil of a Sorted Array using C++ STL - GeeksforGeeks
26 Oct, 2021 Given a sorted array, the task is to find the floor and ceil of given numbers using STL.Examples: Input: arr[] = {1, 2, 4, 7, 11, 12, 23, 30, 32}, values[] = { 1, 3, 5, 7, 20, 24 } Output: Floor Values: 1 2 4 7 12 23 Ceil values: 1 4 7 7 23 30 In case of floor(): lower_bound() method os STL will be used to find the lower bound. This returns an iterator pointing to the first element in the range [first,last) which does not compare less than the target.In case of ceil(): upper_bound() method os STL will be used to find the upper bound. This method returns an iterator pointing to the first element in the range [first,last) which compares greater than a target.Implementation: CPP // C++ program to find the floor and ceil// of a given numbers in a sorted array #include <bits/stdc++.h>using namespace std; // Function to find floor of list of// values using lower_bound in STLvoid printFloor(int arr[], int n1, int findFloor[], int n2){ // Find and print the Floor Values int low; cout << "Floor : "; for (int i = 0; i < n2; i++) { low = (lower_bound(arr, arr + n1, findFloor[i]) - arr); if (arr[low] > findFloor[i]) cout << arr[low - 1] << " "; else cout << arr[low] << " "; } cout << endl;}ceil// Function to find Ceil of list of// values using upper_bound in STLvoid printCeil(int arr[], int n1, int findCeil[], int n2){ // Find and print the Ceil Values int up; cout << "Ceil : "; for (int i = 0; i < n2; i++) { up = (upper_bound(arr, arr + n1, findCeil[i]) - arr); if (arr[up] > findCeil[i] && arr[up - 1] == findCeil[i]) { cout << arr[up - 1] << " "; } else cout << arr[up] << " "; } cout << endl;} // Driver codeint main(){ // Get the sorted array int arr[] = { 1, 2, 4, 7, 11, 12, 23, 30, 32 }; int n1 = sizeof(arr) / sizeof(arr[0]); // Print Array cout << "Original Array: "; for (unsigned int i = 0; i < n1; i++) cout << " " << arr[i]; cout << "\n"; // Given values whose floor and ceil // values are needed to find int find[] = { 1, 3, 5, 7, 20, 24 }; int n2 = sizeof(find) / sizeof(find[0]); // Print Values whose floor // and ceil is to be found cout << "Values: "; for (unsigned int i = 0; i < n2; i++) cout << find[i] << " "; cout << "\n"; // Print Floor Values printFloor(arr, n1, find, n2); // Print Ceil Values printCeil(arr, n1, find, n2); return 0;} Array: 1 2 4 7 11 12 23 30 32 Values: 1 3 5 7 20 24 Floor : 1 2 4 7 12 23 Ceil : 1 4 7 7 23 30 jatishay444 akshaysingh98088 saurabh1990aror Binary Search STL Technical Scripter 2018 C++ C++ Programs Technical Scripter STL Binary Search CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Sorting a vector in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) Header files in C/C++ and its uses How to return multiple values from a function in C or C++? C++ Program for QuickSort Program to print ASCII Value of a character Sorting a Map by value in C++ STL
[ { "code": null, "e": 24098, "s": 24070, "text": "\n26 Oct, 2021" }, { "code": null, "e": 24198, "s": 24098, "text": "Given a sorted array, the task is to find the floor and ceil of given numbers using STL.Examples: " }, { "code": null, "e": 24360, "s": 24198, "text": "Input: arr[] = {1, 2, 4, 7, 11, 12, 23, 30, 32},\n values[] = { 1, 3, 5, 7, 20, 24 }\nOutput: Floor Values: 1 2 4 7 12 23 \n Ceil values: 1 4 7 7 23 30 " }, { "code": null, "e": 24799, "s": 24360, "text": "In case of floor(): lower_bound() method os STL will be used to find the lower bound. This returns an iterator pointing to the first element in the range [first,last) which does not compare less than the target.In case of ceil(): upper_bound() method os STL will be used to find the upper bound. This method returns an iterator pointing to the first element in the range [first,last) which compares greater than a target.Implementation: " }, { "code": null, "e": 24803, "s": 24799, "text": "CPP" }, { "code": "// C++ program to find the floor and ceil// of a given numbers in a sorted array #include <bits/stdc++.h>using namespace std; // Function to find floor of list of// values using lower_bound in STLvoid printFloor(int arr[], int n1, int findFloor[], int n2){ // Find and print the Floor Values int low; cout << \"Floor : \"; for (int i = 0; i < n2; i++) { low = (lower_bound(arr, arr + n1, findFloor[i]) - arr); if (arr[low] > findFloor[i]) cout << arr[low - 1] << \" \"; else cout << arr[low] << \" \"; } cout << endl;}ceil// Function to find Ceil of list of// values using upper_bound in STLvoid printCeil(int arr[], int n1, int findCeil[], int n2){ // Find and print the Ceil Values int up; cout << \"Ceil : \"; for (int i = 0; i < n2; i++) { up = (upper_bound(arr, arr + n1, findCeil[i]) - arr); if (arr[up] > findCeil[i] && arr[up - 1] == findCeil[i]) { cout << arr[up - 1] << \" \"; } else cout << arr[up] << \" \"; } cout << endl;} // Driver codeint main(){ // Get the sorted array int arr[] = { 1, 2, 4, 7, 11, 12, 23, 30, 32 }; int n1 = sizeof(arr) / sizeof(arr[0]); // Print Array cout << \"Original Array: \"; for (unsigned int i = 0; i < n1; i++) cout << \" \" << arr[i]; cout << \"\\n\"; // Given values whose floor and ceil // values are needed to find int find[] = { 1, 3, 5, 7, 20, 24 }; int n2 = sizeof(find) / sizeof(find[0]); // Print Values whose floor // and ceil is to be found cout << \"Values: \"; for (unsigned int i = 0; i < n2; i++) cout << find[i] << \" \"; cout << \"\\n\"; // Print Floor Values printFloor(arr, n1, find, n2); // Print Ceil Values printCeil(arr, n1, find, n2); return 0;}", "e": 26729, "s": 24803, "text": null }, { "code": null, "e": 26828, "s": 26729, "text": "Array: 1 2 4 7 11 12 23 30 32\nValues: 1 3 5 7 20 24 \nFloor : 1 2 4 7 12 23 \nCeil : 1 4 7 7 23 30" }, { "code": null, "e": 26842, "s": 26830, "text": "jatishay444" }, { "code": null, "e": 26859, "s": 26842, "text": "akshaysingh98088" }, { "code": null, "e": 26875, "s": 26859, "text": "saurabh1990aror" }, { "code": null, "e": 26889, "s": 26875, "text": "Binary Search" }, { "code": null, "e": 26893, "s": 26889, "text": "STL" }, { "code": null, "e": 26917, "s": 26893, "text": "Technical Scripter 2018" }, { "code": null, "e": 26921, "s": 26917, "text": "C++" }, { "code": null, "e": 26934, "s": 26921, "text": "C++ Programs" }, { "code": null, "e": 26953, "s": 26934, "text": "Technical Scripter" }, { "code": null, "e": 26957, "s": 26953, "text": "STL" }, { "code": null, "e": 26971, "s": 26957, "text": "Binary Search" }, { "code": null, "e": 26975, "s": 26971, "text": "CPP" }, { "code": null, "e": 27073, "s": 26975, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27101, "s": 27073, "text": "Operator Overloading in C++" }, { "code": null, "e": 27121, "s": 27101, "text": "Polymorphism in C++" }, { "code": null, "e": 27145, "s": 27121, "text": "Sorting a vector in C++" }, { "code": null, "e": 27178, "s": 27145, "text": "Friend class and function in C++" }, { "code": null, "e": 27222, "s": 27178, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 27257, "s": 27222, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 27316, "s": 27257, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 27342, "s": 27316, "text": "C++ Program for QuickSort" }, { "code": null, "e": 27386, "s": 27342, "text": "Program to print ASCII Value of a character" } ]
Check if a String is not empty ("") and not null in Java
Let’s say we have the following string − String myStr1 = "Jack Sparrow"; Let us check the string now whether it is not null or not empty. if(myStr != null || myStr.length() != 0) { System.out.println("String is not null or not empty"); Live Demo public class Demo { public static void main(String[] args) { String myStr = "Jack Sparrow"; boolean res; if(myStr != null || myStr.length() != 0) { System.out.println("String is not null or not empty"); } else { System.out.println("String is null or empty"); } } } String is not null or not empty
[ { "code": null, "e": 1103, "s": 1062, "text": "Let’s say we have the following string −" }, { "code": null, "e": 1135, "s": 1103, "text": "String myStr1 = \"Jack Sparrow\";" }, { "code": null, "e": 1200, "s": 1135, "text": "Let us check the string now whether it is not null or not empty." }, { "code": null, "e": 1298, "s": 1200, "text": "if(myStr != null || myStr.length() != 0) {\nSystem.out.println(\"String is not null or not empty\");" }, { "code": null, "e": 1309, "s": 1298, "text": " Live Demo" }, { "code": null, "e": 1628, "s": 1309, "text": "public class Demo {\n public static void main(String[] args) {\n String myStr = \"Jack Sparrow\";\n boolean res;\n if(myStr != null || myStr.length() != 0) {\n System.out.println(\"String is not null or not empty\");\n } else {\n System.out.println(\"String is null or empty\");\n }\n }\n}" }, { "code": null, "e": 1660, "s": 1628, "text": "String is not null or not empty" } ]
Number of character corrections in the given strings to make them equal - GeeksforGeeks
11 May, 2021 Given three strings A, B, and C. Each of these is a string of length N consisting of lowercase English letters. The task is to make all the strings equal by performing an operation where any character of the given strings can be replaced with any other character, print the count of the minimum number of such operations required. Examples: Input: A = “place”, B = “abcde”, C = “plybe” Output: 6 A = “place”, B = “abcde”, C = “plybe”. We can achieve the task in the minimum number of operations by performing six operations as follows: Change the first character in B to ‘p’. B is now “pbcde” Change the second character in B to ‘l’. B is now “plcde” Change the third character in B and C to ‘a’. B and C are now “plade” and “plabe” respectively. Change the fourth character in B to ‘c’. B is now “place” Change the fourth character in C to ‘c’. C is now “place”Input: A = “game”, B = “game”, C = “game” Output: 0 Approach: Run a loop, check if the ith characters of all the strings are equal then no operations are required. If two characters are equal then one operation is required and if all three characters are different from two operations are required. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <iostream>#include <bits/stdc++.h>using namespace std; // Function to return the count of operations requiredconst int minOperations(int n, string a, string b, string c){ // To store the count of operations int ans = 0; for (int i = 0; i < n; i++) { char x = a[i]; char y = b[i]; char z = c[i]; // No operation required if (x == y && y == z) ; // One operation is required when // any two characters are equal else if (x == y || y == z || x == z) { ans++; } // Two operations are required when // none of the characters are equal else { ans += 2; } } // Return the minimum count of operations required return ans;} // Driver codeint main(){ string a = "place"; string b = "abcde"; string c = "plybe"; int n = a.size(); cout << minOperations(n, a, b, c); return 0;} // This code is contributed by 29AjayKumar // Java implementation of the approachclass GFG { // Function to return the count of operations required static int minOperations(int n, String a, String b, String c) { // To store the count of operations int ans = 0; for (int i = 0; i < n; i++) { char x = a.charAt(i); char y = b.charAt(i); char z = c.charAt(i); // No operation required if (x == y && y == z) ; // One operation is required when // any two characters are equal else if (x == y || y == z || x == z) { ans++; } // Two operations are required when // none of the characters are equal else { ans += 2; } } // Return the minimum count of operations required return ans; } // Driver code public static void main(String[] args) { String a = "place"; String b = "abcde"; String c = "plybe"; int n = a.length(); System.out.print(minOperations(n, a, b, c)); }} # Python 3 implementation of the approach # Function to return the count# of operations requireddef minOperations(n, a, b, c): # To store the count of operations ans = 0 for i in range(n): x = a[i] y = b[i] z = c[i] # No operation required if (x == y and y == z): continue # One operation is required when # any two characters are equal elif (x == y or y == z or x == z): ans += 1 # Two operations are required when # none of the characters are equal else: ans += 2 # Return the minimum count # of operations required return ans # Driver codeif __name__ == '__main__': a = "place" b = "abcde" c = "plybe" n = len(a) print(minOperations(n, a, b, c)) # This code is contributed by# Surendra_Gangwar // C# implementation of the approachusing System; class GFG{ // Function to return the count of operations required static int minOperations(int n, string a, string b, string c) { // To store the count of operations int ans = 0; for (int i = 0; i < n; i++) { char x = a[i]; char y = b[i]; char z = c[i]; // No operation required if (x == y && y == z) {;} // One operation is required when // any two characters are equal else if (x == y || y == z || x == z) { ans++; } // Two operations are required when // none of the characters are equal else { ans += 2; } } // Return the minimum count of operations required return ans; } // Driver code public static void Main() { string a = "place"; string b = "abcde"; string c = "plybe"; int n = a.Length; Console.Write(minOperations(n, a, b, c)); }} // This code is contributed by Ryuga <?php// PHP implementation of the approach // Function to return the count of // operations requiredfunction minOperations($n, $a, $b, $c){ // To store the count of operations $ans = 0; for ($i = 0; $i < $n; $i++) { $x = $a[$i]; $y = $b[$i]; $z = $c[$i]; // No operation required if ($x == $y && $y == $z) ; // One operation is required when // any two characters are equal else if ($x == $y || $y == $z || $x == $z) { $ans++; } // Two operations are required when // none of the characters are equal else { $ans += 2; } } // Return the minimum count of // operations required return $ans;} // Driver code$a = "place";$b = "abcde";$c = "plybe";$n = strlen($a);echo minOperations($n, $a, $b, $c); // This code is contributed by ajit.?> <script> // Javascript implementation of the approach // Function to return the count of operations required function minOperations(n, a, b, c) { // To store the count of operations let ans = 0; for (let i = 0; i < n; i++) { let x = a[i]; let y = b[i]; let z = c[i]; // No operation required if (x == y && y == z) {;} // One operation is required when // any two characters are equal else if (x == y || y == z || x == z) { ans++; } // Two operations are required when // none of the characters are equal else { ans += 2; } } // Return the minimum count of operations required return ans; } let a = "place"; let b = "abcde"; let c = "plybe"; let n = a.length; document.write(minOperations(n, a, b, c)); </script> 6 ankthon 29AjayKumar jit_t SURENDRA_GANGWAR mukesh07 Java School Programming Strings 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 Stream In Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java Python Dictionary Arrays in C/C++ Inheritance in C++ C++ Classes and Objects Interfaces in Java
[ { "code": null, "e": 26373, "s": 26345, "text": "\n11 May, 2021" }, { "code": null, "e": 26704, "s": 26373, "text": "Given three strings A, B, and C. Each of these is a string of length N consisting of lowercase English letters. The task is to make all the strings equal by performing an operation where any character of the given strings can be replaced with any other character, print the count of the minimum number of such operations required." }, { "code": null, "e": 26716, "s": 26704, "text": "Examples: " }, { "code": null, "e": 27291, "s": 26716, "text": "Input: A = “place”, B = “abcde”, C = “plybe” Output: 6 A = “place”, B = “abcde”, C = “plybe”. We can achieve the task in the minimum number of operations by performing six operations as follows: Change the first character in B to ‘p’. B is now “pbcde” Change the second character in B to ‘l’. B is now “plcde” Change the third character in B and C to ‘a’. B and C are now “plade” and “plabe” respectively. Change the fourth character in B to ‘c’. B is now “place” Change the fourth character in C to ‘c’. C is now “place”Input: A = “game”, B = “game”, C = “game” Output: 0 " }, { "code": null, "e": 27540, "s": 27291, "text": "Approach: Run a loop, check if the ith characters of all the strings are equal then no operations are required. If two characters are equal then one operation is required and if all three characters are different from two operations are required. " }, { "code": null, "e": 27593, "s": 27540, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27597, "s": 27593, "text": "C++" }, { "code": null, "e": 27602, "s": 27597, "text": "Java" }, { "code": null, "e": 27610, "s": 27602, "text": "Python3" }, { "code": null, "e": 27613, "s": 27610, "text": "C#" }, { "code": null, "e": 27617, "s": 27613, "text": "PHP" }, { "code": null, "e": 27628, "s": 27617, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <iostream>#include <bits/stdc++.h>using namespace std; // Function to return the count of operations requiredconst int minOperations(int n, string a, string b, string c){ // To store the count of operations int ans = 0; for (int i = 0; i < n; i++) { char x = a[i]; char y = b[i]; char z = c[i]; // No operation required if (x == y && y == z) ; // One operation is required when // any two characters are equal else if (x == y || y == z || x == z) { ans++; } // Two operations are required when // none of the characters are equal else { ans += 2; } } // Return the minimum count of operations required return ans;} // Driver codeint main(){ string a = \"place\"; string b = \"abcde\"; string c = \"plybe\"; int n = a.size(); cout << minOperations(n, a, b, c); return 0;} // This code is contributed by 29AjayKumar", "e": 28676, "s": 27628, "text": null }, { "code": "// Java implementation of the approachclass GFG { // Function to return the count of operations required static int minOperations(int n, String a, String b, String c) { // To store the count of operations int ans = 0; for (int i = 0; i < n; i++) { char x = a.charAt(i); char y = b.charAt(i); char z = c.charAt(i); // No operation required if (x == y && y == z) ; // One operation is required when // any two characters are equal else if (x == y || y == z || x == z) { ans++; } // Two operations are required when // none of the characters are equal else { ans += 2; } } // Return the minimum count of operations required return ans; } // Driver code public static void main(String[] args) { String a = \"place\"; String b = \"abcde\"; String c = \"plybe\"; int n = a.length(); System.out.print(minOperations(n, a, b, c)); }}", "e": 29791, "s": 28676, "text": null }, { "code": "# Python 3 implementation of the approach # Function to return the count# of operations requireddef minOperations(n, a, b, c): # To store the count of operations ans = 0 for i in range(n): x = a[i] y = b[i] z = c[i] # No operation required if (x == y and y == z): continue # One operation is required when # any two characters are equal elif (x == y or y == z or x == z): ans += 1 # Two operations are required when # none of the characters are equal else: ans += 2 # Return the minimum count # of operations required return ans # Driver codeif __name__ == '__main__': a = \"place\" b = \"abcde\" c = \"plybe\" n = len(a) print(minOperations(n, a, b, c)) # This code is contributed by# Surendra_Gangwar", "e": 30652, "s": 29791, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the count of operations required static int minOperations(int n, string a, string b, string c) { // To store the count of operations int ans = 0; for (int i = 0; i < n; i++) { char x = a[i]; char y = b[i]; char z = c[i]; // No operation required if (x == y && y == z) {;} // One operation is required when // any two characters are equal else if (x == y || y == z || x == z) { ans++; } // Two operations are required when // none of the characters are equal else { ans += 2; } } // Return the minimum count of operations required return ans; } // Driver code public static void Main() { string a = \"place\"; string b = \"abcde\"; string c = \"plybe\"; int n = a.Length; Console.Write(minOperations(n, a, b, c)); }} // This code is contributed by Ryuga", "e": 31807, "s": 30652, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to return the count of // operations requiredfunction minOperations($n, $a, $b, $c){ // To store the count of operations $ans = 0; for ($i = 0; $i < $n; $i++) { $x = $a[$i]; $y = $b[$i]; $z = $c[$i]; // No operation required if ($x == $y && $y == $z) ; // One operation is required when // any two characters are equal else if ($x == $y || $y == $z || $x == $z) { $ans++; } // Two operations are required when // none of the characters are equal else { $ans += 2; } } // Return the minimum count of // operations required return $ans;} // Driver code$a = \"place\";$b = \"abcde\";$c = \"plybe\";$n = strlen($a);echo minOperations($n, $a, $b, $c); // This code is contributed by ajit.?>", "e": 32737, "s": 31807, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the count of operations required function minOperations(n, a, b, c) { // To store the count of operations let ans = 0; for (let i = 0; i < n; i++) { let x = a[i]; let y = b[i]; let z = c[i]; // No operation required if (x == y && y == z) {;} // One operation is required when // any two characters are equal else if (x == y || y == z || x == z) { ans++; } // Two operations are required when // none of the characters are equal else { ans += 2; } } // Return the minimum count of operations required return ans; } let a = \"place\"; let b = \"abcde\"; let c = \"plybe\"; let n = a.length; document.write(minOperations(n, a, b, c)); </script>", "e": 33763, "s": 32737, "text": null }, { "code": null, "e": 33765, "s": 33763, "text": "6" }, { "code": null, "e": 33775, "s": 33767, "text": "ankthon" }, { "code": null, "e": 33787, "s": 33775, "text": "29AjayKumar" }, { "code": null, "e": 33793, "s": 33787, "text": "jit_t" }, { "code": null, "e": 33810, "s": 33793, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 33819, "s": 33810, "text": "mukesh07" }, { "code": null, "e": 33824, "s": 33819, "text": "Java" }, { "code": null, "e": 33843, "s": 33824, "text": "School Programming" }, { "code": null, "e": 33851, "s": 33843, "text": "Strings" }, { "code": null, "e": 33859, "s": 33851, "text": "Strings" }, { "code": null, "e": 33864, "s": 33859, "text": "Java" }, { "code": null, "e": 33962, "s": 33864, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34013, "s": 33962, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 34028, "s": 34013, "text": "Stream In Java" }, { "code": null, "e": 34058, "s": 34028, "text": "HashMap in Java with Examples" }, { "code": null, "e": 34077, "s": 34058, "text": "Interfaces in Java" }, { "code": null, "e": 34108, "s": 34077, "text": "How to iterate any Map in Java" }, { "code": null, "e": 34126, "s": 34108, "text": "Python Dictionary" }, { "code": null, "e": 34142, "s": 34126, "text": "Arrays in C/C++" }, { "code": null, "e": 34161, "s": 34142, "text": "Inheritance in C++" }, { "code": null, "e": 34185, "s": 34161, "text": "C++ Classes and Objects" } ]
How to merge two csv files by specific column using Pandas in Python? - GeeksforGeeks
13 Jan, 2021 In this article, we are going to discuss how to merge two CSV files there is a function in pandas library pandas.merge(). Merging means nothing but combining two datasets together into one based on common attributes or column. Syntax: pandas.merge() Parameters : data1, data2: Dataframes used for merging. how: {‘left’, ‘right’, ‘outer’, ‘inner’}, default ‘inner’ on: label or list Returns : A DataFrame of the two merged objects. Inner Left Right Outer We are going to use the below two csv files i.e. loan.csv and borrower.csv to perform all operations: By setting how=’inner‘ it will merge both dataframes based on the specified column and then return new dataframe containing only those rows that have a matching value in both original dataframes. Code: Python3 import pandas as pd # reading two csv filesdata1 = pd.read_csv('datasets/loan.csv')data2 = pd.read_csv('datasets/borrower.csv') # using merge function by setting how='inner'output1 = pd.merge(data1, data2, on='LOAN_NO', how='inner') # displaying resultprint(output1) Output: By setting how=’left’ it will merge both dataframes based on the specified column and then return new dataframe containing all rows from left dataframe including those rows also who do not have values in the right dataframe and set right dataframe column value to NAN. Code: Python3 import pandas as pd # reading csv filesdata1 = pd.read_csv('datasets/loan.csv')data2 = pd.read_csv('datasets/borrower.csv') # using merge function by setting how='left'output2 = pd.merge(data1, data2, on='LOAN_NO', how='left') # displaying resultprint(output2) Output: By setting how=’right’ it will merge both dataframes based on the specified column and then return new dataframe containing all rows from right dataframe including those rows also who do not have values in the left dataframe and set left dataframe column value to NAN. Code: Python3 import pandas as pd # reading csv filesdata1 = pd.read_csv('datasets/loan.csv')data2 = pd.read_csv('datasets/borrower.csv') # using merge function by setting how='right'output3 = pd.merge(data1, data2, on='LOAN_NO', how='right') # displaying resultprint(output3) Output: By setting how=’right’ it will merge both dataframes based on the specified column and then return new dataframe containing rows from both dataframes and set NAN value for those where data is missing in one of the dataframes. Code: Python3 import pandas as pd # reading csv filesdata1 = pd.read_csv('datasets/loan.csv')data2 = pd.read_csv('datasets/borrower.csv') # using merge function by setting how='outer'output4 = pd.merge(data1, data2, on='LOAN_NO', how='outer') # displaying resultprint(output4) Output: Picked Python pandas-io Python-pandas 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": 26500, "s": 26472, "text": "\n13 Jan, 2021" }, { "code": null, "e": 26727, "s": 26500, "text": "In this article, we are going to discuss how to merge two CSV files there is a function in pandas library pandas.merge(). Merging means nothing but combining two datasets together into one based on common attributes or column." }, { "code": null, "e": 26750, "s": 26727, "text": "Syntax: pandas.merge()" }, { "code": null, "e": 26763, "s": 26750, "text": "Parameters :" }, { "code": null, "e": 26806, "s": 26763, "text": "data1, data2: Dataframes used for merging." }, { "code": null, "e": 26864, "s": 26806, "text": "how: {‘left’, ‘right’, ‘outer’, ‘inner’}, default ‘inner’" }, { "code": null, "e": 26882, "s": 26864, "text": "on: label or list" }, { "code": null, "e": 26931, "s": 26882, "text": "Returns : A DataFrame of the two merged objects." }, { "code": null, "e": 26937, "s": 26931, "text": "Inner" }, { "code": null, "e": 26942, "s": 26937, "text": "Left" }, { "code": null, "e": 26948, "s": 26942, "text": "Right" }, { "code": null, "e": 26954, "s": 26948, "text": "Outer" }, { "code": null, "e": 27056, "s": 26954, "text": "We are going to use the below two csv files i.e. loan.csv and borrower.csv to perform all operations:" }, { "code": null, "e": 27252, "s": 27056, "text": "By setting how=’inner‘ it will merge both dataframes based on the specified column and then return new dataframe containing only those rows that have a matching value in both original dataframes." }, { "code": null, "e": 27258, "s": 27252, "text": "Code:" }, { "code": null, "e": 27266, "s": 27258, "text": "Python3" }, { "code": "import pandas as pd # reading two csv filesdata1 = pd.read_csv('datasets/loan.csv')data2 = pd.read_csv('datasets/borrower.csv') # using merge function by setting how='inner'output1 = pd.merge(data1, data2, on='LOAN_NO', how='inner') # displaying resultprint(output1)", "e": 27574, "s": 27266, "text": null }, { "code": null, "e": 27582, "s": 27574, "text": "Output:" }, { "code": null, "e": 27852, "s": 27582, "text": "By setting how=’left’ it will merge both dataframes based on the specified column and then return new dataframe containing all rows from left dataframe including those rows also who do not have values in the right dataframe and set right dataframe column value to NAN. " }, { "code": null, "e": 27858, "s": 27852, "text": "Code:" }, { "code": null, "e": 27866, "s": 27858, "text": "Python3" }, { "code": "import pandas as pd # reading csv filesdata1 = pd.read_csv('datasets/loan.csv')data2 = pd.read_csv('datasets/borrower.csv') # using merge function by setting how='left'output2 = pd.merge(data1, data2, on='LOAN_NO', how='left') # displaying resultprint(output2)", "e": 28168, "s": 27866, "text": null }, { "code": null, "e": 28176, "s": 28168, "text": "Output:" }, { "code": null, "e": 28446, "s": 28176, "text": "By setting how=’right’ it will merge both dataframes based on the specified column and then return new dataframe containing all rows from right dataframe including those rows also who do not have values in the left dataframe and set left dataframe column value to NAN. " }, { "code": null, "e": 28452, "s": 28446, "text": "Code:" }, { "code": null, "e": 28460, "s": 28452, "text": "Python3" }, { "code": "import pandas as pd # reading csv filesdata1 = pd.read_csv('datasets/loan.csv')data2 = pd.read_csv('datasets/borrower.csv') # using merge function by setting how='right'output3 = pd.merge(data1, data2, on='LOAN_NO', how='right') # displaying resultprint(output3)", "e": 28762, "s": 28460, "text": null }, { "code": null, "e": 28770, "s": 28762, "text": "Output:" }, { "code": null, "e": 28996, "s": 28770, "text": "By setting how=’right’ it will merge both dataframes based on the specified column and then return new dataframe containing rows from both dataframes and set NAN value for those where data is missing in one of the dataframes." }, { "code": null, "e": 29002, "s": 28996, "text": "Code:" }, { "code": null, "e": 29010, "s": 29002, "text": "Python3" }, { "code": "import pandas as pd # reading csv filesdata1 = pd.read_csv('datasets/loan.csv')data2 = pd.read_csv('datasets/borrower.csv') # using merge function by setting how='outer'output4 = pd.merge(data1, data2, on='LOAN_NO', how='outer') # displaying resultprint(output4)", "e": 29314, "s": 29010, "text": null }, { "code": null, "e": 29322, "s": 29314, "text": "Output:" }, { "code": null, "e": 29329, "s": 29322, "text": "Picked" }, { "code": null, "e": 29346, "s": 29329, "text": "Python pandas-io" }, { "code": null, "e": 29360, "s": 29346, "text": "Python-pandas" }, { "code": null, "e": 29367, "s": 29360, "text": "Python" }, { "code": null, "e": 29465, "s": 29367, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29483, "s": 29465, "text": "Python Dictionary" }, { "code": null, "e": 29518, "s": 29483, "text": "Read a file line by line in Python" }, { "code": null, "e": 29550, "s": 29518, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29572, "s": 29550, "text": "Enumerate() in Python" }, { "code": null, "e": 29614, "s": 29572, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29644, "s": 29614, "text": "Iterate over a list in Python" }, { "code": null, "e": 29670, "s": 29644, "text": "Python String | replace()" }, { "code": null, "e": 29699, "s": 29670, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29743, "s": 29699, "text": "Reading and Writing to text files in Python" } ]
Schedule Optimisation using Linear Programming in Python | by Lewis Woolfson | Towards Data Science
Scheduling is an everyday challenge for many organisations. From allocating jobs on a manufacturing line to timetabling hospital surgery cases, the problem of how to efficiently manage limited resources pops up all the time. While ‘back-of-the-envelope’ planning can take us so far, there are often times where more advanced prescriptive analytics tools such as linear programming can help decision-makers identify the best choices quickly. The technology is not new — mathematical programming has been around for decades — but in recent years it has become more accessible. Improvements to the algorithmic performance of linear solvers have enabled more complex problems to be tackled in reasonable time frames; open-source libraries such as Pyomo make it possible to build models in familiar coding languages, and digitalisation has increased the availability of high-quality data. Yet despite these advances, traditional optimisation methods are often overlooked by Data Scientists and Analysts. In this post, I hope to demonstrate the value of linear programming and show how to get started with building models in Python. To do this we will construct a basic model to optimise theatre scheduling in hospitals. I’ll assume familiarity with Python and basic knowledge of linear optimisation concepts. Source code and data can be found here: https://github.com/Lewisw3/theatre-scheduling Scheduling is crucial to the smooth running of an operating theatre department. Effective scheduling benefits all parties: the medical staff, the healthcare provider, and not least, the patients. But surgery planning remains a major challenge for hospitals. A recent study commissioned by NHS Improvement reported that an additional 290,000 operations could be completed each year with improved management of surgical lists and holiday bookings [1]. That was pre-Covid. The pandemic has since created a significant backlog in elective care so effective management of theatre schedules is even more pertinent than usual. It’s a complex challenge and the solution does not lie with analytics alone. In this post, we will consider just a simplified example of elective surgery planning for an individual surgeon. Our goal is to highlight the potential of analytics to support theatre planning — the model is not intended to be a real-world decision support tool! There is plenty of literature on theatre schedule optimisation. If you are interested I recommend the review papers by Guerriero and Guido [2] and Cardoen et al. [3]. Suppose a hospital theatre department is planning elective surgeries for a consultant ophthalmologist. The hospital maintains two lists: A list of operations (cases) assigned to the consultant to be performed before a deadline A list of operating theatre time blocks (theatre sessions) allocated to the consultant Theatre sessions can be either half-day (8.30am-1pm) or full-day (8.30am-6pm) sessions and the consultant is typically allocated one theatre session per week. The task is to assign the consultant’s upcoming cases to their theatre sessions in such a way that we maximise the utilisation of each session. Utilisation is defined as the percentage of the theatre time block that is filled up by surgery cases. Cases must be completed before their target deadline and at least 15% of a theatre session’s time block should be kept free for other activities (e.g. sterilisation, staff breaks, etc.) We formulate the problem as a flexible job-shop scheduling problem where a surgical case is analogous to a job and a theatre session to a machine. We start by defining our decision variables, linear constraints, and a linear objective function. Before we begin, let's look at the data. We have two data sources: cases.csv and sessions.csv. cases.csv contains a list of all upcoming elective surgeries: sessions.csv contains a list of all upcoming theatre sessions: The full CSV files are available on the Github repo. We start by importing the relevant data into a Pyomo ConcreteModel object using Sets (similar to arrays) and Params (key-value pairs). We use a number of helper functions to initialize the Pyomo Sets and Params. These are omitted here for brevity but can be found on the Github repo. We also define a Set called TASKS that contains a list of all possible combinations of (CaseID, SessionID). This represents all potential case allocation decisions available: The main decision is assigning cases to sessions. This requires a binary yes/no decision to be made for each case-session combination in the TASKS Set above. We also want to calculate the start time of each case and the utilisation of each session. All in, we have 3 decisions variables: We define these decision variables in our Pyomo model as follows: An advantage of linear programming is the flexibility to define an objective function that represents our business needs. We are free to define any (linear) function, and in our case, our goal is to maximise the utilisation of all sessions: Next, we add our constraints. The constraints capture all the rules (not so realistic in this example!) that ensure the solution returned by the model constitutes a feasible theatre schedule. Here we have 6 rules: The start time of a case must be after the start time of the session it is assigned toA case must end before the end of its allocated sessionA case can be assigned to at most one sessionCases cannot be assigned to a session after their deadline dateNo two cases can overlap: the start time of one case must be after the end time of another caseThe utilisation of a session is equal to the fraction of the session duration that is taken up by surgical cases The start time of a case must be after the start time of the session it is assigned to A case must end before the end of its allocated session A case can be assigned to at most one session Cases cannot be assigned to a session after their deadline date No two cases can overlap: the start time of one case must be after the end time of another case The utilisation of a session is equal to the fraction of the session duration that is taken up by surgical cases We also restrict the bounds of our decision variables. The utilisation must be between 0 and 85% (because 15% of the session must be kept free for other activities) and that the start time of a case must be between 0 and the number of minutes in a day (1440). The Constraints above are added to the model by writing a separate Python function for each constraint and using Pyomo’s Constraint method: To define these constraints as linear equations we make use of two helpful techniques worth noting: Big M formulation and a logical disjunction. Big M Formulation The big M method is a trick to switch on and off constraints. For example, constraint 1 above states that a case must start after the session start time. This is only valid for the session that the case is assigned to. It shouldn’t hold for all the other sessions. We ensure this happens with the inequality: case_start_time >= session_start_time - (1 - session_assigned)*M where M is a sufficiently large constant and session_assigned is a binary variable. After staring at this long enough it begins to make sense. If session_assigned is equal to 1 then the rule must be held. However, if session_assigned is 0 then (assuming M is large enough) the second term on the RHS becomes much larger than the first so the entire RHS is always negative. Since our variable bounds force case_start_time ≥ 0, there is effectively no additional restriction. Disjunctive Programming Constraint number 5 is a logical disjunction: a set of constraints that are linked by an OR relationship. The disjunction states that for any pair of cases in the same session, either case 1 happens before case 2 or case 2 happens before case 1. This relationship is non-linear so we must convert it into a linear constraint to work with standard linear solvers. To do this we used Pyomo’s Generalised Disjunctive Programming (GDP) modelling extension (see line 27 in the code snippet above). It allows us to define the disjunction as a simple Python function and all we need to do to convert the “disjunctive” model back to a standard mixed-inter programming (MIP) model is to include the following line: pe.TransformationFactory("gdp.bigm").apply_to(model) The GDP extension may be avoided by adding big M constraints and introducing a new binary variable to the model, but we’ll keep the disjunction as it works and is readable. And finally, we are done! In full the linear programming model is: An advantage of using an interface such as Pyomo is that it is easy to try out different linear solvers without rewriting the model in another coding language. Here we use Coin-or Branch and Cut (CBC) — an open-source mixed-integer program solver (https://github.com/coin-or/Cbc). The code snippet below solves the model using Pyomo’s SolverFactory class. The class can take a number of tuning parameters to control the operation of the chosen solver, but for simplicity, we keep default settings except for a time limit of 60 seconds. Below is a Gantt chart to visualise the solution returned by the model. The input case and session data are available here: The chart above shows a feasible schedule for cases and sessions that maximises the utilisation of all sessions subject to our constraints. The input data provided to the model had more demand (case time) than capacity (session time), and the model found that dropping case #2 (a Vitrectomy with 70 min duration) was the best option to maximise the total utilisation across all sessions. Linear programming is a powerful tool for helping organisations make informed decisions quickly. It is a useful skill for Data Scientists, and with open-source libraries such as Pyomo it is easy to formulate models in Python. In this post, we created a simple optimisation model for efficiently scheduling surgery cases. Despite not being a real-world solution, it demonstrates how optimisation methods like linear programming may support planners get the most out of their available resources. Potential next steps with this model are to: tune the solver parameters to improve performance and reduce solve time reformulate the model to simplify the problem and reduce solve time adjust the objective function to better represent performance targets incorporate additional constraints to better represent real-world elective theatre scheduling use a more sophisticated approach for predicting case times On that last bullet point, prescriptive analytical techniques such as linear programming are increasingly being combined with predictive methods such as machine learning. For a scheduling application like the one presented here, machine learning could be used to predict the duration of tasks or even which tasks are going to occur. Once the demand is predicted, optimisation methods can help with the planning. Thanks for reading! Please do not hesitate to reach out if you have any questions or comments. [1] NHS Improvement (2019). Operating theatres: opportunities to reduce waiting lists. Available at: https://improvement.nhs.uk/resources/operating-theatres-opportunities-reduce-waiting-lists/ [2]Guerriero, F., Guido, R. Operational research in the management of the operating theatre: a survey. Health Care Manag Sci 14, 89–114 (2011). https://doi.org/10.1007/s10729-010-9143-6 [3] Cardoen et al. Operating room planning and scheduling: A literature review. European Journal of Operational Research 201(3), 921–932 (2010). https://doi.org/10.1016/j.ejor.2009.04.011
[ { "code": null, "e": 397, "s": 172, "text": "Scheduling is an everyday challenge for many organisations. From allocating jobs on a manufacturing line to timetabling hospital surgery cases, the problem of how to efficiently manage limited resources pops up all the time." }, { "code": null, "e": 613, "s": 397, "text": "While ‘back-of-the-envelope’ planning can take us so far, there are often times where more advanced prescriptive analytics tools such as linear programming can help decision-makers identify the best choices quickly." }, { "code": null, "e": 1056, "s": 613, "text": "The technology is not new — mathematical programming has been around for decades — but in recent years it has become more accessible. Improvements to the algorithmic performance of linear solvers have enabled more complex problems to be tackled in reasonable time frames; open-source libraries such as Pyomo make it possible to build models in familiar coding languages, and digitalisation has increased the availability of high-quality data." }, { "code": null, "e": 1171, "s": 1056, "text": "Yet despite these advances, traditional optimisation methods are often overlooked by Data Scientists and Analysts." }, { "code": null, "e": 1387, "s": 1171, "text": "In this post, I hope to demonstrate the value of linear programming and show how to get started with building models in Python. To do this we will construct a basic model to optimise theatre scheduling in hospitals." }, { "code": null, "e": 1476, "s": 1387, "text": "I’ll assume familiarity with Python and basic knowledge of linear optimisation concepts." }, { "code": null, "e": 1562, "s": 1476, "text": "Source code and data can be found here: https://github.com/Lewisw3/theatre-scheduling" }, { "code": null, "e": 2012, "s": 1562, "text": "Scheduling is crucial to the smooth running of an operating theatre department. Effective scheduling benefits all parties: the medical staff, the healthcare provider, and not least, the patients. But surgery planning remains a major challenge for hospitals. A recent study commissioned by NHS Improvement reported that an additional 290,000 operations could be completed each year with improved management of surgical lists and holiday bookings [1]." }, { "code": null, "e": 2182, "s": 2012, "text": "That was pre-Covid. The pandemic has since created a significant backlog in elective care so effective management of theatre schedules is even more pertinent than usual." }, { "code": null, "e": 2259, "s": 2182, "text": "It’s a complex challenge and the solution does not lie with analytics alone." }, { "code": null, "e": 2522, "s": 2259, "text": "In this post, we will consider just a simplified example of elective surgery planning for an individual surgeon. Our goal is to highlight the potential of analytics to support theatre planning — the model is not intended to be a real-world decision support tool!" }, { "code": null, "e": 2689, "s": 2522, "text": "There is plenty of literature on theatre schedule optimisation. If you are interested I recommend the review papers by Guerriero and Guido [2] and Cardoen et al. [3]." }, { "code": null, "e": 2826, "s": 2689, "text": "Suppose a hospital theatre department is planning elective surgeries for a consultant ophthalmologist. The hospital maintains two lists:" }, { "code": null, "e": 2916, "s": 2826, "text": "A list of operations (cases) assigned to the consultant to be performed before a deadline" }, { "code": null, "e": 3003, "s": 2916, "text": "A list of operating theatre time blocks (theatre sessions) allocated to the consultant" }, { "code": null, "e": 3306, "s": 3003, "text": "Theatre sessions can be either half-day (8.30am-1pm) or full-day (8.30am-6pm) sessions and the consultant is typically allocated one theatre session per week. The task is to assign the consultant’s upcoming cases to their theatre sessions in such a way that we maximise the utilisation of each session." }, { "code": null, "e": 3409, "s": 3306, "text": "Utilisation is defined as the percentage of the theatre time block that is filled up by surgery cases." }, { "code": null, "e": 3595, "s": 3409, "text": "Cases must be completed before their target deadline and at least 15% of a theatre session’s time block should be kept free for other activities (e.g. sterilisation, staff breaks, etc.)" }, { "code": null, "e": 3840, "s": 3595, "text": "We formulate the problem as a flexible job-shop scheduling problem where a surgical case is analogous to a job and a theatre session to a machine. We start by defining our decision variables, linear constraints, and a linear objective function." }, { "code": null, "e": 3935, "s": 3840, "text": "Before we begin, let's look at the data. We have two data sources: cases.csv and sessions.csv." }, { "code": null, "e": 3997, "s": 3935, "text": "cases.csv contains a list of all upcoming elective surgeries:" }, { "code": null, "e": 4060, "s": 3997, "text": "sessions.csv contains a list of all upcoming theatre sessions:" }, { "code": null, "e": 4113, "s": 4060, "text": "The full CSV files are available on the Github repo." }, { "code": null, "e": 4248, "s": 4113, "text": "We start by importing the relevant data into a Pyomo ConcreteModel object using Sets (similar to arrays) and Params (key-value pairs)." }, { "code": null, "e": 4397, "s": 4248, "text": "We use a number of helper functions to initialize the Pyomo Sets and Params. These are omitted here for brevity but can be found on the Github repo." }, { "code": null, "e": 4572, "s": 4397, "text": "We also define a Set called TASKS that contains a list of all possible combinations of (CaseID, SessionID). This represents all potential case allocation decisions available:" }, { "code": null, "e": 4730, "s": 4572, "text": "The main decision is assigning cases to sessions. This requires a binary yes/no decision to be made for each case-session combination in the TASKS Set above." }, { "code": null, "e": 4860, "s": 4730, "text": "We also want to calculate the start time of each case and the utilisation of each session. All in, we have 3 decisions variables:" }, { "code": null, "e": 4926, "s": 4860, "text": "We define these decision variables in our Pyomo model as follows:" }, { "code": null, "e": 5167, "s": 4926, "text": "An advantage of linear programming is the flexibility to define an objective function that represents our business needs. We are free to define any (linear) function, and in our case, our goal is to maximise the utilisation of all sessions:" }, { "code": null, "e": 5381, "s": 5167, "text": "Next, we add our constraints. The constraints capture all the rules (not so realistic in this example!) that ensure the solution returned by the model constitutes a feasible theatre schedule. Here we have 6 rules:" }, { "code": null, "e": 5838, "s": 5381, "text": "The start time of a case must be after the start time of the session it is assigned toA case must end before the end of its allocated sessionA case can be assigned to at most one sessionCases cannot be assigned to a session after their deadline dateNo two cases can overlap: the start time of one case must be after the end time of another caseThe utilisation of a session is equal to the fraction of the session duration that is taken up by surgical cases" }, { "code": null, "e": 5925, "s": 5838, "text": "The start time of a case must be after the start time of the session it is assigned to" }, { "code": null, "e": 5981, "s": 5925, "text": "A case must end before the end of its allocated session" }, { "code": null, "e": 6027, "s": 5981, "text": "A case can be assigned to at most one session" }, { "code": null, "e": 6091, "s": 6027, "text": "Cases cannot be assigned to a session after their deadline date" }, { "code": null, "e": 6187, "s": 6091, "text": "No two cases can overlap: the start time of one case must be after the end time of another case" }, { "code": null, "e": 6300, "s": 6187, "text": "The utilisation of a session is equal to the fraction of the session duration that is taken up by surgical cases" }, { "code": null, "e": 6560, "s": 6300, "text": "We also restrict the bounds of our decision variables. The utilisation must be between 0 and 85% (because 15% of the session must be kept free for other activities) and that the start time of a case must be between 0 and the number of minutes in a day (1440)." }, { "code": null, "e": 6700, "s": 6560, "text": "The Constraints above are added to the model by writing a separate Python function for each constraint and using Pyomo’s Constraint method:" }, { "code": null, "e": 6845, "s": 6700, "text": "To define these constraints as linear equations we make use of two helpful techniques worth noting: Big M formulation and a logical disjunction." }, { "code": null, "e": 6863, "s": 6845, "text": "Big M Formulation" }, { "code": null, "e": 7172, "s": 6863, "text": "The big M method is a trick to switch on and off constraints. For example, constraint 1 above states that a case must start after the session start time. This is only valid for the session that the case is assigned to. It shouldn’t hold for all the other sessions. We ensure this happens with the inequality:" }, { "code": null, "e": 7237, "s": 7172, "text": "case_start_time >= session_start_time - (1 - session_assigned)*M" }, { "code": null, "e": 7711, "s": 7237, "text": "where M is a sufficiently large constant and session_assigned is a binary variable. After staring at this long enough it begins to make sense. If session_assigned is equal to 1 then the rule must be held. However, if session_assigned is 0 then (assuming M is large enough) the second term on the RHS becomes much larger than the first so the entire RHS is always negative. Since our variable bounds force case_start_time ≥ 0, there is effectively no additional restriction." }, { "code": null, "e": 7735, "s": 7711, "text": "Disjunctive Programming" }, { "code": null, "e": 7981, "s": 7735, "text": "Constraint number 5 is a logical disjunction: a set of constraints that are linked by an OR relationship. The disjunction states that for any pair of cases in the same session, either case 1 happens before case 2 or case 2 happens before case 1." }, { "code": null, "e": 8441, "s": 7981, "text": "This relationship is non-linear so we must convert it into a linear constraint to work with standard linear solvers. To do this we used Pyomo’s Generalised Disjunctive Programming (GDP) modelling extension (see line 27 in the code snippet above). It allows us to define the disjunction as a simple Python function and all we need to do to convert the “disjunctive” model back to a standard mixed-inter programming (MIP) model is to include the following line:" }, { "code": null, "e": 8494, "s": 8441, "text": "pe.TransformationFactory(\"gdp.bigm\").apply_to(model)" }, { "code": null, "e": 8667, "s": 8494, "text": "The GDP extension may be avoided by adding big M constraints and introducing a new binary variable to the model, but we’ll keep the disjunction as it works and is readable." }, { "code": null, "e": 8734, "s": 8667, "text": "And finally, we are done! In full the linear programming model is:" }, { "code": null, "e": 8894, "s": 8734, "text": "An advantage of using an interface such as Pyomo is that it is easy to try out different linear solvers without rewriting the model in another coding language." }, { "code": null, "e": 9015, "s": 8894, "text": "Here we use Coin-or Branch and Cut (CBC) — an open-source mixed-integer program solver (https://github.com/coin-or/Cbc)." }, { "code": null, "e": 9270, "s": 9015, "text": "The code snippet below solves the model using Pyomo’s SolverFactory class. The class can take a number of tuning parameters to control the operation of the chosen solver, but for simplicity, we keep default settings except for a time limit of 60 seconds." }, { "code": null, "e": 9394, "s": 9270, "text": "Below is a Gantt chart to visualise the solution returned by the model. The input case and session data are available here:" }, { "code": null, "e": 9782, "s": 9394, "text": "The chart above shows a feasible schedule for cases and sessions that maximises the utilisation of all sessions subject to our constraints. The input data provided to the model had more demand (case time) than capacity (session time), and the model found that dropping case #2 (a Vitrectomy with 70 min duration) was the best option to maximise the total utilisation across all sessions." }, { "code": null, "e": 10008, "s": 9782, "text": "Linear programming is a powerful tool for helping organisations make informed decisions quickly. It is a useful skill for Data Scientists, and with open-source libraries such as Pyomo it is easy to formulate models in Python." }, { "code": null, "e": 10277, "s": 10008, "text": "In this post, we created a simple optimisation model for efficiently scheduling surgery cases. Despite not being a real-world solution, it demonstrates how optimisation methods like linear programming may support planners get the most out of their available resources." }, { "code": null, "e": 10322, "s": 10277, "text": "Potential next steps with this model are to:" }, { "code": null, "e": 10394, "s": 10322, "text": "tune the solver parameters to improve performance and reduce solve time" }, { "code": null, "e": 10462, "s": 10394, "text": "reformulate the model to simplify the problem and reduce solve time" }, { "code": null, "e": 10532, "s": 10462, "text": "adjust the objective function to better represent performance targets" }, { "code": null, "e": 10626, "s": 10532, "text": "incorporate additional constraints to better represent real-world elective theatre scheduling" }, { "code": null, "e": 10686, "s": 10626, "text": "use a more sophisticated approach for predicting case times" }, { "code": null, "e": 11098, "s": 10686, "text": "On that last bullet point, prescriptive analytical techniques such as linear programming are increasingly being combined with predictive methods such as machine learning. For a scheduling application like the one presented here, machine learning could be used to predict the duration of tasks or even which tasks are going to occur. Once the demand is predicted, optimisation methods can help with the planning." }, { "code": null, "e": 11193, "s": 11098, "text": "Thanks for reading! Please do not hesitate to reach out if you have any questions or comments." }, { "code": null, "e": 11386, "s": 11193, "text": "[1] NHS Improvement (2019). Operating theatres: opportunities to reduce waiting lists. Available at: https://improvement.nhs.uk/resources/operating-theatres-opportunities-reduce-waiting-lists/" }, { "code": null, "e": 11572, "s": 11386, "text": "[2]Guerriero, F., Guido, R. Operational research in the management of the operating theatre: a survey. Health Care Manag Sci 14, 89–114 (2011). https://doi.org/10.1007/s10729-010-9143-6" } ]
Count of ways to write N as a sum of three numbers - GeeksforGeeks
20 Apr, 2021 Given a positive integer N, count number of ways to write N as a sum of three numbers. For numbers which are not expressible print -1.Examples: Input: N = 4 Output: 3 Explanation: ( 1 + 1 + 2 ) = 4 ( 1 + 2 + 1 ) = 4 ( 2 + 1 + 1 ) = 4. So in total, there are 3 ways.Input: N = 5 Output: 6 ( 1 + 1 + 3 ) = 5 ( 1 + 3 + 1 ) = 5 ( 3 + 1 + 1 ) = 5 ( 1 + 2 + 2 ) = 5 ( 2 + 2 + 1 ) = 5 ( 2 + 1 + 2 ) = 5. So in total, there are 6 ways Approach: To solve the problem mentioned above if we take a closer look we will observe a pattern in solution to the question. For all the numbers that are greater than 2 we get a series 3, 6, 10, 15, 25 and so on, which is nothing but the sum of first N-1 natural numbers.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to count the total number of// ways to write N as a sum of three numbers #include <bits/stdc++.h>using namespace std; // Function to find the number of waysvoid countWays(int n){ // Check if number is less than 2 if (n <= 2) cout << "-1"; else { // Calculate the sum int ans = (n - 1) * (n - 2) / 2; cout << ans; }} // Driver codeint main(){ int N = 5; countWays(N); return 0;} // Java program to count the total number of// ways to write N as a sum of three numbersclass GFG{ // Function to find the number of waysstatic void countWays(int n){ // Check if number is less than 2 if (n <= 2) { System.out.print("-1"); } else { // Calculate the sum int ans = (n - 1) * (n - 2) / 2; System.out.print(ans); }} // Driver codepublic static void main(String[] args){ int N = 5; countWays(N);}} // This code is contributed by Amit Katiyar # Python3 program to count the total number of# ways to write N as a sum of three numbersdef countWays(N): # Check if number is less than 2 if (N <= 2): print("-1") else: # Calculate the sum ans = (N - 1) * (N - 2) / 2 print(ans) # Driver codeif __name__ == '__main__': N = 5 countWays(N) # This code is contributed by coder001 // C# program to count the total number of// ways to write N as a sum of three numbersusing System; class GFG{ // Function to find the number of waysstatic void countWays(int n){ // Check if number is less than 2 if (n <= 2) { Console.WriteLine("-1"); } else { // Calculate the sum int ans = (n - 1) * (n - 2) / 2; Console.WriteLine(ans); }} // Driver code static void Main(){ int N = 5; countWays(N);}} // This code is contributed by divyeshrabadiya07 <script> // Javascript program to count the total number of// ways to write N as a sum of three numbers // Function to find the number of waysfunction countWays(n){ // Check if number is less than 2 if (n <= 2) document.write( "-1"); else { // Calculate the sum var ans = (n - 1) * (n - 2) / 2; document.write( ans); }} // Driver code var N = 5;countWays(N); </script> 6 Time Complexity: O(1) amit143katiyar coder001 divyeshrabadiya07 rutvik_56 Natural Numbers series Mathematical School Programming Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Print all possible combinations of r elements in a given array of size n Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26411, "s": 26383, "text": "\n20 Apr, 2021" }, { "code": null, "e": 26556, "s": 26411, "text": "Given a positive integer N, count number of ways to write N as a sum of three numbers. For numbers which are not expressible print -1.Examples: " }, { "code": null, "e": 26841, "s": 26556, "text": "Input: N = 4 Output: 3 Explanation: ( 1 + 1 + 2 ) = 4 ( 1 + 2 + 1 ) = 4 ( 2 + 1 + 1 ) = 4. So in total, there are 3 ways.Input: N = 5 Output: 6 ( 1 + 1 + 3 ) = 5 ( 1 + 3 + 1 ) = 5 ( 3 + 1 + 1 ) = 5 ( 1 + 2 + 2 ) = 5 ( 2 + 2 + 1 ) = 5 ( 2 + 1 + 2 ) = 5. So in total, there are 6 ways " }, { "code": null, "e": 27169, "s": 26843, "text": "Approach: To solve the problem mentioned above if we take a closer look we will observe a pattern in solution to the question. For all the numbers that are greater than 2 we get a series 3, 6, 10, 15, 25 and so on, which is nothing but the sum of first N-1 natural numbers.Below is the implementation of the above approach: " }, { "code": null, "e": 27173, "s": 27169, "text": "C++" }, { "code": null, "e": 27178, "s": 27173, "text": "Java" }, { "code": null, "e": 27186, "s": 27178, "text": "Python3" }, { "code": null, "e": 27189, "s": 27186, "text": "C#" }, { "code": null, "e": 27200, "s": 27189, "text": "Javascript" }, { "code": "// C++ program to count the total number of// ways to write N as a sum of three numbers #include <bits/stdc++.h>using namespace std; // Function to find the number of waysvoid countWays(int n){ // Check if number is less than 2 if (n <= 2) cout << \"-1\"; else { // Calculate the sum int ans = (n - 1) * (n - 2) / 2; cout << ans; }} // Driver codeint main(){ int N = 5; countWays(N); return 0;}", "e": 27646, "s": 27200, "text": null }, { "code": "// Java program to count the total number of// ways to write N as a sum of three numbersclass GFG{ // Function to find the number of waysstatic void countWays(int n){ // Check if number is less than 2 if (n <= 2) { System.out.print(\"-1\"); } else { // Calculate the sum int ans = (n - 1) * (n - 2) / 2; System.out.print(ans); }} // Driver codepublic static void main(String[] args){ int N = 5; countWays(N);}} // This code is contributed by Amit Katiyar", "e": 28168, "s": 27646, "text": null }, { "code": "# Python3 program to count the total number of# ways to write N as a sum of three numbersdef countWays(N): # Check if number is less than 2 if (N <= 2): print(\"-1\") else: # Calculate the sum ans = (N - 1) * (N - 2) / 2 print(ans) # Driver codeif __name__ == '__main__': N = 5 countWays(N) # This code is contributed by coder001", "e": 28559, "s": 28168, "text": null }, { "code": "// C# program to count the total number of// ways to write N as a sum of three numbersusing System; class GFG{ // Function to find the number of waysstatic void countWays(int n){ // Check if number is less than 2 if (n <= 2) { Console.WriteLine(\"-1\"); } else { // Calculate the sum int ans = (n - 1) * (n - 2) / 2; Console.WriteLine(ans); }} // Driver code static void Main(){ int N = 5; countWays(N);}} // This code is contributed by divyeshrabadiya07 ", "e": 29087, "s": 28559, "text": null }, { "code": "<script> // Javascript program to count the total number of// ways to write N as a sum of three numbers // Function to find the number of waysfunction countWays(n){ // Check if number is less than 2 if (n <= 2) document.write( \"-1\"); else { // Calculate the sum var ans = (n - 1) * (n - 2) / 2; document.write( ans); }} // Driver code var N = 5;countWays(N); </script>", "e": 29498, "s": 29087, "text": null }, { "code": null, "e": 29500, "s": 29498, "text": "6" }, { "code": null, "e": 29525, "s": 29502, "text": "Time Complexity: O(1) " }, { "code": null, "e": 29540, "s": 29525, "text": "amit143katiyar" }, { "code": null, "e": 29549, "s": 29540, "text": "coder001" }, { "code": null, "e": 29567, "s": 29549, "text": "divyeshrabadiya07" }, { "code": null, "e": 29577, "s": 29567, "text": "rutvik_56" }, { "code": null, "e": 29593, "s": 29577, "text": "Natural Numbers" }, { "code": null, "e": 29600, "s": 29593, "text": "series" }, { "code": null, "e": 29613, "s": 29600, "text": "Mathematical" }, { "code": null, "e": 29632, "s": 29613, "text": "School Programming" }, { "code": null, "e": 29645, "s": 29632, "text": "Mathematical" }, { "code": null, "e": 29652, "s": 29645, "text": "series" }, { "code": null, "e": 29750, "s": 29652, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29774, "s": 29750, "text": "Merge two sorted arrays" }, { "code": null, "e": 29817, "s": 29774, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 29831, "s": 29817, "text": "Prime Numbers" }, { "code": null, "e": 29873, "s": 29831, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 29946, "s": 29873, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 29964, "s": 29946, "text": "Python Dictionary" }, { "code": null, "e": 29980, "s": 29964, "text": "Arrays in C/C++" }, { "code": null, "e": 29999, "s": 29980, "text": "Inheritance in C++" }, { "code": null, "e": 30024, "s": 29999, "text": "Reverse a string in Java" } ]
HTML strong Tag - GeeksforGeeks
17 Mar, 2022 The <strong> tag in HTML is the parsed tag and used to show the importance of the text. Make that text bold. Syntax: <strong> Contents... </strong> Example: HTML <!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2><strong> Tag</h2> <!-- html strong tag used here --> <strong>Welcome to geeksforGeeks!</strong> </body> </html> Output: Example 2: Use CSS property to set bold font weight. HTML <!DOCTYPE html><html> <head> <title>strong Tag</title> <style> body { text-align:center; } h1 { color:green; } .gfg { font-weight:bold; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>font-weight: bold;</h2> <div class = "gfg">Welcome to geeksforGeeks!</div> </body></html> Output: Supported Browsers: Google Chrome Internet Explorer Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. shubhamyadav4 HTML-Tags HTML HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML How to Insert Form Data into Database using PHP ? CSS to put icon inside an input element in a form
[ { "code": null, "e": 24391, "s": 24363, "text": "\n17 Mar, 2022" }, { "code": null, "e": 24500, "s": 24391, "text": "The <strong> tag in HTML is the parsed tag and used to show the importance of the text. Make that text bold." }, { "code": null, "e": 24509, "s": 24500, "text": "Syntax: " }, { "code": null, "e": 24540, "s": 24509, "text": "<strong> Contents... </strong>" }, { "code": null, "e": 24550, "s": 24540, "text": "Example: " }, { "code": null, "e": 24555, "s": 24550, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2><strong> Tag</h2> <!-- html strong tag used here --> <strong>Welcome to geeksforGeeks!</strong> </body> </html>", "e": 24762, "s": 24555, "text": null }, { "code": null, "e": 24772, "s": 24762, "text": "Output: " }, { "code": null, "e": 24826, "s": 24772, "text": "Example 2: Use CSS property to set bold font weight. " }, { "code": null, "e": 24831, "s": 24826, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>strong Tag</title> <style> body { text-align:center; } h1 { color:green; } .gfg { font-weight:bold; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>font-weight: bold;</h2> <div class = \"gfg\">Welcome to geeksforGeeks!</div> </body></html> ", "e": 25294, "s": 24831, "text": null }, { "code": null, "e": 25304, "s": 25294, "text": "Output: " }, { "code": null, "e": 25325, "s": 25304, "text": "Supported Browsers: " }, { "code": null, "e": 25339, "s": 25325, "text": "Google Chrome" }, { "code": null, "e": 25357, "s": 25339, "text": "Internet Explorer" }, { "code": null, "e": 25365, "s": 25357, "text": "Firefox" }, { "code": null, "e": 25371, "s": 25365, "text": "Opera" }, { "code": null, "e": 25378, "s": 25371, "text": "Safari" }, { "code": null, "e": 25517, "s": 25380, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 25531, "s": 25517, "text": "shubhamyadav4" }, { "code": null, "e": 25541, "s": 25531, "text": "HTML-Tags" }, { "code": null, "e": 25546, "s": 25541, "text": "HTML" }, { "code": null, "e": 25551, "s": 25546, "text": "HTML" }, { "code": null, "e": 25649, "s": 25551, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25699, "s": 25649, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 25761, "s": 25699, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 25821, "s": 25761, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 25869, "s": 25821, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 25922, "s": 25869, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 25983, "s": 25922, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 26007, "s": 25983, "text": "REST API (Introduction)" }, { "code": null, "e": 26048, "s": 26007, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 26098, "s": 26048, "text": "How to Insert Form Data into Database using PHP ?" } ]
Can you create an array of Generics type in Java?
Generics is a concept in Java where you can enable a class, interface and, method, accept all (reference) types as parameters. In other words it is the concept which enables the users to choose the reference type that a method, constructor of a class accepts, dynamically. By defining a class as generic you are making it type-safe i.e. it can act up on any datatype. Live Demo class Student<T>{ T age; Student(T age){ this.age = age; } public void display() { System.out.println("Value of age: "+this.age); } } public class GenericsExample { public static void main(String args[]) { Student<Float> std1 = new Student<Float>(25.5f); std1.display(); Student<String> std2 = new Student<String>("25"); std2.display(); Student<Integer> std3 = new Student<Integer>(25); std3.display(); } } Value of age: 25.5 Value of age: 25 Value of age: 25 No, we cannot create an array of generic type objects if you try to do so, a compile time error is generated. Live Demo class Student<T>{ T age; Student(T age){ this.age = age; } public void display() { System.out.println("Value of age: "+this.age); } } public class GenericsExample { public static void main(String args[]) { Student<Float>[] std1 = new Student<Float>[5]; } } GenericsExample.java:12: error: generic array creation Student<Float>[] std1 = new Student<Float>[5]; ^ 1 error
[ { "code": null, "e": 1430, "s": 1062, "text": "Generics is a concept in Java where you can enable a class, interface and, method, accept all (reference) types as parameters. In other words it is the concept which enables the users to choose the reference type that a method, constructor of a class accepts, dynamically. By defining a class as generic you are making it type-safe i.e. it can act up on any datatype." }, { "code": null, "e": 1441, "s": 1430, "text": " Live Demo" }, { "code": null, "e": 1917, "s": 1441, "text": "class Student<T>{\n T age;\n Student(T age){\n this.age = age;\n }\n public void display() {\n System.out.println(\"Value of age: \"+this.age);\n }\n}\npublic class GenericsExample {\n public static void main(String args[]) {\n Student<Float> std1 = new Student<Float>(25.5f);\n std1.display();\n Student<String> std2 = new Student<String>(\"25\");\n std2.display();\n Student<Integer> std3 = new Student<Integer>(25);\n std3.display();\n }\n}" }, { "code": null, "e": 1970, "s": 1917, "text": "Value of age: 25.5\nValue of age: 25\nValue of age: 25" }, { "code": null, "e": 2080, "s": 1970, "text": "No, we cannot create an array of generic type objects if you try to do so, a compile time error is generated." }, { "code": null, "e": 2091, "s": 2080, "text": " Live Demo" }, { "code": null, "e": 2387, "s": 2091, "text": "class Student<T>{\n T age;\n Student(T age){\n this.age = age;\n }\n public void display() {\n System.out.println(\"Value of age: \"+this.age);\n }\n}\npublic class GenericsExample {\n public static void main(String args[]) {\n Student<Float>[] std1 = new Student<Float>[5];\n }\n}" }, { "code": null, "e": 2535, "s": 2387, "text": "GenericsExample.java:12: error: generic array creation\n Student<Float>[] std1 = new Student<Float>[5];\n ^\n1 error" } ]
How to check if remote ports are open using PowerShell?
Earlier days we were using telnet clients to check the remote port connectivity, in fact, we are still using it with cmd and PowerShell but this feature is not by default installed in OS and some companies have restrictions on installing new features including telnet. We can leverage PowerShell to test remote port connectivity without installing telnet and with the use of the Test-NetConnection command. This command is also very useful for other diagnostics but we are focusing here for the remote port check. To check if the remote port is open or not we can use the Test-NetConnection command and it requires -ComputerName parameter and -Port to check the remote port status. Test-NetConnection -ComputerName Test1-Win2k12 -Port 80 ComputerName : Test1-Win2k12 RemoteAddress : 192.168.0.107 RemotePort : 80 InterfaceAlias : Ethernet0 SourceAddress : 192.168.0.106 TcpTestSucceeded : True The above example will check Port number 80 con ectivity on remote server Test1-Win2k12. You can see that the TcpTestSucceeded property is true so the port is open. One more example shown below is WInRM https port 5986. Test-NetConnection -ComputerName Test1-Win2k12 -Port 5986 WARNING: TCP connect to Test1-Win2k12:5986 failed ComputerName : Test1-Win2k12 RemoteAddress : 192.168.0.107 RemotePort : 5986 InterfaceAlias : Ethernet0 SourceAddress : 192.168.0.106 PingSucceeded : True PingReplyDetails (RTT) : 0 ms TcpTestSucceeded : False You can see that the WinRM SSL port is not open on the remote server and a warning message is displayed in the first line as well as in the TcpTestSucceeded property.
[ { "code": null, "e": 1331, "s": 1062, "text": "Earlier days we were using telnet clients to check the remote port connectivity, in fact, we are still using it with cmd and PowerShell but this feature is not by default installed in OS and some companies have restrictions on installing new features including telnet." }, { "code": null, "e": 1576, "s": 1331, "text": "We can leverage PowerShell to test remote port connectivity without installing telnet and with the use of the Test-NetConnection command. This command is also very useful for other diagnostics but we are focusing here for the remote port check." }, { "code": null, "e": 1744, "s": 1576, "text": "To check if the remote port is open or not we can use the Test-NetConnection command and it requires -ComputerName parameter and -Port to check the remote port status." }, { "code": null, "e": 1800, "s": 1744, "text": "Test-NetConnection -ComputerName Test1-Win2k12 -Port 80" }, { "code": null, "e": 1974, "s": 1800, "text": "ComputerName : Test1-Win2k12\nRemoteAddress : 192.168.0.107\nRemotePort : 80\nInterfaceAlias : Ethernet0\nSourceAddress : 192.168.0.106\nTcpTestSucceeded : True" }, { "code": null, "e": 2022, "s": 1974, "text": "The above example will check Port number 80 con" }, { "code": null, "e": 2194, "s": 2022, "text": "ectivity on remote server Test1-Win2k12. You can see that the TcpTestSucceeded property is true so the port is open. One more example shown below is WInRM https port 5986." }, { "code": null, "e": 2252, "s": 2194, "text": "Test-NetConnection -ComputerName Test1-Win2k12 -Port 5986" }, { "code": null, "e": 2563, "s": 2252, "text": "WARNING: TCP connect to Test1-Win2k12:5986 failed\nComputerName : Test1-Win2k12\nRemoteAddress : 192.168.0.107 RemotePort : 5986\nInterfaceAlias : Ethernet0\nSourceAddress : 192.168.0.106\nPingSucceeded : True\nPingReplyDetails (RTT) : 0 ms\nTcpTestSucceeded : False" }, { "code": null, "e": 2730, "s": 2563, "text": "You can see that the WinRM SSL port is not open on the remote server and a warning message is displayed in the first line as well as in the TcpTestSucceeded property." } ]
JDBC - Data Types
The JDBC driver converts the Java data type to the appropriate JDBC type, before sending it to the database. It uses a default mapping for most data types. For example, a Java int is converted to an SQL INTEGER. Default mappings were created to provide consistency between drivers. The following table summarizes the default JDBC data type that the Java data type is converted to, when you call the setXXX() method of the PreparedStatement or CallableStatement object or the ResultSet.updateXXX() method. JDBC 3.0 has enhanced support for BLOB, CLOB, ARRAY, and REF data types. The ResultSet object now has updateBLOB(), updateCLOB(), updateArray(), and updateRef() methods that enable you to directly manipulate the respective data on the server. The setXXX() and updateXXX() methods enable you to convert specific Java types to specific JDBC data types. The methods, setObject() and updateObject(), enable you to map almost any Java type to a JDBC data type. ResultSet object provides corresponding getXXX() method for each data type to retrieve column value. Each method can be used with column name or by its ordinal position. The java.sql.Date class maps to the SQL DATE type, and the java.sql.Time and java.sql.Timestamp classes map to the SQL TIME and SQL TIMESTAMP data types, respectively. Following example shows how the Date and Time classes format the standard Java date and time values to match the SQL data type requirements. import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.util.*; public class SqlDateTime { public static void main(String[] args) { //Get standard date and time java.util.Date javaDate = new java.util.Date(); long javaTime = javaDate.getTime(); System.out.println("The Java Date is:" + javaDate.toString()); //Get and display SQL DATE java.sql.Date sqlDate = new java.sql.Date(javaTime); System.out.println("The SQL DATE is: " + sqlDate.toString()); //Get and display SQL TIME java.sql.Time sqlTime = new java.sql.Time(javaTime); System.out.println("The SQL TIME is: " + sqlTime.toString()); //Get and display SQL TIMESTAMP java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(javaTime); System.out.println("The SQL TIMESTAMP is: " + sqlTimestamp.toString()); }//end main }//end SqlDateTime Now let us compile the above example as follows − C:\>javac SqlDateTime.java C:\> When you run JDBCExample, it produces the following result − C:\>java SqlDateTime The Java Date is:Tue Aug 18 13:46:02 GMT+04:00 2009 The SQL DATE is: 2009-08-18 The SQL TIME is: 13:46:02 The SQL TIMESTAMP is: 2009-08-18 13:46:02.828 C:\> SQL's use of NULL values and Java's use of null are different concepts. So, to handle SQL NULL values in Java, there are three tactics you can use − Avoid using getXXX( ) methods that return primitive data types. Avoid using getXXX( ) methods that return primitive data types. Use wrapper classes for primitive data types, and use the ResultSet object's wasNull( ) method to test whether the wrapper class variable that received the value returned by the getXXX( ) method should be set to null. Use wrapper classes for primitive data types, and use the ResultSet object's wasNull( ) method to test whether the wrapper class variable that received the value returned by the getXXX( ) method should be set to null. Use primitive data types and the ResultSet object's wasNull( ) method to test whether the primitive variable that received the value returned by the getXXX( ) method should be set to an acceptable value that you've chosen to represent a NULL. Use primitive data types and the ResultSet object's wasNull( ) method to test whether the primitive variable that received the value returned by the getXXX( ) method should be set to an acceptable value that you've chosen to represent a NULL. Here is one example to handle a NULL value − Statement stmt = conn.createStatement( ); String sql = "SELECT id, first, last, age FROM Employees"; ResultSet rs = stmt.executeQuery(sql); int id = rs.getInt(1); if( rs.wasNull( ) ) { id = 0; } 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2444, "s": 2162, "text": "The JDBC driver converts the Java data type to the appropriate JDBC type, before sending it to the database. It uses a default mapping for most data types. For example, a Java int is converted to an SQL INTEGER. Default mappings were created to provide consistency between drivers." }, { "code": null, "e": 2667, "s": 2444, "text": "The following table summarizes the default JDBC data type that the Java data type is converted to, when you call the setXXX() method of the PreparedStatement or CallableStatement object or the ResultSet.updateXXX() method." }, { "code": null, "e": 2910, "s": 2667, "text": "JDBC 3.0 has enhanced support for BLOB, CLOB, ARRAY, and REF data types. The ResultSet object now has updateBLOB(), updateCLOB(), updateArray(), and updateRef() methods that enable you to directly manipulate the respective data on the server." }, { "code": null, "e": 3123, "s": 2910, "text": "The setXXX() and updateXXX() methods enable you to convert specific Java types to specific JDBC data types. The methods, setObject() and updateObject(), enable you to map almost any Java type to a JDBC data type." }, { "code": null, "e": 3293, "s": 3123, "text": "ResultSet object provides corresponding getXXX() method for each data type to retrieve column value. Each method can be used with column name or by its ordinal position." }, { "code": null, "e": 3461, "s": 3293, "text": "The java.sql.Date class maps to the SQL DATE type, and the java.sql.Time and java.sql.Timestamp classes map to the SQL TIME and SQL TIMESTAMP data types, respectively." }, { "code": null, "e": 3602, "s": 3461, "text": "Following example shows how the Date and Time classes format the standard Java date and time values to match the SQL data type requirements." }, { "code": null, "e": 4575, "s": 3602, "text": "import java.sql.Date;\nimport java.sql.Time;\nimport java.sql.Timestamp;\nimport java.util.*;\n\npublic class SqlDateTime {\n public static void main(String[] args) {\n //Get standard date and time\n java.util.Date javaDate = new java.util.Date();\n long javaTime = javaDate.getTime();\n System.out.println(\"The Java Date is:\" + \n javaDate.toString());\n\n //Get and display SQL DATE\n java.sql.Date sqlDate = new java.sql.Date(javaTime);\n System.out.println(\"The SQL DATE is: \" + \n sqlDate.toString());\n\n //Get and display SQL TIME\n java.sql.Time sqlTime = new java.sql.Time(javaTime);\n System.out.println(\"The SQL TIME is: \" + \n sqlTime.toString());\n //Get and display SQL TIMESTAMP\n java.sql.Timestamp sqlTimestamp =\n new java.sql.Timestamp(javaTime);\n System.out.println(\"The SQL TIMESTAMP is: \" + \n sqlTimestamp.toString());\n }//end main\n}//end SqlDateTime" }, { "code": null, "e": 4625, "s": 4575, "text": "Now let us compile the above example as follows −" }, { "code": null, "e": 4657, "s": 4625, "text": "C:\\>javac SqlDateTime.java\nC:\\>" }, { "code": null, "e": 4718, "s": 4657, "text": "When you run JDBCExample, it produces the following result −" }, { "code": null, "e": 4897, "s": 4718, "text": "C:\\>java SqlDateTime\nThe Java Date is:Tue Aug 18 13:46:02 GMT+04:00 2009\nThe SQL DATE is: 2009-08-18\nThe SQL TIME is: 13:46:02\nThe SQL TIMESTAMP is: 2009-08-18 13:46:02.828\nC:\\>\n" }, { "code": null, "e": 5046, "s": 4897, "text": "SQL's use of NULL values and Java's use of null are different concepts. So, to handle SQL NULL values in Java, there are three tactics you can use −" }, { "code": null, "e": 5110, "s": 5046, "text": "Avoid using getXXX( ) methods that return primitive data types." }, { "code": null, "e": 5174, "s": 5110, "text": "Avoid using getXXX( ) methods that return primitive data types." }, { "code": null, "e": 5392, "s": 5174, "text": "Use wrapper classes for primitive data types, and use the ResultSet object's wasNull( ) method to test whether the wrapper class variable that received the value\nreturned by the getXXX( ) method should be set to null." }, { "code": null, "e": 5610, "s": 5392, "text": "Use wrapper classes for primitive data types, and use the ResultSet object's wasNull( ) method to test whether the wrapper class variable that received the value\nreturned by the getXXX( ) method should be set to null." }, { "code": null, "e": 5853, "s": 5610, "text": "Use primitive data types and the ResultSet object's wasNull( ) method to test whether the primitive variable that received the value returned by the getXXX( )\nmethod should be set to an acceptable value that you've chosen to represent a NULL." }, { "code": null, "e": 6096, "s": 5853, "text": "Use primitive data types and the ResultSet object's wasNull( ) method to test whether the primitive variable that received the value returned by the getXXX( )\nmethod should be set to an acceptable value that you've chosen to represent a NULL." }, { "code": null, "e": 6141, "s": 6096, "text": "Here is one example to handle a NULL value −" }, { "code": null, "e": 6340, "s": 6141, "text": "Statement stmt = conn.createStatement( );\nString sql = \"SELECT id, first, last, age FROM Employees\";\nResultSet rs = stmt.executeQuery(sql);\n\nint id = rs.getInt(1);\nif( rs.wasNull( ) ) {\n id = 0;\n}" }, { "code": null, "e": 6373, "s": 6340, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 6389, "s": 6373, "text": " Malhar Lathkar" }, { "code": null, "e": 6422, "s": 6389, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 6438, "s": 6422, "text": " Malhar Lathkar" }, { "code": null, "e": 6473, "s": 6438, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6487, "s": 6473, "text": " Anadi Sharma" }, { "code": null, "e": 6521, "s": 6487, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 6535, "s": 6521, "text": " Tushar Kale" }, { "code": null, "e": 6572, "s": 6535, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 6587, "s": 6572, "text": " Monica Mittal" }, { "code": null, "e": 6620, "s": 6587, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 6639, "s": 6620, "text": " Arnab Chakraborty" }, { "code": null, "e": 6646, "s": 6639, "text": " Print" }, { "code": null, "e": 6657, "s": 6646, "text": " Add Notes" } ]
Fetching multiple MySQL rows based on a specific input within one of the table columns?
Let us first create a table − mysql> create table DemoTable1528 -> ( -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentName varchar(20), -> StudentSubject varchar(20) -> ); Query OK, 0 rows affected (0.53 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1528(StudentName,StudentSubject) values('Chris','MongoDB'); Query OK, 1 row affected (0.38 sec) mysql> insert into DemoTable1528(StudentName,StudentSubject) values('Bob','MySQL'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable1528(StudentName,StudentSubject) values('David','Java'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable1528(StudentName,StudentSubject) values('Carol','C'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1528(StudentName,StudentSubject) values('Sam','Java'); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable1528(StudentName,StudentSubject) values('Mike','Java'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable1528(StudentName,StudentSubject) values('Adam','MySQL'); Query OK, 1 row affected (0.13 sec) Display all records from the table using select statement − mysql> select * from DemoTable1528; This will produce the following output − +-----------+-------------+----------------+ | StudentId | StudentName | StudentSubject | +-----------+-------------+----------------+ | 1 | Chris | MongoDB | | 2 | Bob | MySQL | | 3 | David | Java | | 4 | Carol | C | | 5 | Sam | Java | | 6 | Mike | Java | | 7 | Adam | MySQL | +-----------+-------------+----------------+ 7 rows in set (0.00 sec) Following is the query to fetch multiple MySQL rows based on a specific input within one of the table columns. Here, our specific input is “Java” − mysql> select StudentId,StudentName,StudentSubject from DemoTable1528 where StudentSubject='Java'; This will produce the following output − +-----------+-------------+----------------+ | StudentId | StudentName | StudentSubject | +-----------+-------------+----------------+ | 3 | David | Java | | 5 | Sam | Java | | 6 | Mike | Java | +-----------+-------------+----------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table −" }, { "code": null, "e": 1301, "s": 1092, "text": "mysql> create table DemoTable1528\n -> (\n -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> StudentName varchar(20),\n -> StudentSubject varchar(20)\n -> );\nQuery OK, 0 rows affected (0.53 sec)" }, { "code": null, "e": 1357, "s": 1301, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 2200, "s": 1357, "text": "mysql> insert into DemoTable1528(StudentName,StudentSubject) values('Chris','MongoDB');\nQuery OK, 1 row affected (0.38 sec)\nmysql> insert into DemoTable1528(StudentName,StudentSubject) values('Bob','MySQL');\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable1528(StudentName,StudentSubject) values('David','Java');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable1528(StudentName,StudentSubject) values('Carol','C');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable1528(StudentName,StudentSubject) values('Sam','Java');\nQuery OK, 1 row affected (0.08 sec)\nmysql> insert into DemoTable1528(StudentName,StudentSubject) values('Mike','Java');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable1528(StudentName,StudentSubject) values('Adam','MySQL');\nQuery OK, 1 row affected (0.13 sec)" }, { "code": null, "e": 2260, "s": 2200, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2296, "s": 2260, "text": "mysql> select * from DemoTable1528;" }, { "code": null, "e": 2337, "s": 2296, "text": "This will produce the following output −" }, { "code": null, "e": 2857, "s": 2337, "text": "+-----------+-------------+----------------+\n| StudentId | StudentName | StudentSubject |\n+-----------+-------------+----------------+\n| 1 | Chris | MongoDB |\n| 2 | Bob | MySQL |\n| 3 | David | Java |\n| 4 | Carol | C |\n| 5 | Sam | Java |\n| 6 | Mike | Java |\n| 7 | Adam | MySQL |\n+-----------+-------------+----------------+\n7 rows in set (0.00 sec)" }, { "code": null, "e": 3005, "s": 2857, "text": "Following is the query to fetch multiple MySQL rows based on a specific input within one of the table columns. Here, our specific input is “Java” −" }, { "code": null, "e": 3104, "s": 3005, "text": "mysql> select StudentId,StudentName,StudentSubject from DemoTable1528 where StudentSubject='Java';" }, { "code": null, "e": 3145, "s": 3104, "text": "This will produce the following output −" }, { "code": null, "e": 3485, "s": 3145, "text": "+-----------+-------------+----------------+\n| StudentId | StudentName | StudentSubject |\n+-----------+-------------+----------------+\n| 3 | David | Java |\n| 5 | Sam | Java |\n| 6 | Mike | Java |\n+-----------+-------------+----------------+\n3 rows in set (0.00 sec)" } ]
5 Ways Julia Is Better Than Python | by Emmett Boudreau | Towards Data Science
Julia is a multi-paradigm, primarily functional programming language that was created for machine-learning and statistical programming. Python is another multi-paradigm programming language that is used for machine-learning, though generally Python is considered to be object-oriented. Julia, on the other hand, is more based on the functional paradigm. Though Julia certainly isn’t as popular as Python, there are some huge benefits to using Julia for Data Science that make it a better choice in a lot of situations that Python. It’s hard to talk about Julia without talking about speed. Julia prides itself on being very fast. Julia, unlike Python which is interpreted, is a compiled language that is primarily written in its own base. However, unlike other compiled languages like C, Julia is compiled at run-time, whereas traditional languages are compiled prior to execution. Julia, especially when written well, can be as fast and sometimes even faster than C. Julia uses the Just In Time (JIT) compiler and compiles incredibly fast, though it compiles more like an interpreted language than a traditional low-level compiled language like C, or Fortran. You might have noticed that I said Python was versatile as an advantage to Julia, and this is true — there are a lot of things that can be done with Python that you just can’t do with Julia. Of course, this is only natively speaking, because the versatility we’re talking about now is versatility in language. Julia code is universally executable in R, Latex, Python, and C. This means that typical Data Science projects have the potential to be written once, and compiled in Julia natively from another language in a wrapper, or just by sending strings. PyCall and RCall are also pretty big deals. Given that a serious downside to Julia is in fact the packages, it’s really convenient to be able to call on Python and R whenever you need them. PyCall is very well implemented into Julia, and is definitely sincerely well-done, and very usable. Julia is a very uniquely typed language and has its own quirks and features, but among one of the coolest features is Julia’s multiple dispatch. First and foremost, Julia’s multiple dispatch is fast. On top of that, using Julia’s polymorphic dispatch allows for applying function definitions as properties of a struct. This, of course, makes inheritance viable inside of Julia. Not only that, but using Julia’s multiple dispatch makes a function extendable. This is a great benefit for package extensions, as whenever a method is explicitly imported, it can be changed by a user. It would be easy to explicitly import your method and extend it to route structs to a new function. Unlike Python, Julia was made with the intention of being used in statistics and machine-learning. Python was created in the early 90s as an easy object-oriented language, though it has changed a lot since then. Given Python’s history, and the wide variety of uses for Python since it’s so popular, using a language that was made specifically for high-level statistical work could show a lot of benefits. One way I see this benefiting Julia over Python is in linear algebra. Vanilla Python can chug through linear algebra, but vanilla Julia can fly through linear algebra. This is because of course Python was never meant to support all of the matrices and equations that go along with machine-learning. By no means at all is Python bad, especially with NumPy, but in terms of a no-package experience, Julia feels a lot more catered towards these sorts of mathematics. Julia’s operand system is a lot closer to that of R than Python’s, and that’s a big benefit. Most linear algebra is quicker and easier to do. Let’s show a dot-product equation, just to illustrate this further: Python -> y = np.dot(array1,array2)R -> y <- array1 * array2Julia -> y = array1 .* array2 I’ll be the first to say it, Julia’s Pkg package manager is an entire world above Python’s Pip package manager. Pkg comes loaded with its own REPL and Julia package from which you can build, add, remove, and instantiate packages. This is especially convenient because of Pkg’s tie-in with Git. Updating is easy, adding packages is always easy, and overall Pkg is a pleasure to use over Python’s Pip any day. It doesn’t really matter which language you use, be it R, Julia, Python, or Scala. It is important to note, however that every language has its downsides, and no language is ever going to be the “ perfect language.” This is especially true if you are versatile in your programming, from machine-learning to GUIs to APIs. With that being said, Julia is certainly one of my favorites in my arsenal, as well as Python. Python has better packages, and with that typically if the project is small enough, I’ll veer towards Python, but for data-sets with millions of observations, it can be hard to even get that kind of data read in Python. Overall, I look forward into the future of Julia. Julia’s a lot of fun to write, and will likely become even more viable for Data Science in the future.
[ { "code": null, "e": 703, "s": 172, "text": "Julia is a multi-paradigm, primarily functional programming language that was created for machine-learning and statistical programming. Python is another multi-paradigm programming language that is used for machine-learning, though generally Python is considered to be object-oriented. Julia, on the other hand, is more based on the functional paradigm. Though Julia certainly isn’t as popular as Python, there are some huge benefits to using Julia for Data Science that make it a better choice in a lot of situations that Python." }, { "code": null, "e": 1333, "s": 703, "text": "It’s hard to talk about Julia without talking about speed. Julia prides itself on being very fast. Julia, unlike Python which is interpreted, is a compiled language that is primarily written in its own base. However, unlike other compiled languages like C, Julia is compiled at run-time, whereas traditional languages are compiled prior to execution. Julia, especially when written well, can be as fast and sometimes even faster than C. Julia uses the Just In Time (JIT) compiler and compiles incredibly fast, though it compiles more like an interpreted language than a traditional low-level compiled language like C, or Fortran." }, { "code": null, "e": 1888, "s": 1333, "text": "You might have noticed that I said Python was versatile as an advantage to Julia, and this is true — there are a lot of things that can be done with Python that you just can’t do with Julia. Of course, this is only natively speaking, because the versatility we’re talking about now is versatility in language. Julia code is universally executable in R, Latex, Python, and C. This means that typical Data Science projects have the potential to be written once, and compiled in Julia natively from another language in a wrapper, or just by sending strings." }, { "code": null, "e": 2178, "s": 1888, "text": "PyCall and RCall are also pretty big deals. Given that a serious downside to Julia is in fact the packages, it’s really convenient to be able to call on Python and R whenever you need them. PyCall is very well implemented into Julia, and is definitely sincerely well-done, and very usable." }, { "code": null, "e": 2556, "s": 2178, "text": "Julia is a very uniquely typed language and has its own quirks and features, but among one of the coolest features is Julia’s multiple dispatch. First and foremost, Julia’s multiple dispatch is fast. On top of that, using Julia’s polymorphic dispatch allows for applying function definitions as properties of a struct. This, of course, makes inheritance viable inside of Julia." }, { "code": null, "e": 2858, "s": 2556, "text": "Not only that, but using Julia’s multiple dispatch makes a function extendable. This is a great benefit for package extensions, as whenever a method is explicitly imported, it can be changed by a user. It would be easy to explicitly import your method and extend it to route structs to a new function." }, { "code": null, "e": 3263, "s": 2858, "text": "Unlike Python, Julia was made with the intention of being used in statistics and machine-learning. Python was created in the early 90s as an easy object-oriented language, though it has changed a lot since then. Given Python’s history, and the wide variety of uses for Python since it’s so popular, using a language that was made specifically for high-level statistical work could show a lot of benefits." }, { "code": null, "e": 3937, "s": 3263, "text": "One way I see this benefiting Julia over Python is in linear algebra. Vanilla Python can chug through linear algebra, but vanilla Julia can fly through linear algebra. This is because of course Python was never meant to support all of the matrices and equations that go along with machine-learning. By no means at all is Python bad, especially with NumPy, but in terms of a no-package experience, Julia feels a lot more catered towards these sorts of mathematics. Julia’s operand system is a lot closer to that of R than Python’s, and that’s a big benefit. Most linear algebra is quicker and easier to do. Let’s show a dot-product equation, just to illustrate this further:" }, { "code": null, "e": 4027, "s": 3937, "text": "Python -> y = np.dot(array1,array2)R -> y <- array1 * array2Julia -> y = array1 .* array2" }, { "code": null, "e": 4435, "s": 4027, "text": "I’ll be the first to say it, Julia’s Pkg package manager is an entire world above Python’s Pip package manager. Pkg comes loaded with its own REPL and Julia package from which you can build, add, remove, and instantiate packages. This is especially convenient because of Pkg’s tie-in with Git. Updating is easy, adding packages is always easy, and overall Pkg is a pleasure to use over Python’s Pip any day." }, { "code": null, "e": 5071, "s": 4435, "text": "It doesn’t really matter which language you use, be it R, Julia, Python, or Scala. It is important to note, however that every language has its downsides, and no language is ever going to be the “ perfect language.” This is especially true if you are versatile in your programming, from machine-learning to GUIs to APIs. With that being said, Julia is certainly one of my favorites in my arsenal, as well as Python. Python has better packages, and with that typically if the project is small enough, I’ll veer towards Python, but for data-sets with millions of observations, it can be hard to even get that kind of data read in Python." } ]
How to return 2 values from a Java method
A method can give multiple values if we pass an object to the method and then modifies its values. See the example below − public class Tester { public static void main(String[] args) { Model model = new Model(); model.data1 = 1; model.data2 = 2; System.out.println(model.data1 + ", " + model.data2); changeValues(model); System.out.println(model.data1 + ", " + model.data2); } public static void changeValues(Model model) { model.data1 = 100; model.data2 = 200; } } class Model { int data1; int data2; } 1, 2 100, 200
[ { "code": null, "e": 1185, "s": 1062, "text": "A method can give multiple values if we pass an object to the method and then modifies its values. See the example below −" }, { "code": null, "e": 1633, "s": 1185, "text": "public class Tester {\n public static void main(String[] args) {\n Model model = new Model();\n model.data1 = 1;\n model.data2 = 2;\n System.out.println(model.data1 + \", \" + model.data2);\n changeValues(model);\n System.out.println(model.data1 + \", \" + model.data2);\n }\n public static void changeValues(Model model) {\n model.data1 = 100;\n model.data2 = 200;\n }\n}\nclass Model {\n int data1;\n int data2;\n}" }, { "code": null, "e": 1647, "s": 1633, "text": "1, 2\n100, 200" } ]
Building a Road Sign Classifier in Keras | by Nushaine Ferdinand | Towards Data Science
There are so many different types of traffic signs out there, each with different colours, shapes and sizes. Sometimes, there are two signs may have a similar colour, shape and size, but have 2 totally different meanings. How on earth would we ever be able to program a computer to correctly classify a traffic sign on the road? We can do this by creating our very own CNN to classify each different road sign for us. In this tutorial, we’ll use the GTSRB dataset, a dataset with over 50,000 images of German Traffic Signs. There are 43 classes (43 different types of signs that we’re going to have to classify). Click the link below to download the dataset. www.kaggle.com When you open the dataset in your computer, there should be 6 paths inside your dataset (3 folders and 3 spreadsheets), like below. The meta folder should have 43 different images (ranging from 0–42). The test folder is just a bunch of test images. The train folder should have 43 folders (again, ranging from 0–42), each containing images from its respective class. Now that you have the dataset, and that the dataset contains all the required data, let's begin coding! This tutorial will be divided into 3 parts: loading the data, building the model and training the model. Just before starting though, make sure you have Jupiter notebooks installed on your computer because this tutorial is done on Jupiter notebooks (this can be done by installing Anaconda. Click the link below to install Anaconda.) www.anaconda.com Okay, so now that we’ve installed Jupyter Notebooks and we have the dataset installed, we’re ready to begin coding (Yesss)! First things first, let’s import the necessary libraries and modules that are required for us to load the data. import pandas as pdimport numpy as npimport osimport cv2import matplotlib.pyplot as pltimport randomimport tensorflow as tffrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import BatchNormalizationfrom tensorflow.keras.layers import Conv2Dfrom tensorflow.keras.layers import MaxPooling2Dfrom tensorflow.keras.layers import Activationfrom tensorflow.keras.layers import Flattenfrom tensorflow.keras.layers import Dropoutfrom tensorflow.keras.layers import Densefrom tensorflow.keras.utils import to_categoricalfrom tensorflow.keras.preprocessing.image import ImageDataGeneratorfrom tensorflow.keras.optimizers import Adam The first bunch is libraries needed to create the load_data function. The second bunch is the stuff that we need to build our model. You can import each bunch in different kernels if you like, but it really doesn’t matter. To begin loading the data, let's create a variable that will represent where our dataset is stored. Make sure you put the letter r in front of your path string so that your computer knows that it’s supposed to read the string. Note: My path will be different to yours. To get the path to your dataset, you should go to the folder where your dataset is located, click once on your dataset (don’t open it, just make that you clicked on it), then click the button copy path which is on the top left of your screen Then paste the path into your jupyter notebook (like I did below). Make sure that you put an r in front of your string so that the pc knows that it's supposed to read the file. data_path = r"D:\users\new owner\Desktop\Christmas Break\gtsrb-german-traffic-sign" Next, let’s define the function that will load our data into the notebook from the computer. def load_data(dataset): images = [] classes = [] rows = pd.read_csv(dataset) rows = rows.sample(frac=1).reset_index(drop=True) Our load_data function takes 1 parameter, which is the path to our dataset. After that, we define two lists, images and classes. The images list will store the image arrays and the class list will store the class number for each image. In the next line, we’re going to open the CSV file. And the final line randomizes our data which will prevent the model from overfitting to specific classes. for i, row in rows.iterrows(): img_class = row["ClassId"] img_path = row["Path"] image = os.path.join(data, img_path) The for loop cycles through all the rows. The .iterrows() function returns an index for each row (The first row is 0, then 1, 2, 3, .... until the final row). We take the image’s class from the ClassId column and the image data from the Path column. Finally, we take the image’s path we got from the spreadsheet and we join it with the path to our dataset to get the full path to the image image = cv2.imread(image) image_rs = cv2.resize(image, (img_size, img_size), 3) R, G, B = cv2.split(image_rs) img_r = cv2.equalizeHist(R) img_g = cv2.equalizeHist(G) img_b = cv2.equalizeHist(B) new_image = cv2.merge((img_r, img_g, img_b)) First, we read the image array (convert it from an array of numbers into an actual picture, so that we can resize it). Then we resize the image dimensions into 32 X 32 X 3, (it makes training the model lot faster if all the images are the same dimensions). The next 5 lines are performing histogram equalization, which is an equalization technique which improves the contrast in images. If you’re interested in learning more about histogram equalization, click here Note: This code is still in the for loop from the previous code block if i % 500 == 0: print(f"loaded: {i}") images.append(new_image) classes.append(img_class) X = np.array(images) y = np.array(images) return (X, y) Still in the for loop, we’re going to write an if statement that prints how many images we have loaded in. This statement will print every 500 images, just so that we know that our function is actually working. Next, we’ll add the image that we just extracted from the dataset into the lists that we defined before. Now outside of the for loop, we’re going to redefine the images and classes lists as Numpy arrays. This is so that we can perform operations on the arrays later on. Finally, when we have finished extracting all the images from the dataset, we will return both the images and classes list in a tuple. Hyperparameters are parameters that a neural network cannot learn. They must be explicitly defined by the programmer before training epochs = 20learning_rate = 0.001batch_size = 64 Our first hyperparameter (I’ll use the abbreviation HYP), epochs, tells the neural network how many times it should complete a full training process. In this case, the neural network will train itself 20 times (go over all 50,000 images and validate itself with 12,000 test images 20 times)! The learning rate tells us how much the weights will be updated each time. The learning rate is often between 0 and 1. The batch size tells us how much images the neural network will cycle through at once. It would be impossible for the computer to cycle through all 50,000 images at one go, it would crash. That’s why we have the batch size. train_data = r"D:\users\new owner\Desktop\TKS\Christmas Break\gtsrb-german-traffic-sign\Train.csv"test_data = r"D:\users\new owner\Desktop\TKS\Christmas Break\gtsrb-german-traffic-sign\Test.csv"(trainX, trainY) = load_data(train_data)(testX, testY) = load_data(test_data) First, we’ll define the paths to our test and train datasets, using the same method that we used to define the path to the dataset before Now, we’re going to load both the training and test data in using our load_data function. We’re going to store the images list in the variable trainX, and store the classes list in the trainY variable, and do the same for testX, and testY. Note: This step may take a while, depending on the specs of your computer. Mine took 10–15 mins. print("UPDATE: Normalizing data")trainX = train_X.astype("float32") / 255.0testX = test_X.astype("float32") / 255.0print("UPDATE: One-Hot Encoding data")num_labels = len(np.unique(train_y))trainY = to_categorical(trainY, num_labels)testY = to_categorical(testY, num_labels)class_totals = trainY.sum(axis=0)class_weight = class_totals.max() / class_totals Now we’re going to normalize the data. This allows us to scale down the values in the data to be between 0 and 1, from before which was between 0 and 255. Next, we’re going to one-hot encode the test and train labels. In essence, one-hot encoding is a way of representing each class with a binary value (1s and 0s) instead of a categorical value (“red” or “blue”). It does this by creating a diagonal matrix where the principal diagonal is ones, and the rest of the values are 0. The matrix has dimensions equal to the number of classes there are (if there are 20 classes, the matrix is a 20X20 matrix). In the matrix, each row represents a different class, so each class has its unique code. If you want to learn more about one-hot encoding, here's a great resource And finally, we’re going to account for inequalities in the classes by assigning a weight to each class. Now it’s time to build the actual CNN architecture. First, let's import the necessary libraries and modules: import tensorflow as tffrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import BatchNormalizationfrom tensorflow.keras.layers import Conv2Dfrom tensorflow.keras.layers import MaxPooling2Dfrom tensorflow.keras.layers import Activationfrom tensorflow.keras.layers import Flattenfrom tensorflow.keras.layers import Dropoutfrom tensorflow.keras.layers import Dense Here, we import Tensorflow, which is a framework in Python that allows us to build our ML models, and from Tensorflow we import Keras, which simplifies our models even more! After that, we’re importing a bunch of different layers that we need to build the model. If you want to learn more about exactly what each of these layers does, skim through my article on CNN’s. towardsdatascience.com Before we jump into building the model, I want to point out that there is no “proper” way to build the model. There is no fixed amount of layers, dimensions or types of layers that your CNN has to have. You should play around with it to see which one gives you the best accuracy. I’ll give you the one that gave me the best accuracy. class RoadSignClassifier: def createCNN(width, height, depth, classes): model = Sequential() inputShape = (height, width, depth) This time, we’re going to create a class, called RoadSignClassifier (any name should do). Within the class, there is one function, createCNN, which takes 4 parameters. We’ll be using the Sequential API, which allows us to create the model layer-by-layer. model.add(Conv2D(8, (5, 5), input_shape=inputShape, activation="relu")) model.add(MaxPooling2D(pool_size=(2, 2))) This is our first convolutional layer. We define the dimension of our output (8 X 8 X 3), and we use the activation function “relu”. We continue with this Conv2D — MaxPooling2D sequence for 2 more times. model.add(Conv2D(16, (3, 3), activation="relu")) model.add(BatchNormalization()) model.add(Conv2D(16, (3, 3), activation="relu")) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(32, (3, 3), padding="same", activation="relu")) model.add(BatchNormalization()) model.add(Conv2D(32, (3, 3), padding="same", activation="relu")) model.add(BatchNormalization()) The same thing as last time, except this time we include batch normalization. It just speeds up training. model.add(Flatten()) model.add(Dropout(0.5)) model.add(Dense(512, activation="relu")) model.add(Dense(classes, activation="softmax")) return model Now we flatten the output from the final convolutional layer, perform a dropout and enter into our final dense layer. The output in the final dense layer is equal to the number of classes that we have. That’s basically it for building the model. Time to move on ahead! Now its time for the fun part (actually this is the part where we have to wait 30 mins for the model to train lol). Its time to train our model to recognize road signs! data_aug = ImageDataGenerator(rotation_range=10,zoom_range=0.15,width_shift_range=0.1,height_shift_range=0.1,shear_range=0.15,horizontal_flip=False,vertical_flip=False) Here we’re performing data augmentation. Data augmentation creates modified versions of the images in our dataset. It allows us to add images to our dataset without us having to collect new ones. In Keras, we use the ImageDataGenerator module to perform data augmentation. model = RoadSignClassifier.createCNN(width=32, height=32, depth=3, classes=43)optimizer = Adam(lr=learning_rate, decay=learning_rate / (epochs)) The first line defines our model. We use the class RoadSignClassifier, and define the width, height, depth and the number of classes. In the second line, we create our optimizer, which in this case is the Adam optimizer. We’ll initialize the learning rate as what we had set it to be previously (0.001), we’ll also set the learning rate to decrease every epoch (that’s the decay parameter, it reduces overfitting). model.compile(optimizer=optimizer, loss="categorical_crossentropy", metrics=["accuracy"])fit = model.fit_generator( data_aug.flow(train_X, trainY, batch_size=batch_size), epochs=epochs, validation_data=(test_X, testY), class_weight=class_weight, verbose=1) The first line compiles the model. We create the model and define the optimizer, the loss, and the number of epochs. In the second line, we fit out model (this is where the training takes place). Our data_aug.flow method applies the augmentations to our images that we defined before. The number of epochs is set to 20. For the validation data, we use our test data. The verbose is set to 1, which just means that Keras will show the progress of the model being trained as you go along. Now, you’ve finished writing the code for your model. Its time to run it. Once you’ve run it for a bit, you should get an output like this: Then after you’ve finished all you’re epochs, you should get an output similar to this: Your accuracy should be at least 90%. If not, go an play around with the model architecture. Eventually, your model will return an accuracy of around 90% or more. Now you finished your classifier! It feels good, right! Well, that’s it for today. Hopefully, you learned something in this article! If you’re stuck on something, you can e-mail me at nushainef@gmail.com, and I’ll do my best to help you. Good luck on your ML journey. If this tutorial didn’t appeal to you, or you’re just looking for another tutorial, here is another great tutorial that I find really informative!
[ { "code": null, "e": 590, "s": 172, "text": "There are so many different types of traffic signs out there, each with different colours, shapes and sizes. Sometimes, there are two signs may have a similar colour, shape and size, but have 2 totally different meanings. How on earth would we ever be able to program a computer to correctly classify a traffic sign on the road? We can do this by creating our very own CNN to classify each different road sign for us." }, { "code": null, "e": 831, "s": 590, "text": "In this tutorial, we’ll use the GTSRB dataset, a dataset with over 50,000 images of German Traffic Signs. There are 43 classes (43 different types of signs that we’re going to have to classify). Click the link below to download the dataset." }, { "code": null, "e": 846, "s": 831, "text": "www.kaggle.com" }, { "code": null, "e": 978, "s": 846, "text": "When you open the dataset in your computer, there should be 6 paths inside your dataset (3 folders and 3 spreadsheets), like below." }, { "code": null, "e": 1213, "s": 978, "text": "The meta folder should have 43 different images (ranging from 0–42). The test folder is just a bunch of test images. The train folder should have 43 folders (again, ranging from 0–42), each containing images from its respective class." }, { "code": null, "e": 1317, "s": 1213, "text": "Now that you have the dataset, and that the dataset contains all the required data, let's begin coding!" }, { "code": null, "e": 1422, "s": 1317, "text": "This tutorial will be divided into 3 parts: loading the data, building the model and training the model." }, { "code": null, "e": 1651, "s": 1422, "text": "Just before starting though, make sure you have Jupiter notebooks installed on your computer because this tutorial is done on Jupiter notebooks (this can be done by installing Anaconda. Click the link below to install Anaconda.)" }, { "code": null, "e": 1668, "s": 1651, "text": "www.anaconda.com" }, { "code": null, "e": 1792, "s": 1668, "text": "Okay, so now that we’ve installed Jupyter Notebooks and we have the dataset installed, we’re ready to begin coding (Yesss)!" }, { "code": null, "e": 1904, "s": 1792, "text": "First things first, let’s import the necessary libraries and modules that are required for us to load the data." }, { "code": null, "e": 2551, "s": 1904, "text": "import pandas as pdimport numpy as npimport osimport cv2import matplotlib.pyplot as pltimport randomimport tensorflow as tffrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import BatchNormalizationfrom tensorflow.keras.layers import Conv2Dfrom tensorflow.keras.layers import MaxPooling2Dfrom tensorflow.keras.layers import Activationfrom tensorflow.keras.layers import Flattenfrom tensorflow.keras.layers import Dropoutfrom tensorflow.keras.layers import Densefrom tensorflow.keras.utils import to_categoricalfrom tensorflow.keras.preprocessing.image import ImageDataGeneratorfrom tensorflow.keras.optimizers import Adam" }, { "code": null, "e": 2774, "s": 2551, "text": "The first bunch is libraries needed to create the load_data function. The second bunch is the stuff that we need to build our model. You can import each bunch in different kernels if you like, but it really doesn’t matter." }, { "code": null, "e": 3001, "s": 2774, "text": "To begin loading the data, let's create a variable that will represent where our dataset is stored. Make sure you put the letter r in front of your path string so that your computer knows that it’s supposed to read the string." }, { "code": null, "e": 3285, "s": 3001, "text": "Note: My path will be different to yours. To get the path to your dataset, you should go to the folder where your dataset is located, click once on your dataset (don’t open it, just make that you clicked on it), then click the button copy path which is on the top left of your screen" }, { "code": null, "e": 3462, "s": 3285, "text": "Then paste the path into your jupyter notebook (like I did below). Make sure that you put an r in front of your string so that the pc knows that it's supposed to read the file." }, { "code": null, "e": 3546, "s": 3462, "text": "data_path = r\"D:\\users\\new owner\\Desktop\\Christmas Break\\gtsrb-german-traffic-sign\"" }, { "code": null, "e": 3639, "s": 3546, "text": "Next, let’s define the function that will load our data into the notebook from the computer." }, { "code": null, "e": 3778, "s": 3639, "text": "def load_data(dataset): images = [] classes = [] rows = pd.read_csv(dataset) rows = rows.sample(frac=1).reset_index(drop=True)" }, { "code": null, "e": 4014, "s": 3778, "text": "Our load_data function takes 1 parameter, which is the path to our dataset. After that, we define two lists, images and classes. The images list will store the image arrays and the class list will store the class number for each image." }, { "code": null, "e": 4066, "s": 4014, "text": "In the next line, we’re going to open the CSV file." }, { "code": null, "e": 4172, "s": 4066, "text": "And the final line randomizes our data which will prevent the model from overfitting to specific classes." }, { "code": null, "e": 4315, "s": 4172, "text": " for i, row in rows.iterrows(): img_class = row[\"ClassId\"] img_path = row[\"Path\"] image = os.path.join(data, img_path)" }, { "code": null, "e": 4474, "s": 4315, "text": "The for loop cycles through all the rows. The .iterrows() function returns an index for each row (The first row is 0, then 1, 2, 3, .... until the final row)." }, { "code": null, "e": 4565, "s": 4474, "text": "We take the image’s class from the ClassId column and the image data from the Path column." }, { "code": null, "e": 4705, "s": 4565, "text": "Finally, we take the image’s path we got from the spreadsheet and we join it with the path to our dataset to get the full path to the image" }, { "code": null, "e": 4994, "s": 4705, "text": " image = cv2.imread(image) image_rs = cv2.resize(image, (img_size, img_size), 3) R, G, B = cv2.split(image_rs) img_r = cv2.equalizeHist(R) img_g = cv2.equalizeHist(G) img_b = cv2.equalizeHist(B) new_image = cv2.merge((img_r, img_g, img_b))" }, { "code": null, "e": 5251, "s": 4994, "text": "First, we read the image array (convert it from an array of numbers into an actual picture, so that we can resize it). Then we resize the image dimensions into 32 X 32 X 3, (it makes training the model lot faster if all the images are the same dimensions)." }, { "code": null, "e": 5460, "s": 5251, "text": "The next 5 lines are performing histogram equalization, which is an equalization technique which improves the contrast in images. If you’re interested in learning more about histogram equalization, click here" }, { "code": null, "e": 5530, "s": 5460, "text": "Note: This code is still in the for loop from the previous code block" }, { "code": null, "e": 5722, "s": 5530, "text": " if i % 500 == 0: print(f\"loaded: {i}\") images.append(new_image) classes.append(img_class) X = np.array(images) y = np.array(images) return (X, y)" }, { "code": null, "e": 5933, "s": 5722, "text": "Still in the for loop, we’re going to write an if statement that prints how many images we have loaded in. This statement will print every 500 images, just so that we know that our function is actually working." }, { "code": null, "e": 6038, "s": 5933, "text": "Next, we’ll add the image that we just extracted from the dataset into the lists that we defined before." }, { "code": null, "e": 6203, "s": 6038, "text": "Now outside of the for loop, we’re going to redefine the images and classes lists as Numpy arrays. This is so that we can perform operations on the arrays later on." }, { "code": null, "e": 6338, "s": 6203, "text": "Finally, when we have finished extracting all the images from the dataset, we will return both the images and classes list in a tuple." }, { "code": null, "e": 6471, "s": 6338, "text": "Hyperparameters are parameters that a neural network cannot learn. They must be explicitly defined by the programmer before training" }, { "code": null, "e": 6519, "s": 6471, "text": "epochs = 20learning_rate = 0.001batch_size = 64" }, { "code": null, "e": 6811, "s": 6519, "text": "Our first hyperparameter (I’ll use the abbreviation HYP), epochs, tells the neural network how many times it should complete a full training process. In this case, the neural network will train itself 20 times (go over all 50,000 images and validate itself with 12,000 test images 20 times)!" }, { "code": null, "e": 6930, "s": 6811, "text": "The learning rate tells us how much the weights will be updated each time. The learning rate is often between 0 and 1." }, { "code": null, "e": 7154, "s": 6930, "text": "The batch size tells us how much images the neural network will cycle through at once. It would be impossible for the computer to cycle through all 50,000 images at one go, it would crash. That’s why we have the batch size." }, { "code": null, "e": 7426, "s": 7154, "text": "train_data = r\"D:\\users\\new owner\\Desktop\\TKS\\Christmas Break\\gtsrb-german-traffic-sign\\Train.csv\"test_data = r\"D:\\users\\new owner\\Desktop\\TKS\\Christmas Break\\gtsrb-german-traffic-sign\\Test.csv\"(trainX, trainY) = load_data(train_data)(testX, testY) = load_data(test_data)" }, { "code": null, "e": 7564, "s": 7426, "text": "First, we’ll define the paths to our test and train datasets, using the same method that we used to define the path to the dataset before" }, { "code": null, "e": 7654, "s": 7564, "text": "Now, we’re going to load both the training and test data in using our load_data function." }, { "code": null, "e": 7804, "s": 7654, "text": "We’re going to store the images list in the variable trainX, and store the classes list in the trainY variable, and do the same for testX, and testY." }, { "code": null, "e": 7901, "s": 7804, "text": "Note: This step may take a while, depending on the specs of your computer. Mine took 10–15 mins." }, { "code": null, "e": 8256, "s": 7901, "text": "print(\"UPDATE: Normalizing data\")trainX = train_X.astype(\"float32\") / 255.0testX = test_X.astype(\"float32\") / 255.0print(\"UPDATE: One-Hot Encoding data\")num_labels = len(np.unique(train_y))trainY = to_categorical(trainY, num_labels)testY = to_categorical(testY, num_labels)class_totals = trainY.sum(axis=0)class_weight = class_totals.max() / class_totals" }, { "code": null, "e": 8411, "s": 8256, "text": "Now we’re going to normalize the data. This allows us to scale down the values in the data to be between 0 and 1, from before which was between 0 and 255." }, { "code": null, "e": 9023, "s": 8411, "text": "Next, we’re going to one-hot encode the test and train labels. In essence, one-hot encoding is a way of representing each class with a binary value (1s and 0s) instead of a categorical value (“red” or “blue”). It does this by creating a diagonal matrix where the principal diagonal is ones, and the rest of the values are 0. The matrix has dimensions equal to the number of classes there are (if there are 20 classes, the matrix is a 20X20 matrix). In the matrix, each row represents a different class, so each class has its unique code. If you want to learn more about one-hot encoding, here's a great resource" }, { "code": null, "e": 9128, "s": 9023, "text": "And finally, we’re going to account for inequalities in the classes by assigning a weight to each class." }, { "code": null, "e": 9237, "s": 9128, "text": "Now it’s time to build the actual CNN architecture. First, let's import the necessary libraries and modules:" }, { "code": null, "e": 9624, "s": 9237, "text": "import tensorflow as tffrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import BatchNormalizationfrom tensorflow.keras.layers import Conv2Dfrom tensorflow.keras.layers import MaxPooling2Dfrom tensorflow.keras.layers import Activationfrom tensorflow.keras.layers import Flattenfrom tensorflow.keras.layers import Dropoutfrom tensorflow.keras.layers import Dense" }, { "code": null, "e": 9993, "s": 9624, "text": "Here, we import Tensorflow, which is a framework in Python that allows us to build our ML models, and from Tensorflow we import Keras, which simplifies our models even more! After that, we’re importing a bunch of different layers that we need to build the model. If you want to learn more about exactly what each of these layers does, skim through my article on CNN’s." }, { "code": null, "e": 10016, "s": 9993, "text": "towardsdatascience.com" }, { "code": null, "e": 10350, "s": 10016, "text": "Before we jump into building the model, I want to point out that there is no “proper” way to build the model. There is no fixed amount of layers, dimensions or types of layers that your CNN has to have. You should play around with it to see which one gives you the best accuracy. I’ll give you the one that gave me the best accuracy." }, { "code": null, "e": 10496, "s": 10350, "text": "class RoadSignClassifier: def createCNN(width, height, depth, classes): model = Sequential() inputShape = (height, width, depth)" }, { "code": null, "e": 10751, "s": 10496, "text": "This time, we’re going to create a class, called RoadSignClassifier (any name should do). Within the class, there is one function, createCNN, which takes 4 parameters. We’ll be using the Sequential API, which allows us to create the model layer-by-layer." }, { "code": null, "e": 10885, "s": 10751, "text": " model.add(Conv2D(8, (5, 5), input_shape=inputShape, activation=\"relu\")) model.add(MaxPooling2D(pool_size=(2, 2)))" }, { "code": null, "e": 11089, "s": 10885, "text": "This is our first convolutional layer. We define the dimension of our output (8 X 8 X 3), and we use the activation function “relu”. We continue with this Conv2D — MaxPooling2D sequence for 2 more times." }, { "code": null, "e": 11552, "s": 11089, "text": " model.add(Conv2D(16, (3, 3), activation=\"relu\")) model.add(BatchNormalization()) model.add(Conv2D(16, (3, 3), activation=\"relu\")) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(32, (3, 3), padding=\"same\", activation=\"relu\")) model.add(BatchNormalization()) model.add(Conv2D(32, (3, 3), padding=\"same\", activation=\"relu\")) model.add(BatchNormalization())" }, { "code": null, "e": 11658, "s": 11552, "text": "The same thing as last time, except this time we include batch normalization. It just speeds up training." }, { "code": null, "e": 11841, "s": 11658, "text": " model.add(Flatten()) model.add(Dropout(0.5)) model.add(Dense(512, activation=\"relu\")) model.add(Dense(classes, activation=\"softmax\")) return model" }, { "code": null, "e": 12043, "s": 11841, "text": "Now we flatten the output from the final convolutional layer, perform a dropout and enter into our final dense layer. The output in the final dense layer is equal to the number of classes that we have." }, { "code": null, "e": 12110, "s": 12043, "text": "That’s basically it for building the model. Time to move on ahead!" }, { "code": null, "e": 12279, "s": 12110, "text": "Now its time for the fun part (actually this is the part where we have to wait 30 mins for the model to train lol). Its time to train our model to recognize road signs!" }, { "code": null, "e": 12448, "s": 12279, "text": "data_aug = ImageDataGenerator(rotation_range=10,zoom_range=0.15,width_shift_range=0.1,height_shift_range=0.1,shear_range=0.15,horizontal_flip=False,vertical_flip=False)" }, { "code": null, "e": 12721, "s": 12448, "text": "Here we’re performing data augmentation. Data augmentation creates modified versions of the images in our dataset. It allows us to add images to our dataset without us having to collect new ones. In Keras, we use the ImageDataGenerator module to perform data augmentation." }, { "code": null, "e": 12866, "s": 12721, "text": "model = RoadSignClassifier.createCNN(width=32, height=32, depth=3, classes=43)optimizer = Adam(lr=learning_rate, decay=learning_rate / (epochs))" }, { "code": null, "e": 13000, "s": 12866, "text": "The first line defines our model. We use the class RoadSignClassifier, and define the width, height, depth and the number of classes." }, { "code": null, "e": 13281, "s": 13000, "text": "In the second line, we create our optimizer, which in this case is the Adam optimizer. We’ll initialize the learning rate as what we had set it to be previously (0.001), we’ll also set the learning rate to decrease every epoch (that’s the decay parameter, it reduces overfitting)." }, { "code": null, "e": 13554, "s": 13281, "text": "model.compile(optimizer=optimizer, loss=\"categorical_crossentropy\", metrics=[\"accuracy\"])fit = model.fit_generator( data_aug.flow(train_X, trainY, batch_size=batch_size), epochs=epochs, validation_data=(test_X, testY), class_weight=class_weight, verbose=1)" }, { "code": null, "e": 13671, "s": 13554, "text": "The first line compiles the model. We create the model and define the optimizer, the loss, and the number of epochs." }, { "code": null, "e": 14041, "s": 13671, "text": "In the second line, we fit out model (this is where the training takes place). Our data_aug.flow method applies the augmentations to our images that we defined before. The number of epochs is set to 20. For the validation data, we use our test data. The verbose is set to 1, which just means that Keras will show the progress of the model being trained as you go along." }, { "code": null, "e": 14181, "s": 14041, "text": "Now, you’ve finished writing the code for your model. Its time to run it. Once you’ve run it for a bit, you should get an output like this:" }, { "code": null, "e": 14269, "s": 14181, "text": "Then after you’ve finished all you’re epochs, you should get an output similar to this:" }, { "code": null, "e": 14432, "s": 14269, "text": "Your accuracy should be at least 90%. If not, go an play around with the model architecture. Eventually, your model will return an accuracy of around 90% or more." }, { "code": null, "e": 14700, "s": 14432, "text": "Now you finished your classifier! It feels good, right! Well, that’s it for today. Hopefully, you learned something in this article! If you’re stuck on something, you can e-mail me at nushainef@gmail.com, and I’ll do my best to help you. Good luck on your ML journey." } ]
Count distinct pairs from two arrays having same sum of digits in C++
We are given with two arrays let’s say, arr_1[] and arr_2[] having integer values and the task is to calculate the count of distinct pairs having the same sum of digits. It means, one value should be selected from an arr_1[] and second value from arr_2[] to form a pair and both the values should have the same sum digits. Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Input − int arr_1[] = {1, 22, 42, 17} Int arr_2[] = {1, 31, 6, 8} Output − count is 4 Explanation − in total there are 4 pairs having the same sum of digits and those are (1, 1), (22, 31), (42, 6) and (17, 8). Input − int arr_1[] = {1, 22, 42, 17} Int arr_2[] = {2, 78, 6, 18} Output − count is 1 Explanation − in total there is only one pair having the same sum of digits and that is (42, 6). Input − int arr_1[] = {1, 22, 42, 17} Int arr_2[] = {2, 78, 16, 18} Output − count is 0 Explanation − There is no pair having the same sum of digits so count is 0. Create two arrays let’s say, arr_1[] and arr_2[] Create two arrays let’s say, arr_1[] and arr_2[] Calculate the length of both the arrays using the length() function that will return an integer value as per the elements in an array. Calculate the length of both the arrays using the length() function that will return an integer value as per the elements in an array. Create a set type variable let’s say st Create a set type variable let’s say st Start loop for i to 0 and i less than size of arr_1[] Start loop for i to 0 and i less than size of arr_1[] Inside the loop, Start another loop for j to 0 and j less than size of arr_2[]. Inside the loop, Start another loop for j to 0 and j less than size of arr_2[]. Check if Sum(arr[i]) = sum(arr_2[j]) then check if arr_1[i] less than arr_2[j] then insert(make_pair(arr_1[i], arr_2[j]) Check if Sum(arr[i]) = sum(arr_2[j]) then check if arr_1[i] less than arr_2[j] then insert(make_pair(arr_1[i], arr_2[j]) Else, insert(make_pair(arr_2[j], arr_1[i]). Else, insert(make_pair(arr_2[j], arr_1[i]). Return st.size() Return st.size() Print the result. Print the result. Live Demo #include <iostream> #include <set> using namespace std; // Function to find the // sum of digits of a number int sumdigits(int n){ int sum = 0; while (n > 0){ sum += n % 10; n = n / 10; } return sum; } //function to count the number of pairs int paircount(int arr_1[], int arr_2[], int size1, int size2){ // set is used to avoid duplicate pairs set<pair<int, int> > myset; for (int i = 0; i < size1; i++){ for (int j = 0; j < size2; j++){ // check sum of digits // of both the elements if (sumdigits(arr_1[i]) == sumdigits(arr_2[j])){ if (arr_1[i] < arr_2[j]){ myset.insert(make_pair(arr_1[i], arr_2[j])); } else{ myset.insert(make_pair(arr_2[j], arr_1[i])); } } } } // return size of the set return myset.size(); } // Driver code int main(){ int arr_1[] = { 1, 22, 42, 17 }; int arr_2[] = { 5, 31, 6, 8 }; int size1 = sizeof(arr_1) / sizeof(arr_1[0]); int size2 = sizeof(arr_2) / sizeof(arr_2[0]); cout <<"count is "<<paircount(arr_1, arr_2, size1, size2); return 0; } If we run the above code we will get the following output &miuns; count is 3
[ { "code": null, "e": 1385, "s": 1062, "text": "We are given with two arrays let’s say, arr_1[] and arr_2[] having integer values and the task is to calculate the count of distinct pairs having the same sum of digits. It means, one value should be selected from an arr_1[] and second value from arr_2[] to form a pair and both the values should have the same sum digits." }, { "code": null, "e": 1641, "s": 1385, "text": "Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type." }, { "code": null, "e": 1730, "s": 1641, "text": "Input − int arr_1[] = {1, 22, 42, 17}\n Int arr_2[] = {1, 31, 6, 8}\nOutput − count is 4" }, { "code": null, "e": 1854, "s": 1730, "text": "Explanation − in total there are 4 pairs having the same sum of digits and those are (1, 1), (22, 31), (42, 6) and (17, 8)." }, { "code": null, "e": 1944, "s": 1854, "text": "Input − int arr_1[] = {1, 22, 42, 17}\n Int arr_2[] = {2, 78, 6, 18}\nOutput − count is 1" }, { "code": null, "e": 2041, "s": 1944, "text": "Explanation − in total there is only one pair having the same sum of digits and that is (42, 6)." }, { "code": null, "e": 2132, "s": 2041, "text": "Input − int arr_1[] = {1, 22, 42, 17}\n Int arr_2[] = {2, 78, 16, 18}\nOutput − count is 0" }, { "code": null, "e": 2208, "s": 2132, "text": "Explanation − There is no pair having the same sum of digits so count is 0." }, { "code": null, "e": 2257, "s": 2208, "text": "Create two arrays let’s say, arr_1[] and arr_2[]" }, { "code": null, "e": 2306, "s": 2257, "text": "Create two arrays let’s say, arr_1[] and arr_2[]" }, { "code": null, "e": 2441, "s": 2306, "text": "Calculate the length of both the arrays using the length() function that will return an integer value as per the elements in an array." }, { "code": null, "e": 2576, "s": 2441, "text": "Calculate the length of both the arrays using the length() function that will return an integer value as per the elements in an array." }, { "code": null, "e": 2616, "s": 2576, "text": "Create a set type variable let’s say st" }, { "code": null, "e": 2656, "s": 2616, "text": "Create a set type variable let’s say st" }, { "code": null, "e": 2710, "s": 2656, "text": "Start loop for i to 0 and i less than size of arr_1[]" }, { "code": null, "e": 2764, "s": 2710, "text": "Start loop for i to 0 and i less than size of arr_1[]" }, { "code": null, "e": 2844, "s": 2764, "text": "Inside the loop, Start another loop for j to 0 and j less than size of arr_2[]." }, { "code": null, "e": 2924, "s": 2844, "text": "Inside the loop, Start another loop for j to 0 and j less than size of arr_2[]." }, { "code": null, "e": 3045, "s": 2924, "text": "Check if Sum(arr[i]) = sum(arr_2[j]) then check if arr_1[i] less than arr_2[j] then insert(make_pair(arr_1[i], arr_2[j])" }, { "code": null, "e": 3166, "s": 3045, "text": "Check if Sum(arr[i]) = sum(arr_2[j]) then check if arr_1[i] less than arr_2[j] then insert(make_pair(arr_1[i], arr_2[j])" }, { "code": null, "e": 3210, "s": 3166, "text": "Else, insert(make_pair(arr_2[j], arr_1[i])." }, { "code": null, "e": 3254, "s": 3210, "text": "Else, insert(make_pair(arr_2[j], arr_1[i])." }, { "code": null, "e": 3271, "s": 3254, "text": "Return st.size()" }, { "code": null, "e": 3288, "s": 3271, "text": "Return st.size()" }, { "code": null, "e": 3306, "s": 3288, "text": "Print the result." }, { "code": null, "e": 3324, "s": 3306, "text": "Print the result." }, { "code": null, "e": 3335, "s": 3324, "text": " Live Demo" }, { "code": null, "e": 4479, "s": 3335, "text": "#include <iostream>\n#include <set>\nusing namespace std;\n// Function to find the\n// sum of digits of a number\nint sumdigits(int n){\n int sum = 0;\n while (n > 0){\n sum += n % 10;\n n = n / 10;\n }\n return sum;\n}\n//function to count the number of pairs\nint paircount(int arr_1[], int arr_2[], int size1, int size2){\n // set is used to avoid duplicate pairs\n set<pair<int, int> > myset;\n for (int i = 0; i < size1; i++){\n for (int j = 0; j < size2; j++){\n // check sum of digits\n // of both the elements\n if (sumdigits(arr_1[i]) == sumdigits(arr_2[j])){\n if (arr_1[i] < arr_2[j]){\n myset.insert(make_pair(arr_1[i], arr_2[j]));\n } else{\n myset.insert(make_pair(arr_2[j], arr_1[i]));\n }\n }\n }\n }\n // return size of the set\n return myset.size();\n}\n// Driver code\nint main(){\n int arr_1[] = { 1, 22, 42, 17 };\n int arr_2[] = { 5, 31, 6, 8 };\n int size1 = sizeof(arr_1) / sizeof(arr_1[0]);\n int size2 = sizeof(arr_2) / sizeof(arr_2[0]);\n cout <<\"count is \"<<paircount(arr_1, arr_2, size1, size2);\n return 0;\n}" }, { "code": null, "e": 4545, "s": 4479, "text": "If we run the above code we will get the following output &miuns;" }, { "code": null, "e": 4556, "s": 4545, "text": "count is 3" } ]
Different ways to access Instance Variable in Python - GeeksforGeeks
04 May, 2020 Instance attributes are those attributes that are not shared by objects. Every object has its own copy of the instance attribute i.e. for every object, instance attribute is different. There are two ways to access the instance variable of class: Within the class by using self and object reference. Using getattr() method Example 1: Using Self and object reference #creating classclass student: # constructor def __init__(self, name, rollno): # instance variable self.name = name self.rollno = rollno def display(self): # using self to access # variable inside class print("hello my name is:", self.name) print("my roll number is:", self.rollno) # Driver Code# object createds = student('HARRY', 1001) # function call through objects.display() # accessing variable from # outside the classprint(s.name) Output: hello my name is: HARRY my roll number is: 1001 HARRY Example 2: Using getattr() # Python code for accessing attributes of class class emp: name='Harsh' salary='25000' def show(self): print(self.name) print(self.salary) # Driver Codee1 = emp() # Use getattr instead of e1.name print(getattr(e1,'name')) # returns true if object has attribute print(hasattr(e1,'name')) # sets an attribute setattr(e1,'height',152) # returns the value of attribute name height print(getattr(e1,'height')) # delete the attribute delattr(emp,'salary') Output: Harsh True 152 python-oop-concepts Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Read a file line by line in Python Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Reading and Writing to text files in Python Python OOPs Concepts Create a Pandas DataFrame from Lists
[ { "code": null, "e": 24590, "s": 24562, "text": "\n04 May, 2020" }, { "code": null, "e": 24775, "s": 24590, "text": "Instance attributes are those attributes that are not shared by objects. Every object has its own copy of the instance attribute i.e. for every object, instance attribute is different." }, { "code": null, "e": 24836, "s": 24775, "text": "There are two ways to access the instance variable of class:" }, { "code": null, "e": 24889, "s": 24836, "text": "Within the class by using self and object reference." }, { "code": null, "e": 24912, "s": 24889, "text": "Using getattr() method" }, { "code": null, "e": 24955, "s": 24912, "text": "Example 1: Using Self and object reference" }, { "code": "#creating classclass student: # constructor def __init__(self, name, rollno): # instance variable self.name = name self.rollno = rollno def display(self): # using self to access # variable inside class print(\"hello my name is:\", self.name) print(\"my roll number is:\", self.rollno) # Driver Code# object createds = student('HARRY', 1001) # function call through objects.display() # accessing variable from # outside the classprint(s.name)", "e": 25496, "s": 24955, "text": null }, { "code": null, "e": 25504, "s": 25496, "text": "Output:" }, { "code": null, "e": 25558, "s": 25504, "text": "hello my name is: HARRY\nmy roll number is: 1001\nHARRY" }, { "code": null, "e": 25585, "s": 25558, "text": "Example 2: Using getattr()" }, { "code": "# Python code for accessing attributes of class class emp: name='Harsh' salary='25000' def show(self): print(self.name) print(self.salary) # Driver Codee1 = emp() # Use getattr instead of e1.name print(getattr(e1,'name')) # returns true if object has attribute print(hasattr(e1,'name')) # sets an attribute setattr(e1,'height',152) # returns the value of attribute name height print(getattr(e1,'height')) # delete the attribute delattr(emp,'salary') ", "e": 26085, "s": 25585, "text": null }, { "code": null, "e": 26093, "s": 26085, "text": "Output:" }, { "code": null, "e": 26108, "s": 26093, "text": "Harsh\nTrue\n152" }, { "code": null, "e": 26128, "s": 26108, "text": "python-oop-concepts" }, { "code": null, "e": 26135, "s": 26128, "text": "Python" }, { "code": null, "e": 26233, "s": 26135, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26242, "s": 26233, "text": "Comments" }, { "code": null, "e": 26255, "s": 26242, "text": "Old Comments" }, { "code": null, "e": 26273, "s": 26255, "text": "Python Dictionary" }, { "code": null, "e": 26305, "s": 26273, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26327, "s": 26305, "text": "Enumerate() in Python" }, { "code": null, "e": 26362, "s": 26327, "text": "Read a file line by line in Python" }, { "code": null, "e": 26392, "s": 26362, "text": "Iterate over a list in Python" }, { "code": null, "e": 26434, "s": 26392, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26477, "s": 26434, "text": "Python program to convert a list to string" }, { "code": null, "e": 26521, "s": 26477, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26542, "s": 26521, "text": "Python OOPs Concepts" } ]
Generate Junit Test Cases Using Randoop API in Java
06 Jun, 2021 Here we will be discussing how to generate Junit test cases using Randoop along with sample illustration and snapshots of the current instances. So basically in Development If we talk about test cases, then every developer has to write test cases manually. Which is counted in the development effort and also increases the time of the project and cost estimate. So we can reduce the time taken to write the test cases with the help of some APIs. One of which is Randoop. Java and Randoop are prerequisite requirements before we move ahead. Fundamental Knowledge is required to generate the test cases using randoop you need to know the basics of Junit to verify the results. Working of Randoop: Randoop automatically creates Junit tests for your classes. It is a unit test generator for Java. Randoop generates unit tests using feedback-directed random test generation. This technique pseudo-randomly, but smartly, generates sequences of method/constructor invocations for the classes under test. Randoop typically generates two types of test cases: Error-revealing tests that detect bugs in your current code. Regression tests that can be used to detect the future bugs. Running of Randoop: Now you have the downloaded jar in your machine. To run it, you have to call the main method of Randoop like randoop.main.Main Step 1: First you have to set the environment variable of randoop-all-4.2.6.jar and. Step 2: After setting the variable open terminal and type the line given below and if everything is configured correctly then the out will be like this. java -classpath %RANDOOP_JAR% randoop.main.Main gentests --help Step 3: Now, generate Test cases for java file (–testclass) Create a sample java file to generate testcases. In this example we use –testclass option which is use to test single class file. Example Java public class Message { private String message; public Message(String message){ this.message = message; } public String printMessage(){ System.out.println(message); return message; } } Step 4: Compile using javac Message.java and it will generate Message.class file which will use by randoop to generate the test cases. Step 5: Now open the terminal/cmd and type the command like this: Syntax: java -classpath <location of the class file>;<location where jar file located> randoop-all-4.2.x randoop.main.Main gentests –testclass=<Class File name> Example: java -classpath C:\Users\public\Downloads\testbin;%RANDOOP_JAR% randoop.main.Main gentests --testclass=Message After running this command all the possible test cases of the Message.class file would be listed in the new Java files which is generated by Randoop named RegressionTest0, RegressionTest0. Generate Test cases for java files (--classlist) Implementation: In this example, we are going to generate test cases for the list of class files which is written in a simple text file and we provide that text file as an input to randoop. Syntax: java -classpath <location where jar file located> randoop-all-4.2.x randoop.main.Main gentests –classlist=<location of the file> Example: java -classpath %RANDOOP_JAR% randoop.main.Main gentests --classlist=C:\User\test1.txt Output: By now we are done with generating Junit test cases using Randoop API which was our aim goal. Still some useful set of operations are listed in the tabular format below to get a stronghold over Randoop API. They are as follows: Java 8 Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jun, 2021" }, { "code": null, "e": 703, "s": 28, "text": "Here we will be discussing how to generate Junit test cases using Randoop along with sample illustration and snapshots of the current instances. So basically in Development If we talk about test cases, then every developer has to write test cases manually. Which is counted in the development effort and also increases the time of the project and cost estimate. So we can reduce the time taken to write the test cases with the help of some APIs. One of which is Randoop. Java and Randoop are prerequisite requirements before we move ahead. Fundamental Knowledge is required to generate the test cases using randoop you need to know the basics of Junit to verify the results." }, { "code": null, "e": 1026, "s": 703, "text": "Working of Randoop: Randoop automatically creates Junit tests for your classes. It is a unit test generator for Java. Randoop generates unit tests using feedback-directed random test generation. This technique pseudo-randomly, but smartly, generates sequences of method/constructor invocations for the classes under test. " }, { "code": null, "e": 1079, "s": 1026, "text": "Randoop typically generates two types of test cases:" }, { "code": null, "e": 1140, "s": 1079, "text": "Error-revealing tests that detect bugs in your current code." }, { "code": null, "e": 1201, "s": 1140, "text": "Regression tests that can be used to detect the future bugs." }, { "code": null, "e": 1348, "s": 1201, "text": "Running of Randoop: Now you have the downloaded jar in your machine. To run it, you have to call the main method of Randoop like randoop.main.Main" }, { "code": null, "e": 1433, "s": 1348, "text": "Step 1: First you have to set the environment variable of randoop-all-4.2.6.jar and." }, { "code": null, "e": 1586, "s": 1433, "text": "Step 2: After setting the variable open terminal and type the line given below and if everything is configured correctly then the out will be like this." }, { "code": null, "e": 1650, "s": 1586, "text": "java -classpath %RANDOOP_JAR% randoop.main.Main gentests --help" }, { "code": null, "e": 1710, "s": 1650, "text": "Step 3: Now, generate Test cases for java file (–testclass)" }, { "code": null, "e": 1759, "s": 1710, "text": "Create a sample java file to generate testcases." }, { "code": null, "e": 1840, "s": 1759, "text": "In this example we use –testclass option which is use to test single class file." }, { "code": null, "e": 1848, "s": 1840, "text": "Example" }, { "code": null, "e": 1853, "s": 1848, "text": "Java" }, { "code": "public class Message { private String message; public Message(String message){ this.message = message; } public String printMessage(){ System.out.println(message); return message; } }", "e": 2069, "s": 1853, "text": null }, { "code": null, "e": 2204, "s": 2069, "text": "Step 4: Compile using javac Message.java and it will generate Message.class file which will use by randoop to generate the test cases." }, { "code": null, "e": 2270, "s": 2204, "text": "Step 5: Now open the terminal/cmd and type the command like this:" }, { "code": null, "e": 2278, "s": 2270, "text": "Syntax:" }, { "code": null, "e": 2432, "s": 2278, "text": "java -classpath <location of the class file>;<location where jar file located> randoop-all-4.2.x randoop.main.Main gentests –testclass=<Class File name> " }, { "code": null, "e": 2441, "s": 2432, "text": "Example:" }, { "code": null, "e": 2552, "s": 2441, "text": "java -classpath C:\\Users\\public\\Downloads\\testbin;%RANDOOP_JAR% randoop.main.Main gentests --testclass=Message" }, { "code": null, "e": 2741, "s": 2552, "text": "After running this command all the possible test cases of the Message.class file would be listed in the new Java files which is generated by Randoop named RegressionTest0, RegressionTest0." }, { "code": null, "e": 2790, "s": 2741, "text": "Generate Test cases for java files (--classlist)" }, { "code": null, "e": 2981, "s": 2790, "text": "Implementation: In this example, we are going to generate test cases for the list of class files which is written in a simple text file and we provide that text file as an input to randoop. " }, { "code": null, "e": 2989, "s": 2981, "text": "Syntax:" }, { "code": null, "e": 3118, "s": 2989, "text": "java -classpath <location where jar file located> randoop-all-4.2.x randoop.main.Main gentests –classlist=<location of the file>" }, { "code": null, "e": 3127, "s": 3118, "text": "Example:" }, { "code": null, "e": 3214, "s": 3127, "text": "java -classpath %RANDOOP_JAR% randoop.main.Main gentests --classlist=C:\\User\\test1.txt" }, { "code": null, "e": 3222, "s": 3214, "text": "Output:" }, { "code": null, "e": 3450, "s": 3222, "text": "By now we are done with generating Junit test cases using Randoop API which was our aim goal. Still some useful set of operations are listed in the tabular format below to get a stronghold over Randoop API. They are as follows:" }, { "code": null, "e": 3457, "s": 3450, "text": "Java 8" }, { "code": null, "e": 3462, "s": 3457, "text": "Java" }, { "code": null, "e": 3467, "s": 3462, "text": "Java" } ]
Output of C programs | Set 42
29 Oct, 2021 QUE.1 What is the output of following program? C #include <stdio.h>int main(){ int x = 10, *y, **z; y = &x; z = &y; printf("%d %d %d", *y, **z, *(*z)); return 0;} a. 10 10 10 b. 100xaa54f10 c. Run time error d. No Output Answer : a Explanation: Because y contains the address of x so *y print 10 then **z contains address of y of x so print the value of x 10 and 3rd *(*z) contains address of y of x that’s why print 10. So, final output is 10 10 10. QUE.2 What is the output of following program? C #include <stdio.h>int main(){ // initialize the val=1 int val = 1; do { val++; ++val; } while (val++ > 25); printf("%d\n", val); return 0;} a) 25 b) 50 c) 12 d) 4 Answer : d Explanation: Here, do while loop executes once and then it will check condition while will be false meanwhile value will be increased 3 times (two times in do while body and once while checking the condition); Hence value will be 4. QUE.3 What is the output of following program in the text file? C #include <stdio.h>int main(){ int a = 1, b = 2, c = 3; char d = 0; if (a, b, c, d) { printf("enter in the if\n"); } printf("not entered\n"); return 0;} a) enter in the if b) not entered c) run time error d) segmentation fault Answer : b Explanation: In this program, We are check the if condition all (a, b, c)>0 but d = 0 so condition is false didn’t enter in the if so print not entered. QUE.4 What is the output of following program? C #include <stdio.h>int main(){ char str[10] = "Hello"; printf("%d, %d\n", strlen(str), sizeof(str)); return 0;} a) 5, 10 b) 10, 5 c) 10, 20 d) None of the mentioned Answer: a Explanation: strlen gives length of the string that is 5; sizeof gives total number of occupied memory for a variable that is 8; since str is a pointer so sizeof(str) may be 2, 4 or 8. It depends on the computer architecture. QUE.5 What is the output of following program? C #include <stdio.h>int main(){ if (0) ; printf("Hello"); printf("Hi"); return 0;} OPTION a) Hi b) HelloHi c) run time error d) None of the mentioned Answer : b Explanation: There is a semicolon after the if statement, so this statement will be considered as a separate statement; and here printf(“Hello”); will not be associated with the if statement. Both printf statements will be executed. This article is contributed by Ajay Puri(ajay0007). 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. varshagumber28 chhabradhanvi C-Output Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n29 Oct, 2021" }, { "code": null, "e": 100, "s": 52, "text": "QUE.1 What is the output of following program? " }, { "code": null, "e": 102, "s": 100, "text": "C" }, { "code": "#include <stdio.h>int main(){ int x = 10, *y, **z; y = &x; z = &y; printf(\"%d %d %d\", *y, **z, *(*z)); return 0;}", "e": 233, "s": 102, "text": null }, { "code": null, "e": 292, "s": 233, "text": "a. 10 10 10 b. 100xaa54f10 c. Run time error d. No Output " }, { "code": null, "e": 303, "s": 292, "text": "Answer : a" }, { "code": null, "e": 522, "s": 303, "text": "Explanation: Because y contains the address of x so *y print 10 then **z contains address of y of x so print the value of x 10 and 3rd *(*z) contains address of y of x that’s why print 10. So, final output is 10 10 10." }, { "code": null, "e": 570, "s": 522, "text": "QUE.2 What is the output of following program? " }, { "code": null, "e": 572, "s": 570, "text": "C" }, { "code": "#include <stdio.h>int main(){ // initialize the val=1 int val = 1; do { val++; ++val; } while (val++ > 25); printf(\"%d\\n\", val); return 0;}", "e": 746, "s": 572, "text": null }, { "code": null, "e": 770, "s": 746, "text": "a) 25 b) 50 c) 12 d) 4 " }, { "code": null, "e": 781, "s": 770, "text": "Answer : d" }, { "code": null, "e": 1014, "s": 781, "text": "Explanation: Here, do while loop executes once and then it will check condition while will be false meanwhile value will be increased 3 times (two times in do while body and once while checking the condition); Hence value will be 4." }, { "code": null, "e": 1080, "s": 1014, "text": "QUE.3 What is the output of following program in the text file? " }, { "code": null, "e": 1082, "s": 1080, "text": "C" }, { "code": "#include <stdio.h>int main(){ int a = 1, b = 2, c = 3; char d = 0; if (a, b, c, d) { printf(\"enter in the if\\n\"); } printf(\"not entered\\n\"); return 0;}", "e": 1259, "s": 1082, "text": null }, { "code": null, "e": 1334, "s": 1259, "text": "a) enter in the if b) not entered c) run time error d) segmentation fault " }, { "code": null, "e": 1345, "s": 1334, "text": "Answer : b" }, { "code": null, "e": 1498, "s": 1345, "text": "Explanation: In this program, We are check the if condition all (a, b, c)>0 but d = 0 so condition is false didn’t enter in the if so print not entered." }, { "code": null, "e": 1547, "s": 1498, "text": "QUE.4 What is the output of following program? " }, { "code": null, "e": 1549, "s": 1547, "text": "C" }, { "code": "#include <stdio.h>int main(){ char str[10] = \"Hello\"; printf(\"%d, %d\\n\", strlen(str), sizeof(str)); return 0;}", "e": 1669, "s": 1549, "text": null }, { "code": null, "e": 1723, "s": 1669, "text": "a) 5, 10 b) 10, 5 c) 10, 20 d) None of the mentioned " }, { "code": null, "e": 1733, "s": 1723, "text": "Answer: a" }, { "code": null, "e": 1959, "s": 1733, "text": "Explanation: strlen gives length of the string that is 5; sizeof gives total number of occupied memory for a variable that is 8; since str is a pointer so sizeof(str) may be 2, 4 or 8. It depends on the computer architecture." }, { "code": null, "e": 2008, "s": 1959, "text": "QUE.5 What is the output of following program? " }, { "code": null, "e": 2010, "s": 2008, "text": "C" }, { "code": "#include <stdio.h>int main(){ if (0) ; printf(\"Hello\"); printf(\"Hi\"); return 0;}", "e": 2110, "s": 2010, "text": null }, { "code": null, "e": 2178, "s": 2110, "text": "OPTION a) Hi b) HelloHi c) run time error d) None of the mentioned " }, { "code": null, "e": 2189, "s": 2178, "text": "Answer : b" }, { "code": null, "e": 2422, "s": 2189, "text": "Explanation: There is a semicolon after the if statement, so this statement will be considered as a separate statement; and here printf(“Hello”); will not be associated with the if statement. Both printf statements will be executed." }, { "code": null, "e": 2850, "s": 2422, "text": "This article is contributed by Ajay Puri(ajay0007). 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": 2865, "s": 2850, "text": "varshagumber28" }, { "code": null, "e": 2879, "s": 2865, "text": "chhabradhanvi" }, { "code": null, "e": 2888, "s": 2879, "text": "C-Output" }, { "code": null, "e": 2903, "s": 2888, "text": "Program Output" } ]
Students with maximum average score of three subjects
09 Jun, 2021 Given a file containing data of student name and marks scored by him/her in 3 subjects. The task is to find the list of students having the maximum average score. Note : If more than one student has the maximum average score, print them as per the order in the file.Examples: Input : file[] = {“Shrikanth”, “20”, “30”, “10”, “Ram”, “100”, “50”, “10”} Output : Ram 53 Average scores of Shrikanth, Ram are 20 and 53 respectively. So Ram has the maximum average score of 53. Input : file[] = {“Ramesh”, “90”, “70”, “40”, “Adam”, “50”, “10”, ”40′′, “Suresh”, “22”, “1”, “56”, “Rocky”, “100”, “90”, “10”} Output : Ramesh Rocky 66 Average scores of Ramesh, Adam, Suresh and Rocky are 66, 33, 26 and 66 respectively. So both Ramesh and Rocky have the maximum average score of 66. Approach : Traverse the file data and store average scores for each student.Now, find the maximum average score and search for all the students with this maximum average score.Print the maximum average score and names as per the order in the file. Traverse the file data and store average scores for each student. Now, find the maximum average score and search for all the students with this maximum average score. Print the maximum average score and names as per the order in the file. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to find the// list of students having maximum average score#include<bits/stdc++.h>using namespace std; // Function to find the// list of students having maximum average score// Driver codevoid getStudentsList(string file[],int n){ // Variables to store average score of a student // and maximum average score int avgScore; int maxAvgScore = INT_MIN; // List to store names of students // having maximum average score vector<string> names; // Traversing the file data for (int i = 0; i < n; i += 4) { // finding average score of a student avgScore = (stoi(file[i + 1]) + stoi(file[i + 2]) + stoi(file[i + 3])) / 3; if (avgScore > maxAvgScore) { maxAvgScore = avgScore; // Clear the list and add name of student // having current maximum average score in the list names.clear(); names.push_back(file[i]); } else if (avgScore == maxAvgScore) names.push_back(file[i]); } // Printing the maximum average score and names // of students having this maximum average score // as per the order in the file. for (int i = 0; i < names.size(); i++) { cout <<names[i] + " "; } cout << maxAvgScore;} // Driver codeint main(){ string file[] = { "Shrikanth", "20", "30", "10", "Ram", "100", "50", "10" }; // Number of elements in string array int n= sizeof(file)/sizeof(file[0]); getStudentsList(file,n);} // This code is contributed by ihritik // Java program to find the// list of students having maximum average score import java.io.*;import java.util.*;import java.lang.*; class GFG { // Function to find the // list of students having maximum average score // Driver code static void getStudentsList(String[] file) { // Variables to store average score of a student // and maximum average score int avgScore; int maxAvgScore = Integer.MIN_VALUE; // List to store names of students // having maximum average score ArrayList<String> names = new ArrayList<>(); // Traversing the file data for (int i = 0; i < file.length; i += 4) { // finding average score of a student avgScore = (Integer.parseInt(file[i + 1]) + Integer.parseInt(file[i + 2]) + Integer.parseInt(file[i + 3])) / 3; if (avgScore > maxAvgScore) { maxAvgScore = avgScore; // Clear the list and add name of student // having current maximum average score in the list names.clear(); names.add(file[i]); } else if (avgScore == maxAvgScore) names.add(file[i]); } // Printing the maximum average score and names // of students having this maximum average score // as per the order in the file. for (int i = 0; i < names.size(); i++) { System.out.print(names.get(i) + " "); } System.out.print(maxAvgScore); } // Driver code public static void main(String args[]) { String[] file = { "Shrikanth", "20", "30", "10", "Ram", "100", "50", "10" }; getStudentsList(file); }} # Python3 program to find the list of# students having maximum average score # Function to find the list of students# having maximum average scoredef getStudentsList(file): # Variables to store maximum # average score maxAvgScore = 0 # List to store names of students # having maximum average score names = [] # Traversing the file data for i in range(0, len(file), 4): # finding average score # of a student avgScore = (int(file[i + 1]) + int(file[i + 2]) + int(file[i + 3])) // 3 if avgScore > maxAvgScore: maxAvgScore = avgScore # Clear the list and add name # of student having current # maximum average score in the list names.clear() names.append(file[i]) elif avgScore == maxAvgScore: names.add(file[i]) # Printing the maximum average score and names # of students having this maximum average score # as per the order in the file. for i in range(len(names)): print(names[i], end = " ") print(maxAvgScore) # Driver Codeif __name__ == "__main__": file = ["Shrikanth", "20", "30", "10", "Ram", "100", "50", "10"] getStudentsList(file) # This code is contributed# by rituraj_jain // C# program to find the// list of students having maximum average score using System;using System.Collections.Generic;class GFG { // Function to find the // list of students having maximum average score // Driver code static void getStudentsList(string [] file) { // Variables to store average score of a student // and maximum average score int avgScore; int maxAvgScore = Int32.MinValue; // List to store names of students // having maximum average score List<string> names = new List<string>(); // Traversing the file data for (int i = 0; i < file.Length; i += 4) { // finding average score of a student avgScore = (Int32.Parse(file[i + 1]) + Int32.Parse(file[i + 2]) + Int32.Parse(file[i + 3])) / 3; if (avgScore > maxAvgScore) { maxAvgScore = avgScore; // Clear the list and add name of student // having current maximum average score in the list names.Clear(); names.Add(file[i]); } else if (avgScore == maxAvgScore) names.Add(file[i]); } // Printing the maximum average score and names // of students having this maximum average score // as per the order in the file. for (int i = 0; i < names.Count; i++) { Console.Write(names[i] + " "); } Console.WriteLine(maxAvgScore); } // Driver code public static void Main() { string[] file = { "Shrikanth", "20", "30", "10", "Ram", "100", "50", "10" }; getStudentsList(file); }} // This code is contributed by ihritik <?php// PHP program to find the list of students// having maximum average score // Function to find the list of students// having maximum average scorefunction getStudentsList($file, $n){ // Variables to store average score of // a student and maximum average score $maxAvgScore = PHP_INT_MIN; // List to store names of students // having maximum average score $names = array(); $avgScore = 0; // Traversing the file data for ($i = 0; $i < $n; $i += 4) { // finding average score of a student $avgScore = (int)((intval($file[$i + 1]) + intval($file[$i + 2]) + intval($file[$i + 3])) / 3); if ($avgScore > $maxAvgScore) { $maxAvgScore = $avgScore; // Clear the list and add name of // student having current maximum // average score in the list unset($names); $names = array(); array_push($names, $file[$i]); } else if ($avgScore == $maxAvgScore) array_push($names, $file[$i]); } // Printing the maximum average score // and names of students having this // maximum average score as per the // order in the file. for ($i = 0; $i < count($names); $i++) { echo $names[$i] . " "; } echo $maxAvgScore;} // Driver code$file = array( "Shrikanth", "20", "30", "10", "Ram", "100", "50", "10" ); // Number of elements in string array $n = count($file); getStudentsList($file, $n); // This code is contributed by mits?> <script>// Javascript program to find the// list of students having maximum average score // Function to find the// list of students having maximum average score// Driver codefunction getStudentsList(file, n){ // Variables to store average score of a student // and maximum average score let avgScore; let maxAvgScore = Number.MIN_SAFE_INTEGER; // List to store names of students // having maximum average score let names = []; // Traversing the file data for (let i = 0; i < n; i += 4) { // finding average score of a student avgScore = Math.floor((Number(file[i + 1]) + Number(file[i + 2]) + Number(file[i + 3])) / 3); if (avgScore > maxAvgScore) { maxAvgScore = avgScore; // Clear the list and add name of student // having current maximum average score in the list names = []; names.push(file[i]); } else if (avgScore == maxAvgScore) names.push(file[i]); } // Printing the maximum average score and names // of students having this maximum average score // as per the order in the file. for (let i = 0; i < names.length; i++) { document.write(names[i] + " "); } document.write(maxAvgScore);} // Driver code let file = ["Shrikanth", "20", "30", "10", "Ram", "100", "50", "10"]; // Number of elements in string array let n = file.length; getStudentsList(file, n); // This code is contributed by gfgking. </script> Ram 53 rituraj_jain ihritik Mithun Kumar nidhi_biet gfgking array-traversal-question Arrays Java Programs Strings Arrays Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Jun, 2021" }, { "code": null, "e": 306, "s": 28, "text": "Given a file containing data of student name and marks scored by him/her in 3 subjects. The task is to find the list of students having the maximum average score. Note : If more than one student has the maximum average score, print them as per the order in the file.Examples: " }, { "code": null, "e": 817, "s": 306, "text": "Input : file[] = {“Shrikanth”, “20”, “30”, “10”, “Ram”, “100”, “50”, “10”} Output : Ram 53 Average scores of Shrikanth, Ram are 20 and 53 respectively. So Ram has the maximum average score of 53. Input : file[] = {“Ramesh”, “90”, “70”, “40”, “Adam”, “50”, “10”, ”40′′, “Suresh”, “22”, “1”, “56”, “Rocky”, “100”, “90”, “10”} Output : Ramesh Rocky 66 Average scores of Ramesh, Adam, Suresh and Rocky are 66, 33, 26 and 66 respectively. So both Ramesh and Rocky have the maximum average score of 66. " }, { "code": null, "e": 832, "s": 819, "text": "Approach : " }, { "code": null, "e": 1069, "s": 832, "text": "Traverse the file data and store average scores for each student.Now, find the maximum average score and search for all the students with this maximum average score.Print the maximum average score and names as per the order in the file." }, { "code": null, "e": 1135, "s": 1069, "text": "Traverse the file data and store average scores for each student." }, { "code": null, "e": 1236, "s": 1135, "text": "Now, find the maximum average score and search for all the students with this maximum average score." }, { "code": null, "e": 1308, "s": 1236, "text": "Print the maximum average score and names as per the order in the file." }, { "code": null, "e": 1361, "s": 1308, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1365, "s": 1361, "text": "C++" }, { "code": null, "e": 1370, "s": 1365, "text": "Java" }, { "code": null, "e": 1378, "s": 1370, "text": "Python3" }, { "code": null, "e": 1381, "s": 1378, "text": "C#" }, { "code": null, "e": 1385, "s": 1381, "text": "PHP" }, { "code": null, "e": 1396, "s": 1385, "text": "Javascript" }, { "code": "// C++ program to find the// list of students having maximum average score#include<bits/stdc++.h>using namespace std; // Function to find the// list of students having maximum average score// Driver codevoid getStudentsList(string file[],int n){ // Variables to store average score of a student // and maximum average score int avgScore; int maxAvgScore = INT_MIN; // List to store names of students // having maximum average score vector<string> names; // Traversing the file data for (int i = 0; i < n; i += 4) { // finding average score of a student avgScore = (stoi(file[i + 1]) + stoi(file[i + 2]) + stoi(file[i + 3])) / 3; if (avgScore > maxAvgScore) { maxAvgScore = avgScore; // Clear the list and add name of student // having current maximum average score in the list names.clear(); names.push_back(file[i]); } else if (avgScore == maxAvgScore) names.push_back(file[i]); } // Printing the maximum average score and names // of students having this maximum average score // as per the order in the file. for (int i = 0; i < names.size(); i++) { cout <<names[i] + \" \"; } cout << maxAvgScore;} // Driver codeint main(){ string file[] = { \"Shrikanth\", \"20\", \"30\", \"10\", \"Ram\", \"100\", \"50\", \"10\" }; // Number of elements in string array int n= sizeof(file)/sizeof(file[0]); getStudentsList(file,n);} // This code is contributed by ihritik", "e": 2993, "s": 1396, "text": null }, { "code": "// Java program to find the// list of students having maximum average score import java.io.*;import java.util.*;import java.lang.*; class GFG { // Function to find the // list of students having maximum average score // Driver code static void getStudentsList(String[] file) { // Variables to store average score of a student // and maximum average score int avgScore; int maxAvgScore = Integer.MIN_VALUE; // List to store names of students // having maximum average score ArrayList<String> names = new ArrayList<>(); // Traversing the file data for (int i = 0; i < file.length; i += 4) { // finding average score of a student avgScore = (Integer.parseInt(file[i + 1]) + Integer.parseInt(file[i + 2]) + Integer.parseInt(file[i + 3])) / 3; if (avgScore > maxAvgScore) { maxAvgScore = avgScore; // Clear the list and add name of student // having current maximum average score in the list names.clear(); names.add(file[i]); } else if (avgScore == maxAvgScore) names.add(file[i]); } // Printing the maximum average score and names // of students having this maximum average score // as per the order in the file. for (int i = 0; i < names.size(); i++) { System.out.print(names.get(i) + \" \"); } System.out.print(maxAvgScore); } // Driver code public static void main(String args[]) { String[] file = { \"Shrikanth\", \"20\", \"30\", \"10\", \"Ram\", \"100\", \"50\", \"10\" }; getStudentsList(file); }}", "e": 4766, "s": 2993, "text": null }, { "code": "# Python3 program to find the list of# students having maximum average score # Function to find the list of students# having maximum average scoredef getStudentsList(file): # Variables to store maximum # average score maxAvgScore = 0 # List to store names of students # having maximum average score names = [] # Traversing the file data for i in range(0, len(file), 4): # finding average score # of a student avgScore = (int(file[i + 1]) + int(file[i + 2]) + int(file[i + 3])) // 3 if avgScore > maxAvgScore: maxAvgScore = avgScore # Clear the list and add name # of student having current # maximum average score in the list names.clear() names.append(file[i]) elif avgScore == maxAvgScore: names.add(file[i]) # Printing the maximum average score and names # of students having this maximum average score # as per the order in the file. for i in range(len(names)): print(names[i], end = \" \") print(maxAvgScore) # Driver Codeif __name__ == \"__main__\": file = [\"Shrikanth\", \"20\", \"30\", \"10\", \"Ram\", \"100\", \"50\", \"10\"] getStudentsList(file) # This code is contributed# by rituraj_jain", "e": 6129, "s": 4766, "text": null }, { "code": "// C# program to find the// list of students having maximum average score using System;using System.Collections.Generic;class GFG { // Function to find the // list of students having maximum average score // Driver code static void getStudentsList(string [] file) { // Variables to store average score of a student // and maximum average score int avgScore; int maxAvgScore = Int32.MinValue; // List to store names of students // having maximum average score List<string> names = new List<string>(); // Traversing the file data for (int i = 0; i < file.Length; i += 4) { // finding average score of a student avgScore = (Int32.Parse(file[i + 1]) + Int32.Parse(file[i + 2]) + Int32.Parse(file[i + 3])) / 3; if (avgScore > maxAvgScore) { maxAvgScore = avgScore; // Clear the list and add name of student // having current maximum average score in the list names.Clear(); names.Add(file[i]); } else if (avgScore == maxAvgScore) names.Add(file[i]); } // Printing the maximum average score and names // of students having this maximum average score // as per the order in the file. for (int i = 0; i < names.Count; i++) { Console.Write(names[i] + \" \"); } Console.WriteLine(maxAvgScore); } // Driver code public static void Main() { string[] file = { \"Shrikanth\", \"20\", \"30\", \"10\", \"Ram\", \"100\", \"50\", \"10\" }; getStudentsList(file); }} // This code is contributed by ihritik", "e": 7886, "s": 6129, "text": null }, { "code": "<?php// PHP program to find the list of students// having maximum average score // Function to find the list of students// having maximum average scorefunction getStudentsList($file, $n){ // Variables to store average score of // a student and maximum average score $maxAvgScore = PHP_INT_MIN; // List to store names of students // having maximum average score $names = array(); $avgScore = 0; // Traversing the file data for ($i = 0; $i < $n; $i += 4) { // finding average score of a student $avgScore = (int)((intval($file[$i + 1]) + intval($file[$i + 2]) + intval($file[$i + 3])) / 3); if ($avgScore > $maxAvgScore) { $maxAvgScore = $avgScore; // Clear the list and add name of // student having current maximum // average score in the list unset($names); $names = array(); array_push($names, $file[$i]); } else if ($avgScore == $maxAvgScore) array_push($names, $file[$i]); } // Printing the maximum average score // and names of students having this // maximum average score as per the // order in the file. for ($i = 0; $i < count($names); $i++) { echo $names[$i] . \" \"; } echo $maxAvgScore;} // Driver code$file = array( \"Shrikanth\", \"20\", \"30\", \"10\", \"Ram\", \"100\", \"50\", \"10\" ); // Number of elements in string array $n = count($file); getStudentsList($file, $n); // This code is contributed by mits?>", "e": 9474, "s": 7886, "text": null }, { "code": "<script>// Javascript program to find the// list of students having maximum average score // Function to find the// list of students having maximum average score// Driver codefunction getStudentsList(file, n){ // Variables to store average score of a student // and maximum average score let avgScore; let maxAvgScore = Number.MIN_SAFE_INTEGER; // List to store names of students // having maximum average score let names = []; // Traversing the file data for (let i = 0; i < n; i += 4) { // finding average score of a student avgScore = Math.floor((Number(file[i + 1]) + Number(file[i + 2]) + Number(file[i + 3])) / 3); if (avgScore > maxAvgScore) { maxAvgScore = avgScore; // Clear the list and add name of student // having current maximum average score in the list names = []; names.push(file[i]); } else if (avgScore == maxAvgScore) names.push(file[i]); } // Printing the maximum average score and names // of students having this maximum average score // as per the order in the file. for (let i = 0; i < names.length; i++) { document.write(names[i] + \" \"); } document.write(maxAvgScore);} // Driver code let file = [\"Shrikanth\", \"20\", \"30\", \"10\", \"Ram\", \"100\", \"50\", \"10\"]; // Number of elements in string array let n = file.length; getStudentsList(file, n); // This code is contributed by gfgking. </script>", "e": 10982, "s": 9474, "text": null }, { "code": null, "e": 10989, "s": 10982, "text": "Ram 53" }, { "code": null, "e": 11004, "s": 10991, "text": "rituraj_jain" }, { "code": null, "e": 11012, "s": 11004, "text": "ihritik" }, { "code": null, "e": 11025, "s": 11012, "text": "Mithun Kumar" }, { "code": null, "e": 11036, "s": 11025, "text": "nidhi_biet" }, { "code": null, "e": 11044, "s": 11036, "text": "gfgking" }, { "code": null, "e": 11069, "s": 11044, "text": "array-traversal-question" }, { "code": null, "e": 11076, "s": 11069, "text": "Arrays" }, { "code": null, "e": 11090, "s": 11076, "text": "Java Programs" }, { "code": null, "e": 11098, "s": 11090, "text": "Strings" }, { "code": null, "e": 11105, "s": 11098, "text": "Arrays" }, { "code": null, "e": 11113, "s": 11105, "text": "Strings" } ]
Python | Assign range of elements to List
13 May, 2019 Assigning elements to list is a common problem and many varieties of it have been discussed in the previous articles. This particular article discusses the insertion of range of elements in the list. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using extend()This can be solved using the extend function in which the insertion of range of numbers can be done on the rear end using the range function. # Python3 code to demonstrate# Assigning range of elements to List# using extend() # initializing listtest_list = [3, 5, 6, 8] # printing original listprint("The original list : " + str(test_list)) # using extend()# Assigning range of elements to Listtest_list.extend(range(6)) # print resultprint("The list after adding range elements : " + str(test_list)) The original list : [3, 5, 6, 8] The list after adding range elements : [3, 5, 6, 8, 0, 1, 2, 3, 4, 5] Method #2 Using * operatorThis problem can also be solved using the * operator and with the advantage of flexibility of addition of elements at any position. # Python3 code to demonstrate# Assigning range of elements to List# using * operator # initializing listtest_list = [3, 5, 6, 8] # printing original listprint("The original list : " + str(test_list)) # using * operator# Assigning range of elements to Listres = [3, 5, *range(6), 6, 8] # print resultprint("The list after adding range elements : " + str(res)) The original list : [3, 5, 6, 8] The list after adding range elements : [3, 5, 0, 1, 2, 3, 4, 5, 6, 8] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n13 May, 2019" }, { "code": null, "e": 317, "s": 53, "text": "Assigning elements to list is a common problem and many varieties of it have been discussed in the previous articles. This particular article discusses the insertion of range of elements in the list. Let’s discuss certain ways in which this problem can be solved." }, { "code": null, "e": 485, "s": 317, "text": "Method #1 : Using extend()This can be solved using the extend function in which the insertion of range of numbers can be done on the rear end using the range function." }, { "code": "# Python3 code to demonstrate# Assigning range of elements to List# using extend() # initializing listtest_list = [3, 5, 6, 8] # printing original listprint(\"The original list : \" + str(test_list)) # using extend()# Assigning range of elements to Listtest_list.extend(range(6)) # print resultprint(\"The list after adding range elements : \" + str(test_list))", "e": 847, "s": 485, "text": null }, { "code": null, "e": 951, "s": 847, "text": "The original list : [3, 5, 6, 8]\nThe list after adding range elements : [3, 5, 6, 8, 0, 1, 2, 3, 4, 5]\n" }, { "code": null, "e": 1111, "s": 953, "text": "Method #2 Using * operatorThis problem can also be solved using the * operator and with the advantage of flexibility of addition of elements at any position." }, { "code": "# Python3 code to demonstrate# Assigning range of elements to List# using * operator # initializing listtest_list = [3, 5, 6, 8] # printing original listprint(\"The original list : \" + str(test_list)) # using * operator# Assigning range of elements to Listres = [3, 5, *range(6), 6, 8] # print resultprint(\"The list after adding range elements : \" + str(res))", "e": 1474, "s": 1111, "text": null }, { "code": null, "e": 1578, "s": 1474, "text": "The original list : [3, 5, 6, 8]\nThe list after adding range elements : [3, 5, 0, 1, 2, 3, 4, 5, 6, 8]\n" }, { "code": null, "e": 1599, "s": 1578, "text": "Python list-programs" }, { "code": null, "e": 1606, "s": 1599, "text": "Python" }, { "code": null, "e": 1622, "s": 1606, "text": "Python Programs" } ]
Python | Program to accept the strings which contains all vowels
23 Jun, 2022 Given a string, the task is to check if every vowel is present or not. We consider a vowel to be present if it is present in upper case or lower case. i.e. ‘a’, ‘e’, ‘i’.’o’, ‘u’ or ‘A’, ‘E’, ‘I’, ‘O’, ‘U’ . Examples : Input : geeksforgeeks Output : Not Accepted All vowels except 'a','i','u' are not present Input : ABeeIghiObhkUul Output : Accepted All vowels are present Approach : Firstly, create set of vowels using set() function. Check for each character of the string is vowel or not, if vowel then add into the set s. After coming out of the loop, check length of the set s, if length of set s is equal to the length of the vowels set then string is accepted otherwise not. Below is the implementation : Python3 # Python program to accept the strings# which contains all the vowels # Function for check if string# is accepted or notdef check(string) : string = string.lower() # set() function convert "aeiou" # string into set of characters # i.e.vowels = {'a', 'e', 'i', 'o', 'u'} vowels = set("aeiou") # set() function convert empty # dictionary into empty set s = set({}) # looping through each # character of the string for char in string : # Check for the character is present inside # the vowels set or not. If present, then # add into the set s by using add method if char in vowels : s.add(char) else: pass # check the length of set s equal to length # of vowels set or not. If equal, string is # accepted otherwise not if len(s) == len(vowels) : print("Accepted") else : print("Not Accepted") # Driver codeif __name__ == "__main__" : string = "SEEquoiaL" # calling function check(string) Accepted Alternate Implementation : Python3 def check(string): string = string.replace(' ', '') string = string.lower() vowel = [string.count('a'), string.count('e'), string.count( 'i'), string.count('o'), string.count('u')] # If 0 is present int vowel count array if vowel.count(0) > 0: return('not accepted') else: return('accepted') # Driver codeif __name__ == "__main__": string = "SEEquoiaL" print(check(string)) accepted Alternate Implementation 2.0 : Python3 # Python program for the above approachdef check(string): if len(set(string.lower()).intersection("aeiou")) >= 5: return ('accepted') else: return ("not accepted") # Driver codeif __name__ == "__main__": string = "geeksforgeeks" print(check(string)) not accepted Alternate Implementation 3.0 (Using Regular Expressions): Compile a regular expression using compile() for “character is not a, e, i, o and u”.Use re.findall() to fetch the strings satisfying the above regular expression.Print output based on the result. Python3 #import libraryimport re sampleInput = "aeioAEiuioea" # regular expression to find the strings# which have characters other than a,e,i,o and uc = re.compile('[^aeiouAEIOU]') # use findall() to get the list of strings# that have characters other than a,e,i,o and u.if(len(c.findall(sampleInput))): print("Not Accepted") # if length of list > 0 then it is not acceptedelse: print("Accepted") # if length of list = 0 then it is accepted Accepted Alternate Implementation 4.0 (using data structures): Python3 # Python | Program to accept the strings which contains all vowels def all_vowels(str_value): new_list = [char for char in str_value.lower() if char in 'aeiou'] if new_list: dic, lst = {}, [] for char in new_list: dic['a'] = new_list.count('a') dic['e'] = new_list.count('e') dic['i'] = new_list.count('i') dic['o'] = new_list.count('o') dic['u'] = new_list.count('u') for i, j in dic.items(): if j == 0: lst.append(i) if lst: return f"All vowels except {','.join(lst)} are not presant" else: return 'All vowels are present' else: return "No vowels presant" # function-callstr_value = "geeksforgeeks"print(all_vowels(str_value)) str_value = "ABeeIghiObhkUul"print(all_vowels(str_value)) # contribute by saikot All vowels except a,i,u are not presant All vowels are present jatinkataria94 chauhansumit sanidhya007 shruthims saikot raushangrh Python string-programs python-set python-string Python Python Programs python-set Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n23 Jun, 2022" }, { "code": null, "e": 273, "s": 53, "text": "Given a string, the task is to check if every vowel is present or not. We consider a vowel to be present if it is present in upper case or lower case. i.e. ‘a’, ‘e’, ‘i’.’o’, ‘u’ or ‘A’, ‘E’, ‘I’, ‘O’, ‘U’ . Examples : " }, { "code": null, "e": 429, "s": 273, "text": "Input : geeksforgeeks\nOutput : Not Accepted\nAll vowels except 'a','i','u' are not present\n\nInput : ABeeIghiObhkUul\nOutput : Accepted\nAll vowels are present" }, { "code": null, "e": 769, "s": 429, "text": "Approach : Firstly, create set of vowels using set() function. Check for each character of the string is vowel or not, if vowel then add into the set s. After coming out of the loop, check length of the set s, if length of set s is equal to the length of the vowels set then string is accepted otherwise not. Below is the implementation : " }, { "code": null, "e": 777, "s": 769, "text": "Python3" }, { "code": "# Python program to accept the strings# which contains all the vowels # Function for check if string# is accepted or notdef check(string) : string = string.lower() # set() function convert \"aeiou\" # string into set of characters # i.e.vowels = {'a', 'e', 'i', 'o', 'u'} vowels = set(\"aeiou\") # set() function convert empty # dictionary into empty set s = set({}) # looping through each # character of the string for char in string : # Check for the character is present inside # the vowels set or not. If present, then # add into the set s by using add method if char in vowels : s.add(char) else: pass # check the length of set s equal to length # of vowels set or not. If equal, string is # accepted otherwise not if len(s) == len(vowels) : print(\"Accepted\") else : print(\"Not Accepted\") # Driver codeif __name__ == \"__main__\" : string = \"SEEquoiaL\" # calling function check(string)", "e": 1816, "s": 777, "text": null }, { "code": null, "e": 1825, "s": 1816, "text": "Accepted" }, { "code": null, "e": 1852, "s": 1825, "text": "Alternate Implementation :" }, { "code": null, "e": 1860, "s": 1852, "text": "Python3" }, { "code": "def check(string): string = string.replace(' ', '') string = string.lower() vowel = [string.count('a'), string.count('e'), string.count( 'i'), string.count('o'), string.count('u')] # If 0 is present int vowel count array if vowel.count(0) > 0: return('not accepted') else: return('accepted') # Driver codeif __name__ == \"__main__\": string = \"SEEquoiaL\" print(check(string))", "e": 2283, "s": 1860, "text": null }, { "code": null, "e": 2292, "s": 2283, "text": "accepted" }, { "code": null, "e": 2324, "s": 2292, "text": "Alternate Implementation 2.0 : " }, { "code": null, "e": 2332, "s": 2324, "text": "Python3" }, { "code": "# Python program for the above approachdef check(string): if len(set(string.lower()).intersection(\"aeiou\")) >= 5: return ('accepted') else: return (\"not accepted\") # Driver codeif __name__ == \"__main__\": string = \"geeksforgeeks\" print(check(string))", "e": 2609, "s": 2332, "text": null }, { "code": null, "e": 2622, "s": 2609, "text": "not accepted" }, { "code": null, "e": 2680, "s": 2622, "text": "Alternate Implementation 3.0 (Using Regular Expressions):" }, { "code": null, "e": 2877, "s": 2680, "text": "Compile a regular expression using compile() for “character is not a, e, i, o and u”.Use re.findall() to fetch the strings satisfying the above regular expression.Print output based on the result." }, { "code": null, "e": 2885, "s": 2877, "text": "Python3" }, { "code": "#import libraryimport re sampleInput = \"aeioAEiuioea\" # regular expression to find the strings# which have characters other than a,e,i,o and uc = re.compile('[^aeiouAEIOU]') # use findall() to get the list of strings# that have characters other than a,e,i,o and u.if(len(c.findall(sampleInput))): print(\"Not Accepted\") # if length of list > 0 then it is not acceptedelse: print(\"Accepted\") # if length of list = 0 then it is accepted", "e": 3327, "s": 2885, "text": null }, { "code": null, "e": 3336, "s": 3327, "text": "Accepted" }, { "code": null, "e": 3390, "s": 3336, "text": "Alternate Implementation 4.0 (using data structures):" }, { "code": null, "e": 3398, "s": 3390, "text": "Python3" }, { "code": "# Python | Program to accept the strings which contains all vowels def all_vowels(str_value): new_list = [char for char in str_value.lower() if char in 'aeiou'] if new_list: dic, lst = {}, [] for char in new_list: dic['a'] = new_list.count('a') dic['e'] = new_list.count('e') dic['i'] = new_list.count('i') dic['o'] = new_list.count('o') dic['u'] = new_list.count('u') for i, j in dic.items(): if j == 0: lst.append(i) if lst: return f\"All vowels except {','.join(lst)} are not presant\" else: return 'All vowels are present' else: return \"No vowels presant\" # function-callstr_value = \"geeksforgeeks\"print(all_vowels(str_value)) str_value = \"ABeeIghiObhkUul\"print(all_vowels(str_value)) # contribute by saikot", "e": 4271, "s": 3398, "text": null }, { "code": null, "e": 4334, "s": 4271, "text": "All vowels except a,i,u are not presant\nAll vowels are present" }, { "code": null, "e": 4349, "s": 4334, "text": "jatinkataria94" }, { "code": null, "e": 4362, "s": 4349, "text": "chauhansumit" }, { "code": null, "e": 4374, "s": 4362, "text": "sanidhya007" }, { "code": null, "e": 4384, "s": 4374, "text": "shruthims" }, { "code": null, "e": 4391, "s": 4384, "text": "saikot" }, { "code": null, "e": 4402, "s": 4391, "text": "raushangrh" }, { "code": null, "e": 4425, "s": 4402, "text": "Python string-programs" }, { "code": null, "e": 4436, "s": 4425, "text": "python-set" }, { "code": null, "e": 4450, "s": 4436, "text": "python-string" }, { "code": null, "e": 4457, "s": 4450, "text": "Python" }, { "code": null, "e": 4473, "s": 4457, "text": "Python Programs" }, { "code": null, "e": 4484, "s": 4473, "text": "python-set" } ]
How to Train Detectron2 on Custom Object Detection Data | by Jacob Solawetz | Towards Data Science
Overview of Detectron2 Overview of our custom dataset Install Detectron2 dependencies Download custom Detectron2 object detection data Visualize Detectron2 training data Write our Detectron2 training configuration Run Detectron2 training Evaluate Detectron2 performance Run Detectron2 inference on test images Colab Notebook Implementing Detectron2 on Custom Data Public Blood Cell Detection Dataset Detectron2 is a popular PyTorch based modular computer vision model library. It is the second iteration of Detectron, originally written in Caffe2. The Detectron2 system allows you to plug in custom state of the art computer vision technologies into your workflow. Quoting the Detectron2 release blog: Detectron2 includes all the models that were available in the original Detectron, such as Faster R-CNN, Mask R-CNN, RetinaNet, and DensePose. It also features several new models, including Cascade R-CNN, Panoptic FPN, and TensorMask, and we will continue to add more algorithms. We’ve also added features such as synchronous Batch Norm and support for new datasets like LVIS In this post, we review how to train Detectron2 on custom data for specifically object detection. Though, after you finish reading you will be familiar with the Detectron2 ecosystem and you will be able to generalize to other capabilities included in Detectron2. We will be training our custom Detectron2 detector on public blood cell detection data hosted for free at Roboflow. The blood cell detection dataset is representative of a small custom object detection dataset that one might collect to construct a custom object detection system. Notably, blood cell detection is not a capability available in Detectron2 — we need to train the underlying networks to fit our custom task. If you want to follow along step by step in the tutorial, you can fork this public blood cell dataset. Otherwise you can upload your own dataset in any format (more below). To get started make a copy of this Colab Notebook Implementing Detectron2 on Custom Data. Google Colab provides us with free GPU resources so make sure to enable them by checking Runtime → Change runtime type → GPU. To start training our custom detector we install torch==1.5 and torchvision==0.6 - then after importing torch we can check the version of torch and make doubly sure that a GPU is available printing 1.5.0+cu101 True. Then we pip install the Detectron2 library and make a number of submodule imports. !pip install detectron2==0.1.3 -f https://dl.fbaipublicfiles.com/detectron2/wheels/cu101/torch1.5/index.htmlimport detectron2from detectron2.utils.logger import setup_loggersetup_logger()# import some common librariesimport numpy as npimport cv2import randomfrom google.colab.patches import cv2_imshow# import some common detectron2 utilitiesfrom detectron2 import model_zoofrom detectron2.engine import DefaultPredictorfrom detectron2.config import get_cfgfrom detectron2.utils.visualizer import Visualizerfrom detectron2.data import MetadataCatalogfrom detectron2.data.catalog import DatasetCatalog Detectron2 dependencies installed. We download our custom data in COCO JSON format from Roboflow with a single line of code — this is the only line of code you need to change to train on your own custom objects! NOTE: In this tutorial we export object detection data with bounding boxes. Roboflow does not currently support semantic segmentation annotation formats. Sign up to be notified when we do. If you have unlabeled images, you will first need to label them. For free open source labeling tools, we recommend the following guides on getting started with LabelImg or getting started with CVAT annotation tools. Try labeling ~50 images to proceed in this tutorial. To improve your model’s performance later, you will want to label more. You may also consider building a free object detection dataset from Open Images. Once you have labeled data, to get move your data into Roboflow, create a free account and then you can drag your dataset in in any format: (VOC XML, COCO JSON, TensorFlow Object Detection CSV, etc). Once uploaded you can choose preprocessing and augmentation steps: Then, click Generate and Download and you will be able to choose COCO JSON format. When prompted, be sure to select “Show Code Snippet.” This will output a download curl script so you can easily port your data into Colab in the proper format. Then, Detectron2 keeps track of a list of available datasets in a registry, so we must register our custom data with Detectron2 so it can be invoked for training. from detectron2.data.datasets import register_coco_instancesregister_coco_instances("my_dataset_train", {}, "/content/train/_annotations.coco.json", "/content/train")register_coco_instances("my_dataset_val", {}, "/content/valid/_annotations.coco.json", "/content/valid")register_coco_instances("my_dataset_test", {}, "/content/test/_annotations.coco.json", "/content/test") Detectron2 data registered. Detectron2 makes it easy to view our training data to make sure the data has imported correctly. We do so with the following #visualize training datamy_dataset_train_metadata = MetadataCatalog.get("my_dataset_train")dataset_dicts = DatasetCatalog.get("my_dataset_train")import randomfrom detectron2.utils.visualizer import Visualizerfor d in random.sample(dataset_dicts, 3): img = cv2.imread(d["file_name"]) visualizer = Visualizer(img[:, :, ::-1], metadata=my_dataset_train_metadata, scale=0.5) vis = visualizer.draw_dataset_dict(d) cv2_imshow(vis.get_image()[:, :, ::-1]) Looks like our dataset registered correctly. Next we write our custom training configuration. cfg = get_cfg()cfg.merge_from_file(model_zoo.get_config_file("COCO-Detection/faster_rcnn_X_101_32x8d_FPN_3x.yaml"))cfg.DATASETS.TRAIN = ("my_dataset_train",)cfg.DATASETS.TEST = ("my_dataset_val",)cfg.DATALOADER.NUM_WORKERS = 4cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("COCO-Detection/faster_rcnn_X_101_32x8d_FPN_3x.yaml") # Let training initialize from model zoocfg.SOLVER.IMS_PER_BATCH = 4cfg.SOLVER.BASE_LR = 0.001cfg.SOLVER.WARMUP_ITERS = 1000cfg.SOLVER.MAX_ITER = 1500 #adjust up if val mAP is still rising, adjust down if overfitcfg.SOLVER.STEPS = (1000, 1500)cfg.SOLVER.GAMMA = 0.05cfg.MODEL.ROI_HEADS.BATCH_SIZE_PER_IMAGE = 64cfg.MODEL.ROI_HEADS.NUM_CLASSES = 4cfg.TEST.EVAL_PERIOD = 500 The biggest fixtures we have invoked here are the type of object detection model — the large Faster RCNN. Detectron2 allows you many options in determining your model architecture, which you can see in the Detectron2 model zoo. For object detection alone, the following models are available: The other large config choice we have made is the MAX_ITER parameter. This specifies how long the model will train for, you may need to adjust up and down based on the validation metrics you are seeing. Before starting training, we need to make sure that the model validates against our validation set. Unfortunately, this does not happen by default 🤔. We can easily do this by defining our custom trainer based on the Default Trainer with the COCO Evaluator: from detectron2.engine import DefaultTrainerfrom detectron2.evaluation import COCOEvaluatorclass CocoTrainer(DefaultTrainer):@classmethod def build_evaluator(cls, cfg, dataset_name, output_folder=None):if output_folder is None: os.makedirs("coco_eval", exist_ok=True) output_folder = "coco_eval"return COCOEvaluator(dataset_name, cfg, False, output_folder) Ok now that we have our COCO Trainer we can kick off training: The training will run for a while and print out evaluation metrics on our validation set. Curious to learn what mAP is for evaluation? Check out this article on breaking down mAP. Once training is finished, we can move on to evaluation and inference! First, we can display a tensorboard of results to see how the training procedure has performed. There are a lot of metrics of interest in there — most notably total_loss and validation mAP. We run the same evaluation procedure used in our validation mAP on the test set. from detectron2.data import DatasetCatalog, MetadataCatalog, build_detection_test_loaderfrom detectron2.evaluation import COCOEvaluator, inference_on_datasetcfg.MODEL.WEIGHTS = os.path.join(cfg.OUTPUT_DIR, "model_final.pth")cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.85predictor = DefaultPredictor(cfg)evaluator = COCOEvaluator("my_dataset_test", cfg, False, output_dir="./output/")val_loader = build_detection_test_loader(cfg, "my_dataset_test")inference_on_dataset(trainer.model, val_loader, evaluator) Yielding: Accumulating evaluation results...DONE (t=0.03s). Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.592 Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.881 Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.677 Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.178 Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.613 Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.411 Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.392 Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.633 Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.684 Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.257 Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.709 Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.439[06/23 18:39:47 d2.evaluation.coco_evaluation]: Evaluation results for bbox: | AP | AP50 | AP75 | APs | APm | APl ||:------:|:------:|:------:|:------:|:------:|:------:|| 59.169 | 88.066 | 67.740 | 17.805 | 61.333 | 41.070 |[06/23 18:39:47 d2.evaluation.coco_evaluation]: Per-category bbox AP: | category | AP | category | AP | category | AP ||:-----------|:-------|:-----------|:-------|:-----------|:-------|| cells | nan | Platelets | 40.141 | RBC | 60.326 || WBC | 77.039 | | | | | This evaluation will give you a good idea of how your new custom Detectron2 detector will perform in the wild. Again, if you are curious to learn more about these metrics see this post breaking down mAP. And finally, we can run our new custom Detectron2 detector on real images! Note, these are images that the model has never seen cfg.MODEL.WEIGHTS = os.path.join(cfg.OUTPUT_DIR, "model_final.pth")cfg.DATASETS.TEST = ("my_dataset_test", )cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.7 # set the testing threshold for this modelpredictor = DefaultPredictor(cfg)test_metadata = MetadataCatalog.get("my_dataset_test")from detectron2.utils.visualizer import ColorModeimport globfor imageName in glob.glob('/content/test/*jpg'): im = cv2.imread(imageName) outputs = predictor(im) v = Visualizer(im[:, :, ::-1], metadata=test_metadata, scale=0.8 ) out = v.draw_instance_predictions(outputs["instances"].to("cpu")) cv2_imshow(out.get_image()[:, :, ::-1]) Yielding: Our model makes good predictions showing that it has learned how to identify red blood cells, white blood cells, and platelets. You may consider playing with the SCORE_THRESH_TEST to change the confidence threshold that the model requires to make a prediction. You can now save the weights in the os.path.join(cfg.OUTPUT_DIR, "model_final.pt") for future inference by exporting to Google Drive. You can also see the underlying prediction tensor in the outputs object to use elsewhere in your app. Congratulations! Now you know how to train your own custom Detectron2 detector on a completely new domain. Not seeing the results you need to move forward? Object detection models have been improved since the release of the Detectron2 model zoo — consider checking out some of our other tutorials such as How to Train YOLOv5 and How to Train YOLOv4, or this writeup on improvements in YOLO v5.
[ { "code": null, "e": 70, "s": 47, "text": "Overview of Detectron2" }, { "code": null, "e": 101, "s": 70, "text": "Overview of our custom dataset" }, { "code": null, "e": 133, "s": 101, "text": "Install Detectron2 dependencies" }, { "code": null, "e": 182, "s": 133, "text": "Download custom Detectron2 object detection data" }, { "code": null, "e": 217, "s": 182, "text": "Visualize Detectron2 training data" }, { "code": null, "e": 261, "s": 217, "text": "Write our Detectron2 training configuration" }, { "code": null, "e": 285, "s": 261, "text": "Run Detectron2 training" }, { "code": null, "e": 317, "s": 285, "text": "Evaluate Detectron2 performance" }, { "code": null, "e": 357, "s": 317, "text": "Run Detectron2 inference on test images" }, { "code": null, "e": 411, "s": 357, "text": "Colab Notebook Implementing Detectron2 on Custom Data" }, { "code": null, "e": 447, "s": 411, "text": "Public Blood Cell Detection Dataset" }, { "code": null, "e": 749, "s": 447, "text": "Detectron2 is a popular PyTorch based modular computer vision model library. It is the second iteration of Detectron, originally written in Caffe2. The Detectron2 system allows you to plug in custom state of the art computer vision technologies into your workflow. Quoting the Detectron2 release blog:" }, { "code": null, "e": 1124, "s": 749, "text": "Detectron2 includes all the models that were available in the original Detectron, such as Faster R-CNN, Mask R-CNN, RetinaNet, and DensePose. It also features several new models, including Cascade R-CNN, Panoptic FPN, and TensorMask, and we will continue to add more algorithms. We’ve also added features such as synchronous Batch Norm and support for new datasets like LVIS" }, { "code": null, "e": 1387, "s": 1124, "text": "In this post, we review how to train Detectron2 on custom data for specifically object detection. Though, after you finish reading you will be familiar with the Detectron2 ecosystem and you will be able to generalize to other capabilities included in Detectron2." }, { "code": null, "e": 1808, "s": 1387, "text": "We will be training our custom Detectron2 detector on public blood cell detection data hosted for free at Roboflow. The blood cell detection dataset is representative of a small custom object detection dataset that one might collect to construct a custom object detection system. Notably, blood cell detection is not a capability available in Detectron2 — we need to train the underlying networks to fit our custom task." }, { "code": null, "e": 1981, "s": 1808, "text": "If you want to follow along step by step in the tutorial, you can fork this public blood cell dataset. Otherwise you can upload your own dataset in any format (more below)." }, { "code": null, "e": 2197, "s": 1981, "text": "To get started make a copy of this Colab Notebook Implementing Detectron2 on Custom Data. Google Colab provides us with free GPU resources so make sure to enable them by checking Runtime → Change runtime type → GPU." }, { "code": null, "e": 2413, "s": 2197, "text": "To start training our custom detector we install torch==1.5 and torchvision==0.6 - then after importing torch we can check the version of torch and make doubly sure that a GPU is available printing 1.5.0+cu101 True." }, { "code": null, "e": 2496, "s": 2413, "text": "Then we pip install the Detectron2 library and make a number of submodule imports." }, { "code": null, "e": 3097, "s": 2496, "text": "!pip install detectron2==0.1.3 -f https://dl.fbaipublicfiles.com/detectron2/wheels/cu101/torch1.5/index.htmlimport detectron2from detectron2.utils.logger import setup_loggersetup_logger()# import some common librariesimport numpy as npimport cv2import randomfrom google.colab.patches import cv2_imshow# import some common detectron2 utilitiesfrom detectron2 import model_zoofrom detectron2.engine import DefaultPredictorfrom detectron2.config import get_cfgfrom detectron2.utils.visualizer import Visualizerfrom detectron2.data import MetadataCatalogfrom detectron2.data.catalog import DatasetCatalog" }, { "code": null, "e": 3132, "s": 3097, "text": "Detectron2 dependencies installed." }, { "code": null, "e": 3309, "s": 3132, "text": "We download our custom data in COCO JSON format from Roboflow with a single line of code — this is the only line of code you need to change to train on your own custom objects!" }, { "code": null, "e": 3498, "s": 3309, "text": "NOTE: In this tutorial we export object detection data with bounding boxes. Roboflow does not currently support semantic segmentation annotation formats. Sign up to be notified when we do." }, { "code": null, "e": 3839, "s": 3498, "text": "If you have unlabeled images, you will first need to label them. For free open source labeling tools, we recommend the following guides on getting started with LabelImg or getting started with CVAT annotation tools. Try labeling ~50 images to proceed in this tutorial. To improve your model’s performance later, you will want to label more." }, { "code": null, "e": 3920, "s": 3839, "text": "You may also consider building a free object detection dataset from Open Images." }, { "code": null, "e": 4120, "s": 3920, "text": "Once you have labeled data, to get move your data into Roboflow, create a free account and then you can drag your dataset in in any format: (VOC XML, COCO JSON, TensorFlow Object Detection CSV, etc)." }, { "code": null, "e": 4187, "s": 4120, "text": "Once uploaded you can choose preprocessing and augmentation steps:" }, { "code": null, "e": 4270, "s": 4187, "text": "Then, click Generate and Download and you will be able to choose COCO JSON format." }, { "code": null, "e": 4430, "s": 4270, "text": "When prompted, be sure to select “Show Code Snippet.” This will output a download curl script so you can easily port your data into Colab in the proper format." }, { "code": null, "e": 4593, "s": 4430, "text": "Then, Detectron2 keeps track of a list of available datasets in a registry, so we must register our custom data with Detectron2 so it can be invoked for training." }, { "code": null, "e": 4967, "s": 4593, "text": "from detectron2.data.datasets import register_coco_instancesregister_coco_instances(\"my_dataset_train\", {}, \"/content/train/_annotations.coco.json\", \"/content/train\")register_coco_instances(\"my_dataset_val\", {}, \"/content/valid/_annotations.coco.json\", \"/content/valid\")register_coco_instances(\"my_dataset_test\", {}, \"/content/test/_annotations.coco.json\", \"/content/test\")" }, { "code": null, "e": 4995, "s": 4967, "text": "Detectron2 data registered." }, { "code": null, "e": 5120, "s": 4995, "text": "Detectron2 makes it easy to view our training data to make sure the data has imported correctly. We do so with the following" }, { "code": null, "e": 5581, "s": 5120, "text": "#visualize training datamy_dataset_train_metadata = MetadataCatalog.get(\"my_dataset_train\")dataset_dicts = DatasetCatalog.get(\"my_dataset_train\")import randomfrom detectron2.utils.visualizer import Visualizerfor d in random.sample(dataset_dicts, 3): img = cv2.imread(d[\"file_name\"]) visualizer = Visualizer(img[:, :, ::-1], metadata=my_dataset_train_metadata, scale=0.5) vis = visualizer.draw_dataset_dict(d) cv2_imshow(vis.get_image()[:, :, ::-1])" }, { "code": null, "e": 5626, "s": 5581, "text": "Looks like our dataset registered correctly." }, { "code": null, "e": 5675, "s": 5626, "text": "Next we write our custom training configuration." }, { "code": null, "e": 6378, "s": 5675, "text": "cfg = get_cfg()cfg.merge_from_file(model_zoo.get_config_file(\"COCO-Detection/faster_rcnn_X_101_32x8d_FPN_3x.yaml\"))cfg.DATASETS.TRAIN = (\"my_dataset_train\",)cfg.DATASETS.TEST = (\"my_dataset_val\",)cfg.DATALOADER.NUM_WORKERS = 4cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(\"COCO-Detection/faster_rcnn_X_101_32x8d_FPN_3x.yaml\") # Let training initialize from model zoocfg.SOLVER.IMS_PER_BATCH = 4cfg.SOLVER.BASE_LR = 0.001cfg.SOLVER.WARMUP_ITERS = 1000cfg.SOLVER.MAX_ITER = 1500 #adjust up if val mAP is still rising, adjust down if overfitcfg.SOLVER.STEPS = (1000, 1500)cfg.SOLVER.GAMMA = 0.05cfg.MODEL.ROI_HEADS.BATCH_SIZE_PER_IMAGE = 64cfg.MODEL.ROI_HEADS.NUM_CLASSES = 4cfg.TEST.EVAL_PERIOD = 500" }, { "code": null, "e": 6606, "s": 6378, "text": "The biggest fixtures we have invoked here are the type of object detection model — the large Faster RCNN. Detectron2 allows you many options in determining your model architecture, which you can see in the Detectron2 model zoo." }, { "code": null, "e": 6670, "s": 6606, "text": "For object detection alone, the following models are available:" }, { "code": null, "e": 6873, "s": 6670, "text": "The other large config choice we have made is the MAX_ITER parameter. This specifies how long the model will train for, you may need to adjust up and down based on the validation metrics you are seeing." }, { "code": null, "e": 7023, "s": 6873, "text": "Before starting training, we need to make sure that the model validates against our validation set. Unfortunately, this does not happen by default 🤔." }, { "code": null, "e": 7130, "s": 7023, "text": "We can easily do this by defining our custom trainer based on the Default Trainer with the COCO Evaluator:" }, { "code": null, "e": 7502, "s": 7130, "text": "from detectron2.engine import DefaultTrainerfrom detectron2.evaluation import COCOEvaluatorclass CocoTrainer(DefaultTrainer):@classmethod def build_evaluator(cls, cfg, dataset_name, output_folder=None):if output_folder is None: os.makedirs(\"coco_eval\", exist_ok=True) output_folder = \"coco_eval\"return COCOEvaluator(dataset_name, cfg, False, output_folder)" }, { "code": null, "e": 7565, "s": 7502, "text": "Ok now that we have our COCO Trainer we can kick off training:" }, { "code": null, "e": 7745, "s": 7565, "text": "The training will run for a while and print out evaluation metrics on our validation set. Curious to learn what mAP is for evaluation? Check out this article on breaking down mAP." }, { "code": null, "e": 7816, "s": 7745, "text": "Once training is finished, we can move on to evaluation and inference!" }, { "code": null, "e": 7912, "s": 7816, "text": "First, we can display a tensorboard of results to see how the training procedure has performed." }, { "code": null, "e": 8006, "s": 7912, "text": "There are a lot of metrics of interest in there — most notably total_loss and validation mAP." }, { "code": null, "e": 8087, "s": 8006, "text": "We run the same evaluation procedure used in our validation mAP on the test set." }, { "code": null, "e": 8591, "s": 8087, "text": "from detectron2.data import DatasetCatalog, MetadataCatalog, build_detection_test_loaderfrom detectron2.evaluation import COCOEvaluator, inference_on_datasetcfg.MODEL.WEIGHTS = os.path.join(cfg.OUTPUT_DIR, \"model_final.pth\")cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.85predictor = DefaultPredictor(cfg)evaluator = COCOEvaluator(\"my_dataset_test\", cfg, False, output_dir=\"./output/\")val_loader = build_detection_test_loader(cfg, \"my_dataset_test\")inference_on_dataset(trainer.model, val_loader, evaluator)" }, { "code": null, "e": 8601, "s": 8591, "text": "Yielding:" }, { "code": null, "e": 10179, "s": 8601, "text": "Accumulating evaluation results...DONE (t=0.03s). Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.592 Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.881 Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.677 Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.178 Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.613 Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.411 Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.392 Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.633 Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.684 Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.257 Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.709 Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.439[06/23 18:39:47 d2.evaluation.coco_evaluation]: Evaluation results for bbox: | AP | AP50 | AP75 | APs | APm | APl ||:------:|:------:|:------:|:------:|:------:|:------:|| 59.169 | 88.066 | 67.740 | 17.805 | 61.333 | 41.070 |[06/23 18:39:47 d2.evaluation.coco_evaluation]: Per-category bbox AP: | category | AP | category | AP | category | AP ||:-----------|:-------|:-----------|:-------|:-----------|:-------|| cells | nan | Platelets | 40.141 | RBC | 60.326 || WBC | 77.039 | | | | |" }, { "code": null, "e": 10383, "s": 10179, "text": "This evaluation will give you a good idea of how your new custom Detectron2 detector will perform in the wild. Again, if you are curious to learn more about these metrics see this post breaking down mAP." }, { "code": null, "e": 10511, "s": 10383, "text": "And finally, we can run our new custom Detectron2 detector on real images! Note, these are images that the model has never seen" }, { "code": null, "e": 11180, "s": 10511, "text": "cfg.MODEL.WEIGHTS = os.path.join(cfg.OUTPUT_DIR, \"model_final.pth\")cfg.DATASETS.TEST = (\"my_dataset_test\", )cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.7 # set the testing threshold for this modelpredictor = DefaultPredictor(cfg)test_metadata = MetadataCatalog.get(\"my_dataset_test\")from detectron2.utils.visualizer import ColorModeimport globfor imageName in glob.glob('/content/test/*jpg'): im = cv2.imread(imageName) outputs = predictor(im) v = Visualizer(im[:, :, ::-1], metadata=test_metadata, scale=0.8 ) out = v.draw_instance_predictions(outputs[\"instances\"].to(\"cpu\")) cv2_imshow(out.get_image()[:, :, ::-1])" }, { "code": null, "e": 11190, "s": 11180, "text": "Yielding:" }, { "code": null, "e": 11318, "s": 11190, "text": "Our model makes good predictions showing that it has learned how to identify red blood cells, white blood cells, and platelets." }, { "code": null, "e": 11451, "s": 11318, "text": "You may consider playing with the SCORE_THRESH_TEST to change the confidence threshold that the model requires to make a prediction." }, { "code": null, "e": 11585, "s": 11451, "text": "You can now save the weights in the os.path.join(cfg.OUTPUT_DIR, \"model_final.pt\") for future inference by exporting to Google Drive." }, { "code": null, "e": 11687, "s": 11585, "text": "You can also see the underlying prediction tensor in the outputs object to use elsewhere in your app." }, { "code": null, "e": 11794, "s": 11687, "text": "Congratulations! Now you know how to train your own custom Detectron2 detector on a completely new domain." } ]
Which collection classes are thread-safe in Java?
A thread-safe class is a class that guarantees the internal state of the class as well as returned values from methods, are correct while invoked concurrently from multiple threads. The collection classes that are thread-safe in Java are Stack, Vector, Properties, Hashtable, etc. The Stack class in Java implements the stack data structure that is based on the principle of LIFO. So, the Stack class can support many operations such as push, pop, peek, search, empty, etc. import java.util.*; public class StackTest { public static void main (String[] args) { Stack<Integer> stack = new Stack<Integer>(); stack.push(5); stack.push(7); stack.push(9); Integer num1 = (Integer)stack.pop(); System.out.println("The element popped is: " + num1); Integer num2 = (Integer)stack.peek(); System.out.println(" The element on stack top is: " + num2); } } The element popped is: 9 The element on stack top is: 7 An array of objects that grow as required is implemented by the Vector class in Java. The Vector class can support the methods like add(), remove(), get(), elementAt(), size(), etc import java.util.*; public class VectorTest { public static void main(String[] arg) { Vector vector = new Vector(); vector.add(9); vector.add(3); vector.add("ABC"); vector.add(1); vector.add("DEF"); System.out.println("The vector is: " + vector); vector.remove(1); System.out.println("The vector after an element is removed is: " + vector); } } The vector is: [9, 3, ABC, 1, DEF] The vector after an element is removed is: [9, ABC, 1, DEF]
[ { "code": null, "e": 1343, "s": 1062, "text": "A thread-safe class is a class that guarantees the internal state of the class as well as returned values from methods, are correct while invoked concurrently from multiple threads. The collection classes that are thread-safe in Java are Stack, Vector, Properties, Hashtable, etc." }, { "code": null, "e": 1536, "s": 1343, "text": "The Stack class in Java implements the stack data structure that is based on the principle of LIFO. So, the Stack class can support many operations such as push, pop, peek, search, empty, etc." }, { "code": null, "e": 1961, "s": 1536, "text": "import java.util.*;\npublic class StackTest {\n public static void main (String[] args) {\n Stack<Integer> stack = new Stack<Integer>();\n stack.push(5);\n stack.push(7);\n stack.push(9);\n Integer num1 = (Integer)stack.pop();\n System.out.println(\"The element popped is: \" + num1);\n Integer num2 = (Integer)stack.peek();\n System.out.println(\" The element on stack top is: \" + num2);\n }\n}" }, { "code": null, "e": 2017, "s": 1961, "text": "The element popped is: 9\nThe element on stack top is: 7" }, { "code": null, "e": 2198, "s": 2017, "text": "An array of objects that grow as required is implemented by the Vector class in Java. The Vector class can support the methods like add(), remove(), get(), elementAt(), size(), etc" }, { "code": null, "e": 2603, "s": 2198, "text": "import java.util.*;\npublic class VectorTest {\n public static void main(String[] arg) {\n Vector vector = new Vector();\n vector.add(9);\n vector.add(3);\n vector.add(\"ABC\");\n vector.add(1);\n vector.add(\"DEF\");\n System.out.println(\"The vector is: \" + vector);\n vector.remove(1);\n System.out.println(\"The vector after an element is removed is: \" + vector);\n }\n}" }, { "code": null, "e": 2698, "s": 2603, "text": "The vector is: [9, 3, ABC, 1, DEF]\nThe vector after an element is removed is: [9, ABC, 1, DEF]" } ]
SLF4J - Error Messages
In this chapter, we will discuss the various error messages or warning we get while working with SLF4J and the causes/ meanings of those messages. This is a warning which is caused when there are no SLF4J bindings provided in the classpath. Following is the complete warning − SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. To resolve this, you need to add either of the logging framework bindings. This is explained in the Hello world chapter of this tutorial. Note − This occurs in versions of SLF4J which are between 1.6.0 and 1.8.0-beta2. In slf4j-1.8.0-beta2, the above warning is more clear saying “No SLF4J providers were found”. Following is the complete warning − SLF4J: No SLF4J providers were found. SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#noProviders for further details. If you are using SLF4J 1.8 version and you have the bindings of previous versions in the classpath but not the bindings of 1.8 you will see a warning as shown below. SLF4J: No SLF4J providers were found. SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#noProviders for further details. SLF4J: Class path contains SLF4J bindings targeting slf4j-api versions prior to 1.8. SLF4J: Ignoring binding found at [jar:file:/C:/Users/Tutorialspoint/Desktop/Latest%20Tutorials/SLF4J%20Tutorial/ slf4j-1.7.25/slf4j-jdk14-1.7.25.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: See http://www.slf4j.org/codes.html#ignoredBindings for an explanation. If you are working with slf4j-jcl and if you have only slf4j-jcl.jar in your classpath, you will get an exception such as the one given below. Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory at org.slf4j.impl.JCLLoggerFactory.getLogger(JCLLoggerFactory.java:77) at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:358) at SLF4JExample.main(SLF4JExample.java:8) Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) ... 3 more To resolve this, you need to add commons-logging.jar to your classpath. The binding slf4j-jcl.jar redirects calls of the slf4j logger to JCL and the jcl-over-slf4j.jar redirects calls of JCL logger to slf4j. Therefore, you cannot have both in the classpath of your project. If you do so, you will get an exception such as the one given below. SLF4J: Detected both jcl-over-slf4j.jar AND bound slf4j-jcl.jar on the class path, preempting StackOverflowError. SLF4J: See also http://www.slf4j.org/codes.html#jclDelegationLoop for more details. Exception in thread "main" java.lang.ExceptionInInitializerError at org.slf4j.impl.StaticLoggerBinder.<init>(StaticLoggerBinder.java:71) at org.slf4j.impl.StaticLoggerBinder.<clinit>(StaticLoggerBinder.java:42) at org.slf4j.LoggerFactory.bind(LoggerFactory.java:150) at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:124) at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:412) at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:357) at SLF4JExample.main(SLF4JExample.java:8) Caused by: java.lang.IllegalStateException: Detected both jcl-over-slf4j.jar AND bound slf4j-jcl.jar on the class path, preempting StackOverflowError. See also http://www.slf4j.org/codes.html#jclDelegationLoop for more details. at org.slf4j.impl.JCLLoggerFactory.<clinit>(JCLLoggerFactory.java:54) ... 7 more To resolve this, delete either of the jar files. You can create a Logger object by − Passing the name of the logger to be created as an argument to the getLogger() method. Passing the name of the logger to be created as an argument to the getLogger() method. Passing a class as an argument to this method. Passing a class as an argument to this method. If you are trying to create the logger factory object by passing a class as an argument, and if you have set the system property slf4j.detectLoggerNameMismatch to true, then the name of the class you pass as an argument to the getLogger() method and the class you use should be the same otherwise you will receive the following warning − “Detected logger name mismatch. Consider the following example. import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SLF4JExample { public static void main(String[] args) { System.setProperty("slf4j.detectLoggerNameMismatch", "true"); //Creating the Logger object Logger logger = LoggerFactory.getLogger(Sample.class); //Logging the information logger.info("Hi Welcome to Tutorilspoint"); } } Here, we have set the slf4j.detectLoggerNameMismatch property to true. The name of the class we used is SLF4JExample and the class name we have passed to the getLogger() method is Sample since they both are not equal we will get the following warning. SLF4J: Detected logger name mismatch. Given name: "Sample"; computed name: "SLF4JExample". SLF4J: See http://www.slf4j.org/codes.html#loggerNameMismatch for an explanation Dec 10, 2018 12:43:00 PM SLF4JExample main INFO: Hi Welcome to Tutorilspoint Note − This occurs after slf4j 1.7.9 You should have only one binding in the classpath. If you have more than one binding, you will get a warning listing the bindings and the locations of them. For suppose, if we have the bindings slf4j-jdk14.jar and slf4j-nop.jar in the classpath we will get the following warning. SLF4J: Class path contains multiple SLF4J bindings. SLF4J: Found binding in [jar:file:/C:/Users/Tutorialspoint/Desktop/Latest%20Tutorials/SLF4J%20Tutorial/ slf4j-1.7.25/slf4j-nop-1.7.25.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: Found binding in [jar:file:/C:/Users/Tutorialspoint/Desktop/Latest%20Tutorials/SLF4J%20Tutorial/ slf4j-1.7.25/slf4j-jdk14-1.7.25.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation. SLF4J: Actual binding is of type [org.slf4j.helpers.NOPLoggerFactory] To redirect the log4j logger calls to slf4j, you need to use log4j-over-slf4j.jar binding and if you want to redirect slf4j calls to log4j, you need to use slf4j-log4j12.jar binding. Therefore, you cannot have both in the classpath. If you do, you will get the following exception. SLF4J: Detected both log4j-over-slf4j.jar AND bound slf4j-log4j12.jar on the class path, preempting StackOverflowError. SLF4J: See also http://www.slf4j.org/codes.html#log4jDelegationLoop for more details. Exception in thread "main" java.lang.ExceptionInInitializerError at org.slf4j.impl.StaticLoggerBinder.<init>(StaticLoggerBinder.java:72) at org.slf4j.impl.StaticLoggerBinder.<clinit>(StaticLoggerBinder.java:45) at org.slf4j.LoggerFactory.bind(LoggerFactory.java:150) at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:124) at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:412) at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:357) at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:383) at SLF4JExample.main(SLF4JExample.java:8) Caused by: java.lang.IllegalStateException: Detected both log4j-over-slf4j.jar AND bound slf4j-log4j12.jar on the class path, preempting StackOverflowError. See also http://www.slf4j.org/codes.html#log4jDelegationLoop for more details. Print Add Notes Bookmark this page
[ { "code": null, "e": 1932, "s": 1785, "text": "In this chapter, we will discuss the various error messages or warning we get while working with SLF4J and the causes/ meanings of those messages." }, { "code": null, "e": 2026, "s": 1932, "text": "This is a warning which is caused when there are no SLF4J bindings provided in the classpath." }, { "code": null, "e": 2062, "s": 2026, "text": "Following is the complete warning −" }, { "code": null, "e": 2273, "s": 2062, "text": "SLF4J: Failed to load class \"org.slf4j.impl.StaticLoggerBinder\".\nSLF4J: Defaulting to no-operation (NOP) logger implementation\nSLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further\ndetails.\n" }, { "code": null, "e": 2411, "s": 2273, "text": "To resolve this, you need to add either of the logging framework bindings. This is explained in the Hello world chapter of this tutorial." }, { "code": null, "e": 2492, "s": 2411, "text": "Note − This occurs in versions of SLF4J which are between 1.6.0 and 1.8.0-beta2." }, { "code": null, "e": 2586, "s": 2492, "text": "In slf4j-1.8.0-beta2, the above warning is more clear saying “No SLF4J providers were found”." }, { "code": null, "e": 2622, "s": 2586, "text": "Following is the complete warning −" }, { "code": null, "e": 2799, "s": 2622, "text": "SLF4J: No SLF4J providers were found.\nSLF4J: Defaulting to no-operation (NOP) logger implementation\nSLF4J: See http://www.slf4j.org/codes.html#noProviders for further details.\n" }, { "code": null, "e": 2965, "s": 2799, "text": "If you are using SLF4J 1.8 version and you have the bindings of previous versions in the classpath but not the bindings of 1.8 you will see a warning as shown below." }, { "code": null, "e": 3497, "s": 2965, "text": "SLF4J: No SLF4J providers were found.\nSLF4J: Defaulting to no-operation (NOP) logger implementation\nSLF4J: See http://www.slf4j.org/codes.html#noProviders for further details.\nSLF4J: Class path contains SLF4J bindings targeting slf4j-api versions prior to\n1.8.\nSLF4J: Ignoring binding found at\n[jar:file:/C:/Users/Tutorialspoint/Desktop/Latest%20Tutorials/SLF4J%20Tutorial/\nslf4j-1.7.25/slf4j-jdk14-1.7.25.jar!/org/slf4j/impl/StaticLoggerBinder.class]\nSLF4J: See http://www.slf4j.org/codes.html#ignoredBindings for an explanation.\n" }, { "code": null, "e": 3640, "s": 3497, "text": "If you are working with slf4j-jcl and if you have only slf4j-jcl.jar in your classpath, you will get an exception such as the one given below." }, { "code": null, "e": 4247, "s": 3640, "text": "Exception in thread \"main\" java.lang.NoClassDefFoundError:\norg/apache/commons/logging/LogFactory\n at org.slf4j.impl.JCLLoggerFactory.getLogger(JCLLoggerFactory.java:77)\n at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:358)\n at SLF4JExample.main(SLF4JExample.java:8)\nCaused by: java.lang.ClassNotFoundException:\norg.apache.commons.logging.LogFactory\n at java.net.URLClassLoader.findClass(Unknown Source)\n at java.lang.ClassLoader.loadClass(Unknown Source)\n at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)\n at java.lang.ClassLoader.loadClass(Unknown Source)\n ... 3 more\n" }, { "code": null, "e": 4319, "s": 4247, "text": "To resolve this, you need to add commons-logging.jar to your classpath." }, { "code": null, "e": 4590, "s": 4319, "text": "The binding slf4j-jcl.jar redirects calls of the slf4j logger to JCL and the jcl-over-slf4j.jar redirects calls of JCL logger to slf4j. Therefore, you cannot have both in the classpath of your project. If you do so, you will get an exception such as the one given below." }, { "code": null, "e": 5637, "s": 4590, "text": "SLF4J: Detected both jcl-over-slf4j.jar AND bound slf4j-jcl.jar on the class\npath, preempting StackOverflowError.\nSLF4J: See also http://www.slf4j.org/codes.html#jclDelegationLoop for more\ndetails.\nException in thread \"main\" java.lang.ExceptionInInitializerError\n at org.slf4j.impl.StaticLoggerBinder.<init>(StaticLoggerBinder.java:71)\n at org.slf4j.impl.StaticLoggerBinder.<clinit>(StaticLoggerBinder.java:42)\n at org.slf4j.LoggerFactory.bind(LoggerFactory.java:150)\n at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:124)\n at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:412)\n at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:357)\n at SLF4JExample.main(SLF4JExample.java:8)\nCaused by: java.lang.IllegalStateException: Detected both jcl-over-slf4j.jar\nAND bound slf4j-jcl.jar on the class path, preempting StackOverflowError. See\nalso http://www.slf4j.org/codes.html#jclDelegationLoop for more details.\n at org.slf4j.impl.JCLLoggerFactory.<clinit>(JCLLoggerFactory.java:54)\n ... 7 more\n" }, { "code": null, "e": 5686, "s": 5637, "text": "To resolve this, delete either of the jar files." }, { "code": null, "e": 5722, "s": 5686, "text": "You can create a Logger object by −" }, { "code": null, "e": 5809, "s": 5722, "text": "Passing the name of the logger to be created as an argument to the getLogger() method." }, { "code": null, "e": 5896, "s": 5809, "text": "Passing the name of the logger to be created as an argument to the getLogger() method." }, { "code": null, "e": 5943, "s": 5896, "text": "Passing a class as an argument to this method." }, { "code": null, "e": 5990, "s": 5943, "text": "Passing a class as an argument to this method." }, { "code": null, "e": 6328, "s": 5990, "text": "If you are trying to create the logger factory object by passing a class as an argument, and if you have set the system property slf4j.detectLoggerNameMismatch to true, then the name of the class you pass as an argument to the getLogger() method and the class you use should be the same otherwise you will receive the following warning −" }, { "code": null, "e": 6360, "s": 6328, "text": "“Detected logger name mismatch." }, { "code": null, "e": 6392, "s": 6360, "text": "Consider the following example." }, { "code": null, "e": 6782, "s": 6392, "text": "import org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\npublic class SLF4JExample {\n public static void main(String[] args) {\n System.setProperty(\"slf4j.detectLoggerNameMismatch\", \"true\");\n \n //Creating the Logger object\n Logger logger = LoggerFactory.getLogger(Sample.class);\n\n //Logging the information\n logger.info(\"Hi Welcome to Tutorilspoint\");\n }\n}" }, { "code": null, "e": 7034, "s": 6782, "text": "Here, we have set the slf4j.detectLoggerNameMismatch property to true. The name of the class we used is SLF4JExample and the class name we have passed to the getLogger() method is Sample since they both are not equal we will get the following warning." }, { "code": null, "e": 7284, "s": 7034, "text": "SLF4J: Detected logger name mismatch. Given name: \"Sample\"; computed name:\n\"SLF4JExample\".\nSLF4J: See http://www.slf4j.org/codes.html#loggerNameMismatch for an\nexplanation\nDec 10, 2018 12:43:00 PM SLF4JExample main\nINFO: Hi Welcome to Tutorilspoint\n" }, { "code": null, "e": 7321, "s": 7284, "text": "Note − This occurs after slf4j 1.7.9" }, { "code": null, "e": 7478, "s": 7321, "text": "You should have only one binding in the classpath. If you have more than one binding, you will get a warning listing the bindings and the locations of them." }, { "code": null, "e": 7601, "s": 7478, "text": "For suppose, if we have the bindings slf4j-jdk14.jar and slf4j-nop.jar in the classpath we will get the following warning." }, { "code": null, "e": 8167, "s": 7601, "text": "SLF4J: Class path contains multiple SLF4J bindings.\nSLF4J: Found binding in\n[jar:file:/C:/Users/Tutorialspoint/Desktop/Latest%20Tutorials/SLF4J%20Tutorial/\nslf4j-1.7.25/slf4j-nop-1.7.25.jar!/org/slf4j/impl/StaticLoggerBinder.class]\nSLF4J: Found binding in\n[jar:file:/C:/Users/Tutorialspoint/Desktop/Latest%20Tutorials/SLF4J%20Tutorial/\nslf4j-1.7.25/slf4j-jdk14-1.7.25.jar!/org/slf4j/impl/StaticLoggerBinder.class]\nSLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an\nexplanation.\nSLF4J: Actual binding is of type [org.slf4j.helpers.NOPLoggerFactory]\n" }, { "code": null, "e": 8350, "s": 8167, "text": "To redirect the log4j logger calls to slf4j, you need to use log4j-over-slf4j.jar binding and if you want to redirect slf4j calls to log4j, you need to use slf4j-log4j12.jar binding." }, { "code": null, "e": 8449, "s": 8350, "text": "Therefore, you cannot have both in the classpath. If you do, you will get the following exception." }, { "code": null, "e": 9489, "s": 8449, "text": "SLF4J: Detected both log4j-over-slf4j.jar AND bound slf4j-log4j12.jar on the\nclass path, preempting StackOverflowError.\nSLF4J: See also http://www.slf4j.org/codes.html#log4jDelegationLoop for more\ndetails.\nException in thread \"main\" java.lang.ExceptionInInitializerError\n at org.slf4j.impl.StaticLoggerBinder.<init>(StaticLoggerBinder.java:72)\n at org.slf4j.impl.StaticLoggerBinder.<clinit>(StaticLoggerBinder.java:45)\n at org.slf4j.LoggerFactory.bind(LoggerFactory.java:150)\n at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:124)\n at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:412)\n at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:357)\n at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:383)\n at SLF4JExample.main(SLF4JExample.java:8)\nCaused by: java.lang.IllegalStateException: Detected both log4j-over-slf4j.jar\nAND bound slf4j-log4j12.jar on the class path, preempting StackOverflowError.\nSee also http://www.slf4j.org/codes.html#log4jDelegationLoop for more details.\n" }, { "code": null, "e": 9496, "s": 9489, "text": " Print" }, { "code": null, "e": 9507, "s": 9496, "text": " Add Notes" } ]
Scikeras Tutorial: A Multi Input Multi Output(MIMO) Wrapper for CapsNet Hyperparameter Tuning with Keras | by Anshuman Sabath | Towards Data Science
Use of Hyperparameter Tuning utilities, defined in sklearn, for Deep Learning models developed in Keras has been a challenge; especially for models defined using the Keras API. Scikeras, however, is here to change that. In this article we explore creating a wrapper for non-sequential model(CapsNet) with multiple inputs and multiple outputs (MIMO estimator), and fitting this classifier with GridSearchCV. If you are familiar with Machine Learning, you must have heard of hyperparameters. Readers acquainted with sklearn, keras and hyperparameter tuning in sklearn, can skip this part. For the link to github repo scroll to the end. To give a refresher anyways, hyperparameters are a set of properties of any machine learning or deep learning model that the users can specify to change the way a model is trained. These are not learnable (the nomenclature for learnable properties is parameters or weights), i.e., they are user-defined. Often, hyperparameters control the way the model is trained, for example, learning rate (α) or the type of regularization used. Hyperparameter Tuning/Optimization is one of the crucial steps in designing a Machine Learning or Deep Learning model. This step often demands considerable knowledge of how the model is trained and how the model applies to the problem being solved, especially when done manually. Moreover, manual tuning puts an overhead on the Data Scientist for keeping tab of all the hyperparameters they may have tried. This is where automated hyperparameter tuning with the help of scikit-learn(sklearn) comes into play. Scikit-learn provides multiple APIs under sklearn.model_selection for hyperparameter tuning. But, the caveat with using sklearn is, it is largely used for Machine Learning models only — there are no deep learning models defined in the API. Fortunately, Keras API, which is popularly used among the practitioners of Deep Learning for defining and training Deep Learning models in a simplified manner, has sklearn wrapper classes for Deep Learning models defined in Keras. What this meant is that, one can write one’s own Deep Learning model in Keras, and then convert it into a sklearn-like model using these wrappers. Sounds great so far, right? Well... not so fast. The wrappers defined under Keras(or tensorflow.kerasfor that matter), until now, can wrap your model either as a classifier ( KerasClassifier) or a regressor ( KerasRegressor). Moreover, if you wanted to wrap a model defined using Keras Functional API, i.e., not a sequential model [Read more about Sequential vs Functional API in Keras], that was not possible either. So, this was a limitation when one wanted to tune the hyperparameters of a more complicated deep learning model using the sklearn APIs (and the reason why I am so excited to write this article.) For those unfamiliar with the wrappers, the use of wrappers is illustrated in a code example below. We define get_model()function that returns a compiled Keras model. The model is then wrapped into clfusing KerasClassifier .The clf created in the example has all the attributes and members of a sklearn classifier and can be used as such. SciKeras is the successor to tf.keras.wrappers.scikit_learn, and offers many improvements over the TensorFlow version of the wrappers. Scikeras offers many much awaited APIs that enable developers to interface their tensorflow models with sklearn, including Functional API based models as well as subclassed Keras models. For a full list of new offerings, refer this. The package can be easily installed with a simple pip install, and wrappers imported from scikeras.wrappers. pip install scikerasfrom scikeras.wrappers import KerasClassifier, KerasRegressor These wrappers are largely backwards compatible with KerasClassifieror KerasRegressorif they already being used in your code, except for the renaming of build_fn parameter as model. clf = KerasClassifier(build_fn=get_model,...) #Oldclf = KerasClassifier(model=get_model,....) #New Another change to take note for hyperparameter tuning using these wrappers is defining tunable parameters in get_model with a default value is not encouraged. Users are instead expected to declare all tunable arguments to the get_modelfunction as keyword arguments to the wrapper constructor. #def get_model(param_1=value_1, param_2=value_2,...): -> Discourageddef get_model(param_1, param_2,...): ... ... return modelclf = KerasClassifier(build_fn=get_model, param_1=value_1, param_2=value_2, ...)clf = KerasClassifier(build_fn=get_model, model__param_1=value_1, model__param_2=value_2, ...) Appending model__ before the arguments also reserves the parameters to be passed to the get_model function (see Routed Parameters). Few more changes to the code may be needed depending on whether categorical_cross_entropy is used, and the way fit is called (refer the complete list). We will not delve into details of those implementations. Scikit-Learn natively supports multiple outputs, although it technically requires them to be arrays of equal length (see docs for Scikit-Learn’s MultiOutputClassifier). Scikit-Learn has no support for multiple inputs. Many non-trivial Deep Learning models used in research and industry have either multiple inputs or multiple outputs, or both. Such models can be easily described and trained in Keras. However, using such models in sklearn becomes a challenge, since, sklearn expects the Xand y of a model to be a single n-dimensional numpy array (multiple arrays of same length allowed for the y). Now, the concatenation to a single array can be straightforward if all of the inputs/ouputs are of the same shape. However, this can quickly get messy when the inputs and outputs have different shapes, as is the case with a CapsNet model (more on this later). In order to have multiple inputs and/or multiple outputs for a model, SciKeras allows the use of custom data transformers. The examples given in the official documentation, for achieving this with input and/or output lists with arrays of unmatching shapes, employ a reshaping of the inputs/outputs from an array of shape[E_dim1,E_dim2,E_dim3,...] to [E_dim1, E_dim2*E_dim3*...] , where Ecan either be input or output, effectively reshaping all the inputs to a 2-dimensional numpy array. These custom transformers, depending on whether it is used for transforming X (features) or y (targets), can then be used from a custom estimator to override either scikeras.wrappers.BaseWrappers.feature_encoder() or scikeras.wrappers.BaseWrappers.target_encoder() , respectively. Moreover, for models with multiple outputs, defining a custom scorer is advisable, especially when the outputs have different shapes or use different metrics. At the risk of oversimplifying, CapsNet is a novel architecture proposed by Geoffrey Hinton et al. in late 2017, where they designed a network that could perform without the use of Pooling layers. This is achieved by using capsules, which perform a form of ‘inverse rendering’, which is learnt by dynamic routing-by-agreement. For this tutorial we will not be going into the theory of CapsNet — those interested in theory can read this article for a working understanding, and refer to the original paper [1] for more details. What we are interested in is the implementation of the Capsule Network, and its overall architecture, since, that is what we want to wrap into scikeras. The implementation used in this tutorial is based off of the code made available openly by Xifeng Guo. The illustration shows the high level version of the architecture implemented, showing the approximate flows of inputs and outputs. The Capsule Layers need to be defined by the user or imported. Dynamic Routing of Capsules via routing-by-agreement defines a custom flow of data within the model (implemented in the user-defined Capsule Layer) The outputs are not of the same type — One-Hot-Encoded(OHE) vector and flattened image — instead of both being labels(for classifiers) or continuous values(for regressor). Building up on our discussion so far, the wrapper would need to override both BaseWrappers.feature_encoder() and BaseWrappers.target_encoder() . Depending on the type of transformation required, we could either resort to writing our custom transformer, or use one of the many transformers that are already offered in sklearn.preprocessing . For this tutorial, we will demonstrate both the ways of transformation — we will write a custom transformer for the outputs and use a library transformer for the inputs. Further, since the mechanism of training of the Keras model can not be strictly mirrored with that of a classifier or regressor (due to the reconstruction module), we will sub-class the BaseWrapper while defining our estimator. Moreover, for the performance comparison of the model we need to consider two outputs — hence, a custom scorer will also be needed. For our specific implementation, the outputs needed by the Keras model has to be in the form [y_true, X_true], while sklearn expects a numpy array to be fed as targets array. The transformer we define needs to be able to interface seamlessly between the two. This is achieved by fitting the transformer to the outputs in fitmethod, and then usingtransform method that reshapes the output into a list of arrays as expected by Keras, and an inverse_transform method that reshapes the output as expected by sklearn. We create our custom transformer MultiOutputTransformer , by sub-classing or inheriting from BaseEstimator and TransformerMixin classes of sklearn, and define a fit method. This method could be used to incorporate multiple library encoder, (like LabelEncoder, OneHotEncoder), into a single transformer, as demonstrated in the official tutorial, depending on the type of outputs. These encoders can be fit to the inputs so that the transform and inverse_transform methods can work appropriately. In this function, it is necessary to set the self.n_outputs_expected_ parameter to inform scikeras about the outputs from fit, while other parameters in meta can be optionally set. This function must return self . In the code presented here, however, I have tried to demonstrate the implementation when there is no transformation needed for the targets except for a possible separation and a rearrangement. It should be noted that it would be possible to define a FunctionTransformer over an identity function to achieve this as well (which is demonstrated in next section). The get_metadata function is optionally defined for model_build_fn where meta parameter is accepted. Specific to this code, the transform method is straightforward, in the inverse_transform method, we need to define our custom inverse transformation, since we do not have any library encoders to rely on. For the input transformer, we will use a library transformer already available in sklearn.preprocessing — the FunctionTransformer . For the FunctionTransformer , it is possible to define a lambda function into the func parameter of transformer constructor. But, having a lambda function could cause issues with pickle. So, we instead define a separate function to pass into FunctionTransformer. To finish up the wrapper, we subclass BaseWrapper as mentioned previously, and override feature_encoder, scorer, and target_encoder functions. Note that, in the scorer function, we only evaluate the output from the Capsules layer, since this is the metric on which we would want our cross-validation epochs to optimize the network. The next steps are pretty similar to the first example using the wrappers in tf.keras. We instantiate MIMOEstimator using get_model and pass the (hyper)parameters to get_model as routed parameters (with model__prefix). These routed arguments also include those hyperparameters that we would like to tune using grid-search. Next, we define the params dict containing the hyperparameters list and the corresponding values to try out as key-value pairs. We use the clf as a estimator to create GridSearchCV object, and then fit it to the data. Care must be taken while specifying the cv argument for the GridSearchCV to achieve a suitable relation between the number of training examples (n), the batch size(b), and the number of cross-validation batches (cv)— n should be completely divisible by cv *b. The results of the grid-search are accumulated in gs_res after the fit operation. The best estimator can be obtained using best_estimator_ attribute of gs_res, similarly, the best_score_ gives the best score, and best_params_ gives the best fit of hyperparameters. So, there it is — how we can write a custom wrapper with minimal coding to use Keras models in conjunction with sklearn API. Hope you found it helpful. If you have any suggestions or questions, please tell me about them in the comments section, especially if there is a usecase/model where this wrapping fails. You can find the full code implementation below with a few more resources. > Full code of this implementation can be found here.> A tutorial on custom Keras Layers can be found here and here.> Implemented CapsNet layers can be found here. [1] Sabour S, Frosst N, Hinton GE, Dynamic routing between capsules(2017), Advances in neural information processing systems 2017 (pp. 3856–3866)
[ { "code": null, "e": 579, "s": 172, "text": "Use of Hyperparameter Tuning utilities, defined in sklearn, for Deep Learning models developed in Keras has been a challenge; especially for models defined using the Keras API. Scikeras, however, is here to change that. In this article we explore creating a wrapper for non-sequential model(CapsNet) with multiple inputs and multiple outputs (MIMO estimator), and fitting this classifier with GridSearchCV." }, { "code": null, "e": 1238, "s": 579, "text": "If you are familiar with Machine Learning, you must have heard of hyperparameters. Readers acquainted with sklearn, keras and hyperparameter tuning in sklearn, can skip this part. For the link to github repo scroll to the end. To give a refresher anyways, hyperparameters are a set of properties of any machine learning or deep learning model that the users can specify to change the way a model is trained. These are not learnable (the nomenclature for learnable properties is parameters or weights), i.e., they are user-defined. Often, hyperparameters control the way the model is trained, for example, learning rate (α) or the type of regularization used." }, { "code": null, "e": 1747, "s": 1238, "text": "Hyperparameter Tuning/Optimization is one of the crucial steps in designing a Machine Learning or Deep Learning model. This step often demands considerable knowledge of how the model is trained and how the model applies to the problem being solved, especially when done manually. Moreover, manual tuning puts an overhead on the Data Scientist for keeping tab of all the hyperparameters they may have tried. This is where automated hyperparameter tuning with the help of scikit-learn(sklearn) comes into play." }, { "code": null, "e": 2365, "s": 1747, "text": "Scikit-learn provides multiple APIs under sklearn.model_selection for hyperparameter tuning. But, the caveat with using sklearn is, it is largely used for Machine Learning models only — there are no deep learning models defined in the API. Fortunately, Keras API, which is popularly used among the practitioners of Deep Learning for defining and training Deep Learning models in a simplified manner, has sklearn wrapper classes for Deep Learning models defined in Keras. What this meant is that, one can write one’s own Deep Learning model in Keras, and then convert it into a sklearn-like model using these wrappers." }, { "code": null, "e": 2978, "s": 2365, "text": "Sounds great so far, right? Well... not so fast. The wrappers defined under Keras(or tensorflow.kerasfor that matter), until now, can wrap your model either as a classifier ( KerasClassifier) or a regressor ( KerasRegressor). Moreover, if you wanted to wrap a model defined using Keras Functional API, i.e., not a sequential model [Read more about Sequential vs Functional API in Keras], that was not possible either. So, this was a limitation when one wanted to tune the hyperparameters of a more complicated deep learning model using the sklearn APIs (and the reason why I am so excited to write this article.)" }, { "code": null, "e": 3317, "s": 2978, "text": "For those unfamiliar with the wrappers, the use of wrappers is illustrated in a code example below. We define get_model()function that returns a compiled Keras model. The model is then wrapped into clfusing KerasClassifier .The clf created in the example has all the attributes and members of a sklearn classifier and can be used as such." }, { "code": null, "e": 3452, "s": 3317, "text": "SciKeras is the successor to tf.keras.wrappers.scikit_learn, and offers many improvements over the TensorFlow version of the wrappers." }, { "code": null, "e": 3794, "s": 3452, "text": "Scikeras offers many much awaited APIs that enable developers to interface their tensorflow models with sklearn, including Functional API based models as well as subclassed Keras models. For a full list of new offerings, refer this. The package can be easily installed with a simple pip install, and wrappers imported from scikeras.wrappers." }, { "code": null, "e": 3876, "s": 3794, "text": "pip install scikerasfrom scikeras.wrappers import KerasClassifier, KerasRegressor" }, { "code": null, "e": 4058, "s": 3876, "text": "These wrappers are largely backwards compatible with KerasClassifieror KerasRegressorif they already being used in your code, except for the renaming of build_fn parameter as model." }, { "code": null, "e": 4159, "s": 4058, "text": "clf = KerasClassifier(build_fn=get_model,...) #Oldclf = KerasClassifier(model=get_model,....) #New" }, { "code": null, "e": 4452, "s": 4159, "text": "Another change to take note for hyperparameter tuning using these wrappers is defining tunable parameters in get_model with a default value is not encouraged. Users are instead expected to declare all tunable arguments to the get_modelfunction as keyword arguments to the wrapper constructor." }, { "code": null, "e": 4761, "s": 4452, "text": "#def get_model(param_1=value_1, param_2=value_2,...): -> Discourageddef get_model(param_1, param_2,...): ... ... return modelclf = KerasClassifier(build_fn=get_model, param_1=value_1, param_2=value_2, ...)clf = KerasClassifier(build_fn=get_model, model__param_1=value_1, model__param_2=value_2, ...)" }, { "code": null, "e": 5102, "s": 4761, "text": "Appending model__ before the arguments also reserves the parameters to be passed to the get_model function (see Routed Parameters). Few more changes to the code may be needed depending on whether categorical_cross_entropy is used, and the way fit is called (refer the complete list). We will not delve into details of those implementations." }, { "code": null, "e": 5320, "s": 5102, "text": "Scikit-Learn natively supports multiple outputs, although it technically requires them to be arrays of equal length (see docs for Scikit-Learn’s MultiOutputClassifier). Scikit-Learn has no support for multiple inputs." }, { "code": null, "e": 5961, "s": 5320, "text": "Many non-trivial Deep Learning models used in research and industry have either multiple inputs or multiple outputs, or both. Such models can be easily described and trained in Keras. However, using such models in sklearn becomes a challenge, since, sklearn expects the Xand y of a model to be a single n-dimensional numpy array (multiple arrays of same length allowed for the y). Now, the concatenation to a single array can be straightforward if all of the inputs/ouputs are of the same shape. However, this can quickly get messy when the inputs and outputs have different shapes, as is the case with a CapsNet model (more on this later)." }, { "code": null, "e": 6448, "s": 5961, "text": "In order to have multiple inputs and/or multiple outputs for a model, SciKeras allows the use of custom data transformers. The examples given in the official documentation, for achieving this with input and/or output lists with arrays of unmatching shapes, employ a reshaping of the inputs/outputs from an array of shape[E_dim1,E_dim2,E_dim3,...] to [E_dim1, E_dim2*E_dim3*...] , where Ecan either be input or output, effectively reshaping all the inputs to a 2-dimensional numpy array." }, { "code": null, "e": 6888, "s": 6448, "text": "These custom transformers, depending on whether it is used for transforming X (features) or y (targets), can then be used from a custom estimator to override either scikeras.wrappers.BaseWrappers.feature_encoder() or scikeras.wrappers.BaseWrappers.target_encoder() , respectively. Moreover, for models with multiple outputs, defining a custom scorer is advisable, especially when the outputs have different shapes or use different metrics." }, { "code": null, "e": 7415, "s": 6888, "text": "At the risk of oversimplifying, CapsNet is a novel architecture proposed by Geoffrey Hinton et al. in late 2017, where they designed a network that could perform without the use of Pooling layers. This is achieved by using capsules, which perform a form of ‘inverse rendering’, which is learnt by dynamic routing-by-agreement. For this tutorial we will not be going into the theory of CapsNet — those interested in theory can read this article for a working understanding, and refer to the original paper [1] for more details." }, { "code": null, "e": 7803, "s": 7415, "text": "What we are interested in is the implementation of the Capsule Network, and its overall architecture, since, that is what we want to wrap into scikeras. The implementation used in this tutorial is based off of the code made available openly by Xifeng Guo. The illustration shows the high level version of the architecture implemented, showing the approximate flows of inputs and outputs." }, { "code": null, "e": 7866, "s": 7803, "text": "The Capsule Layers need to be defined by the user or imported." }, { "code": null, "e": 8014, "s": 7866, "text": "Dynamic Routing of Capsules via routing-by-agreement defines a custom flow of data within the model (implemented in the user-defined Capsule Layer)" }, { "code": null, "e": 8186, "s": 8014, "text": "The outputs are not of the same type — One-Hot-Encoded(OHE) vector and flattened image — instead of both being labels(for classifiers) or continuous values(for regressor)." }, { "code": null, "e": 8697, "s": 8186, "text": "Building up on our discussion so far, the wrapper would need to override both BaseWrappers.feature_encoder() and BaseWrappers.target_encoder() . Depending on the type of transformation required, we could either resort to writing our custom transformer, or use one of the many transformers that are already offered in sklearn.preprocessing . For this tutorial, we will demonstrate both the ways of transformation — we will write a custom transformer for the outputs and use a library transformer for the inputs." }, { "code": null, "e": 9057, "s": 8697, "text": "Further, since the mechanism of training of the Keras model can not be strictly mirrored with that of a classifier or regressor (due to the reconstruction module), we will sub-class the BaseWrapper while defining our estimator. Moreover, for the performance comparison of the model we need to consider two outputs — hence, a custom scorer will also be needed." }, { "code": null, "e": 9570, "s": 9057, "text": "For our specific implementation, the outputs needed by the Keras model has to be in the form [y_true, X_true], while sklearn expects a numpy array to be fed as targets array. The transformer we define needs to be able to interface seamlessly between the two. This is achieved by fitting the transformer to the outputs in fitmethod, and then usingtransform method that reshapes the output into a list of arrays as expected by Keras, and an inverse_transform method that reshapes the output as expected by sklearn." }, { "code": null, "e": 10279, "s": 9570, "text": "We create our custom transformer MultiOutputTransformer , by sub-classing or inheriting from BaseEstimator and TransformerMixin classes of sklearn, and define a fit method. This method could be used to incorporate multiple library encoder, (like LabelEncoder, OneHotEncoder), into a single transformer, as demonstrated in the official tutorial, depending on the type of outputs. These encoders can be fit to the inputs so that the transform and inverse_transform methods can work appropriately. In this function, it is necessary to set the self.n_outputs_expected_ parameter to inform scikeras about the outputs from fit, while other parameters in meta can be optionally set. This function must return self ." }, { "code": null, "e": 10640, "s": 10279, "text": "In the code presented here, however, I have tried to demonstrate the implementation when there is no transformation needed for the targets except for a possible separation and a rearrangement. It should be noted that it would be possible to define a FunctionTransformer over an identity function to achieve this as well (which is demonstrated in next section)." }, { "code": null, "e": 10945, "s": 10640, "text": "The get_metadata function is optionally defined for model_build_fn where meta parameter is accepted. Specific to this code, the transform method is straightforward, in the inverse_transform method, we need to define our custom inverse transformation, since we do not have any library encoders to rely on." }, { "code": null, "e": 11340, "s": 10945, "text": "For the input transformer, we will use a library transformer already available in sklearn.preprocessing — the FunctionTransformer . For the FunctionTransformer , it is possible to define a lambda function into the func parameter of transformer constructor. But, having a lambda function could cause issues with pickle. So, we instead define a separate function to pass into FunctionTransformer." }, { "code": null, "e": 11672, "s": 11340, "text": "To finish up the wrapper, we subclass BaseWrapper as mentioned previously, and override feature_encoder, scorer, and target_encoder functions. Note that, in the scorer function, we only evaluate the output from the Capsules layer, since this is the metric on which we would want our cross-validation epochs to optimize the network." }, { "code": null, "e": 11995, "s": 11672, "text": "The next steps are pretty similar to the first example using the wrappers in tf.keras. We instantiate MIMOEstimator using get_model and pass the (hyper)parameters to get_model as routed parameters (with model__prefix). These routed arguments also include those hyperparameters that we would like to tune using grid-search." }, { "code": null, "e": 12213, "s": 11995, "text": "Next, we define the params dict containing the hyperparameters list and the corresponding values to try out as key-value pairs. We use the clf as a estimator to create GridSearchCV object, and then fit it to the data." }, { "code": null, "e": 12473, "s": 12213, "text": "Care must be taken while specifying the cv argument for the GridSearchCV to achieve a suitable relation between the number of training examples (n), the batch size(b), and the number of cross-validation batches (cv)— n should be completely divisible by cv *b." }, { "code": null, "e": 12738, "s": 12473, "text": "The results of the grid-search are accumulated in gs_res after the fit operation. The best estimator can be obtained using best_estimator_ attribute of gs_res, similarly, the best_score_ gives the best score, and best_params_ gives the best fit of hyperparameters." }, { "code": null, "e": 13124, "s": 12738, "text": "So, there it is — how we can write a custom wrapper with minimal coding to use Keras models in conjunction with sklearn API. Hope you found it helpful. If you have any suggestions or questions, please tell me about them in the comments section, especially if there is a usecase/model where this wrapping fails. You can find the full code implementation below with a few more resources." }, { "code": null, "e": 13288, "s": 13124, "text": "> Full code of this implementation can be found here.> A tutorial on custom Keras Layers can be found here and here.> Implemented CapsNet layers can be found here." } ]
Merge Sort for Linked List | Practice | GeeksforGeeks
Given Pointer/Reference to the head of the linked list, the task is to Sort the given linked list using Merge Sort. Note: If the length of linked list is odd, then the extra node should go in the first list while splitting. Example 1: Input: N = 5 value[] = {3,5,2,4,1} Output: 1 2 3 4 5 Explanation: After sorting the given linked list, the resultant matrix will be 1->2->3->4->5. Example 2: Input: N = 3 value[] = {9,15,0} Output: 0 9 15 Explanation: After sorting the given linked list , resultant will be 0->9->15. Your Task: For C++ and Python: The task is to complete the function mergeSort() which sort the linked list using merge sort function. For Java: The task is to complete the function mergeSort() and return the node which can be used to print the sorted linked list. Expected Time Complexity: O(N*Log(N)) Expected Auxiliary Space: O(N) Constraints: 1 <= T <= 100 1 <= N <= 105 0 sandeep55213 days ago C++ Merge Sort Solution Node* mergeTwoLists(Node* l1, Node* l2) { Node *d= new Node(0); auto p=d; while(l1 and l2){ if(l1->data<l2->data){ p->next=l1; l1=l1->next; } else{ p->next=l2; l2=l2->next; } p=p->next; } if(l1) p->next=l1; else p->next=l2; return d->next; } Node* mergeSort(Node* head) { // your code here if(!head or !(head->next)) return head; Node *slow=head; Node *fast=head; Node *tmp=NULL; while(fast and fast->next){ tmp=slow; slow=slow->next; fast=fast->next->next; } tmp->next=NULL; Node* f = mergeSort(head); Node* s = mergeSort(slow); return mergeTwoLists(f,s); } +2 shakshamkaushik11 week ago class Solution{ //Function to sort the given linked list using Merge Sort. static Node mergeSort(Node head) { if(head == null || head.next == null){ return head; } Node middle = getMiddle(head); Node part1 = head; Node part2 = middle.next; middle.next = null; part1 = mergeSort(part1); part2 = mergeSort(part2); head = merge(part1,part2); return head; } static Node getMiddle(Node head){ Node slow = head; Node fast = head; while(fast.next!=null && fast.next.next!=null){ slow = slow.next; fast = fast.next.next; } return slow; } static Node merge(Node h1, Node h2){ if(h1 == null){ return h2; } if(h2 == null){ return h1; } Node head,tail; if(h1.data<=h2.data){ head = h1; tail = h1; h1 = h1.next; }else{ head = h2; tail = h2; h2 = h2.next; } while (h1!=null && h2!=null){ if(h1.data<= h2.data){ tail.next = h1; h1 = h1.next; tail = tail.next; }else{ tail.next = h2; h2 = h2.next; tail = tail.next; } } if(h1!=null){ tail.next = h1; }else{ tail.next = h2; } return head;}} 0 nakulgopal2 weeks ago Very simple and intuitive approach C++. class Solution{ public: //Function to sort the given linked list using Merge Sort. Node* getMid(Node* head){ Node* slow = head; Node* fast = head->next; while(fast!=nullptr and fast->next!=nullptr){ slow = slow->next; fast = fast->next->next; } return slow; } Node* merge(Node*l,Node*r){ Node* newList = new Node(-1); Node* ans = newList; while(l!=nullptr and r!=nullptr){ if(l->data<r->data){ ans->next = new Node(l->data); ans = ans->next; l = l->next; }else{ ans->next = new Node(r->data); ans = ans->next; r= r->next; } } while(l!=nullptr){ ans->next = new Node(l->data); ans = ans->next; l = l->next; } while(r!=nullptr){ ans->next = new Node(r->data); ans = ans->next; r= r->next; } return newList->next; } Node* mergeSort(Node* head) { Node* ans = head; if(head->next!=nullptr){ Node* mid = getMid(head); Node* right = mid->next; mid->next = nullptr; Node* l = mergeSort(head); Node* r = mergeSort(right); ans = merge(l,r); } return ans; } }; 0 annanyamathur2 weeks ago Node *merge(Node *left, Node *right) { Node *curr1=left, *curr2=right, *a=new Node(-1),*temp=a; while(curr1!=NULL && curr2!=NULL) { if(curr1->data<curr2->data) { temp->next=curr1; curr1=curr1->next; temp=temp->next; } else { temp->next=curr2; curr2=curr2->next; temp=temp->next; } } while(curr1!=NULL) { temp->next=curr1; curr1=curr1->next; temp=temp->next; } while(curr2!=NULL) { temp->next=curr2; curr2=curr2->next; temp=temp->next; } a=a->next; temp->next=NULL; return a; } Node* findmid(Node* head, Node*tail) { Node* slow=head, *fast=head; while(fast!=tail && fast->next!=tail) { slow=slow->next; fast=fast->next->next; } return slow; } Node* msort(Node *head, Node *tail) { if(head==tail) { return new Node(head->data); } Node *mid=findmid(head,tail); Node *left=msort(head,mid); Node *right=msort(mid->next,tail); Node *root=merge(left,right); return root; } Node* mergeSort(Node* head) { Node *curr=head; while(curr->next!=NULL) { curr=curr->next; } Node *res= msort(head,curr); return res; } 0 harshscode3 weeks ago very easy c++... void mergesorting(Node **head) { Node *cur=*head; Node *first; Node *second; if(!cur or !cur->next) return; findmiddle(cur,&first,&second); mergesorting(&first); mergesorting(&second); *head=mergeboth(first,second); } Node *mergeboth(Node *first,Node *second) { Node *ans=NULL; if(!first) return second; else if(!second) return first; if(first->data<second->data) { ans=first; ans->next=mergeboth(first->next,second); } else { ans=second; ans->next=mergeboth(first,second->next); } return ans; } void findmiddle(Node *cur,Node **first,Node **second) { Node *fast=cur->next; Node *slow=cur; while(fast and fast->next) { slow=slow->next; fast=fast->next->next; } *first=cur; *second=slow->next; slow->next=NULL; } Node* mergeSort(Node* head) { mergesorting(&head); return head; } 0 himanshukug19cs3 weeks ago java solution static Node merge(Node node1, Node node2) {// Your code hereNode head =null;Node pre=null;if(node1==null&&node2==null) return null;else if(node1==null&&node2!=null) return node2;else if(node1!=null&&node2==null) return node2; if(node1.data<=node2.data){ head = new Node(node1.data); pre=head; node1=node1.next;}else{ head = new Node(node2.data); node2=node2.next; pre=head;} while(node1!=null&&node2!=null){ if(node1.data<=node2.data){ Node nod= new Node(node1.data); pre.next=nod; pre=pre.next; node1=node1.next; } else{ Node nod= new Node(node2.data); pre.next=nod; pre=pre.next; node2=node2.next; }}if(node1!=null){ while(node1!=null){ Node nod= new Node(node1.data); pre.next=nod; pre=pre.next; node1=node1.next; }}if(node2!=null){ while(node2!=null){ Node nod= new Node(node2.data); pre.next=nod; pre=pre.next; node2=node2.next; }}return head; } static Node findmiddle(Node head){ Node slow=head; Node fast=head.next; while(fast!=null&&fast.next!=null){ fast=fast.next.next; slow=slow.next; } return slow; } static Node mergeSort(Node head) { // add your code here if(head==null||head.next==null) return head; Node left=head; Node mid=findmiddle(head); Node right=mid.next; mid.next=null; Node a1=mergeSort(left); Node a2=mergeSort(right); return merge(a1,a2); } 0 bheniavedant4 weeks ago what is wrong with this python code def sorted(self,x,y): if x and y: if x.data > y.data: x, y = y, x x.next = self.sorted(x.next,y) return x,y def getmiddle(self,head): if head == None: return head slow = head fast = head while fast.next and fast.next.next: slow = slow.next fast = fast.next.next return slow def mergeSort(self, head): if head is None or head.next is None: return head middle = self.getmiddle(head) next_to_middle = middle.next middle.next = None left = self.mergeSort(head) right = self.mergeSort(next_to_middle) sortedlst = self.sorted(left,right) return sortedlst +1 shubham211019974 weeks ago static Node merge(Node h1,Node h2){ if(h1==null) return h2; if(h2==null) return h1; Node head,tail; if(h1.data<=h2.data) { head=h1; tail=h1; h1=h1.next; } else { head=h2; tail=h2; h2=h2.next; } while(h1!=null && h2!=null){ if(h1.data<=h2.data){ tail.next=h1; h1=h1.next; tail=tail.next; }else{ tail.next=h2; h2=h2.next; tail=tail.next; } } if(h1!=null) tail.next=h1; else tail.next=h2; return head; } static Node middle(Node head){ Node slow=head,fast=head; while(fast.next!=null && fast.next.next!=null){ slow=slow.next; fast=fast.next.next; } return slow; } //Function to sort the given linked list using Merge Sort. static Node mergeSort(Node head) { if(head==null || head.next==null) return head; Node mid=middle(head); Node part1=head; Node part2=mid.next; mid.next=null; part1=mergeSort(part1); part2=mergeSort(part2); head=merge(part1,part2); return head; } -8 sikkusaurav1231 month ago simple But not using merg_sort , But test case pass 100/100 Node* mergeSort(Node* head) { // your code here Node *p=head; vector<int>v; while(p!=NULL) { v.push_back(p->data); p=p->next; } sort(v.begin(),v.end()); int i=0; p=head; while(p!=NULL) { p->data=v[i]; p=p->next; i++; } return head; } 0 rmn51241 month ago // for O(1) space // we will apply merge sort algorithm class Solution{ public: // find mid in the linked list Node* findMid(Node* head) { Node* slow = head; Node* fast = head->next; while(fast!=NULL && fast->next!=NULL) { fast = fast->next->next; slow = slow->next; } return slow; } // merge sort algorithm Node* merge(Node* left,Node* right) { Node* ans = new Node(-1); Node* temp = ans; if(left==NULL) { return right; } if(right==NULL) { return left; } while(left!=NULL && right!=NULL) { if(left->data < right->data) { temp->next = left; temp = left; left = left->next; } else{ temp->next = right; temp = right; right = right->next; } } while(left!=NULL) { temp->next = left; temp = left; left = left->next; } while(right!=NULL) { temp->next = right; temp = right; right = right->next; } ans = ans->next; return ans; } //Function to sort the given linked list using Merge Sort. Node* mergeSort(Node* head) { if(head == NULL || head->next == NULL) { return head; } Node* left = head; Node* mid = findMid(head); Node* right = mid->next; mid->next = NULL; left = mergeSort(left); // sort left half right = mergeSort(right); // sort right half Node* result = merge(left,right); // apply merge function return result; } }; 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": 462, "s": 238, "text": "Given Pointer/Reference to the head of the linked list, the task is to Sort the given linked list using Merge Sort.\nNote: If the length of linked list is odd, then the extra node should go in the first list while splitting." }, { "code": null, "e": 473, "s": 462, "text": "Example 1:" }, { "code": null, "e": 622, "s": 473, "text": "Input:\nN = 5\nvalue[] = {3,5,2,4,1}\nOutput: 1 2 3 4 5\nExplanation: After sorting the given\nlinked list, the resultant matrix\nwill be 1->2->3->4->5.\n" }, { "code": null, "e": 633, "s": 622, "text": "Example 2:" }, { "code": null, "e": 760, "s": 633, "text": "Input:\nN = 3\nvalue[] = {9,15,0}\nOutput: 0 9 15\nExplanation: After sorting the given\nlinked list , resultant will be\n0->9->15." }, { "code": null, "e": 1024, "s": 760, "text": "Your Task:\nFor C++ and Python: The task is to complete the function mergeSort() which sort the linked list using merge sort function.\nFor Java: The task is to complete the function mergeSort() and return the node which can be used to print the sorted linked list." }, { "code": null, "e": 1093, "s": 1024, "text": "Expected Time Complexity: O(N*Log(N))\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 1134, "s": 1093, "text": "Constraints:\n1 <= T <= 100\n1 <= N <= 105" }, { "code": null, "e": 1138, "s": 1136, "text": "0" }, { "code": null, "e": 1160, "s": 1138, "text": "sandeep55213 days ago" }, { "code": null, "e": 1184, "s": 1160, "text": "C++ Merge Sort Solution" }, { "code": null, "e": 2026, "s": 1184, "text": "Node* mergeTwoLists(Node* l1, Node* l2) {\n Node *d= new Node(0);\n auto p=d;\n while(l1 and l2){\n if(l1->data<l2->data){\n p->next=l1;\n l1=l1->next;\n }\n else{\n p->next=l2;\n l2=l2->next;\n }\n p=p->next;\n }\n if(l1) p->next=l1;\n else p->next=l2;\n return d->next;\n }\n Node* mergeSort(Node* head) {\n // your code here\n if(!head or !(head->next)) return head;\n Node *slow=head;\n Node *fast=head;\n Node *tmp=NULL;\n while(fast and fast->next){\n tmp=slow;\n slow=slow->next;\n fast=fast->next->next;\n }\n tmp->next=NULL;\n Node* f = mergeSort(head);\n Node* s = mergeSort(slow);\n return mergeTwoLists(f,s);\n }" }, { "code": null, "e": 2029, "s": 2026, "text": "+2" }, { "code": null, "e": 2056, "s": 2029, "text": "shakshamkaushik11 week ago" }, { "code": null, "e": 2880, "s": 2058, "text": "class Solution{ //Function to sort the given linked list using Merge Sort. static Node mergeSort(Node head) { if(head == null || head.next == null){ return head; } Node middle = getMiddle(head); Node part1 = head; Node part2 = middle.next; middle.next = null; part1 = mergeSort(part1); part2 = mergeSort(part2); head = merge(part1,part2); return head; } static Node getMiddle(Node head){ Node slow = head; Node fast = head; while(fast.next!=null && fast.next.next!=null){ slow = slow.next; fast = fast.next.next; } return slow; } static Node merge(Node h1, Node h2){ if(h1 == null){ return h2; } if(h2 == null){ return h1; }" }, { "code": null, "e": 3473, "s": 2880, "text": " Node head,tail; if(h1.data<=h2.data){ head = h1; tail = h1; h1 = h1.next; }else{ head = h2; tail = h2; h2 = h2.next; } while (h1!=null && h2!=null){ if(h1.data<= h2.data){ tail.next = h1; h1 = h1.next; tail = tail.next; }else{ tail.next = h2; h2 = h2.next; tail = tail.next; } } if(h1!=null){ tail.next = h1; }else{ tail.next = h2; } " }, { "code": null, "e": 3488, "s": 3473, "text": "return head;}}" }, { "code": null, "e": 3492, "s": 3490, "text": "0" }, { "code": null, "e": 3514, "s": 3492, "text": "nakulgopal2 weeks ago" }, { "code": null, "e": 5100, "s": 3514, "text": "Very simple and intuitive approach C++.\n\nclass Solution{\n public:\n //Function to sort the given linked list using Merge Sort.\n Node* getMid(Node* head){\n Node* slow = head;\n Node* fast = head->next;\n \n while(fast!=nullptr and fast->next!=nullptr){\n slow = slow->next;\n fast = fast->next->next;\n }\n return slow;\n }\n \n Node* merge(Node*l,Node*r){\n Node* newList = new Node(-1);\n Node* ans = newList;\n while(l!=nullptr and r!=nullptr){\n if(l->data<r->data){\n ans->next = new Node(l->data);\n ans = ans->next;\n l = l->next;\n }else{\n ans->next = new Node(r->data);\n ans = ans->next;\n r= r->next;\n }\n }\n \n while(l!=nullptr){\n ans->next = new Node(l->data);\n ans = ans->next;\n l = l->next;\n }\n while(r!=nullptr){\n ans->next = new Node(r->data);\n ans = ans->next;\n r= r->next;\n }\n return newList->next;\n }\n \n \n Node* mergeSort(Node* head) {\n Node* ans = head;\n if(head->next!=nullptr){\n \n Node* mid = getMid(head);\n Node* right = mid->next;\n mid->next = nullptr;\n Node* l = mergeSort(head);\n Node* r = mergeSort(right);\n ans = merge(l,r);\n \n }\n \n return ans;\n }\n};\n" }, { "code": null, "e": 5102, "s": 5100, "text": "0" }, { "code": null, "e": 5127, "s": 5102, "text": "annanyamathur2 weeks ago" }, { "code": null, "e": 6535, "s": 5127, "text": "Node *merge(Node *left, Node *right) { Node *curr1=left, *curr2=right, *a=new Node(-1),*temp=a; while(curr1!=NULL && curr2!=NULL) { if(curr1->data<curr2->data) { temp->next=curr1; curr1=curr1->next; temp=temp->next; } else { temp->next=curr2; curr2=curr2->next; temp=temp->next; } } while(curr1!=NULL) { temp->next=curr1; curr1=curr1->next; temp=temp->next; } while(curr2!=NULL) { temp->next=curr2; curr2=curr2->next; temp=temp->next; } a=a->next; temp->next=NULL; return a; } Node* findmid(Node* head, Node*tail) { Node* slow=head, *fast=head; while(fast!=tail && fast->next!=tail) { slow=slow->next; fast=fast->next->next; } return slow; } Node* msort(Node *head, Node *tail) { if(head==tail) { return new Node(head->data); } Node *mid=findmid(head,tail); Node *left=msort(head,mid); Node *right=msort(mid->next,tail); Node *root=merge(left,right); return root; } Node* mergeSort(Node* head) { Node *curr=head; while(curr->next!=NULL) { curr=curr->next; } Node *res= msort(head,curr); return res; }" }, { "code": null, "e": 6537, "s": 6535, "text": "0" }, { "code": null, "e": 6559, "s": 6537, "text": "harshscode3 weeks ago" }, { "code": null, "e": 6576, "s": 6559, "text": "very easy c++..." }, { "code": null, "e": 7709, "s": 6578, "text": "void mergesorting(Node **head) { Node *cur=*head; Node *first; Node *second; if(!cur or !cur->next) return; findmiddle(cur,&first,&second); mergesorting(&first); mergesorting(&second); *head=mergeboth(first,second); } Node *mergeboth(Node *first,Node *second) { Node *ans=NULL; if(!first) return second; else if(!second) return first; if(first->data<second->data) { ans=first; ans->next=mergeboth(first->next,second); } else { ans=second; ans->next=mergeboth(first,second->next); } return ans; } void findmiddle(Node *cur,Node **first,Node **second) { Node *fast=cur->next; Node *slow=cur; while(fast and fast->next) { slow=slow->next; fast=fast->next->next; } *first=cur; *second=slow->next; slow->next=NULL; } Node* mergeSort(Node* head) { mergesorting(&head); return head; }" }, { "code": null, "e": 7711, "s": 7709, "text": "0" }, { "code": null, "e": 7738, "s": 7711, "text": "himanshukug19cs3 weeks ago" }, { "code": null, "e": 7752, "s": 7738, "text": "java solution" }, { "code": null, "e": 8165, "s": 7754, "text": " static Node merge(Node node1, Node node2) {// Your code hereNode head =null;Node pre=null;if(node1==null&&node2==null) return null;else if(node1==null&&node2!=null) return node2;else if(node1!=null&&node2==null) return node2; if(node1.data<=node2.data){ head = new Node(node1.data); pre=head; node1=node1.next;}else{ head = new Node(node2.data); node2=node2.next; pre=head;}" }, { "code": null, "e": 9389, "s": 8165, "text": "while(node1!=null&&node2!=null){ if(node1.data<=node2.data){ Node nod= new Node(node1.data); pre.next=nod; pre=pre.next; node1=node1.next; } else{ Node nod= new Node(node2.data); pre.next=nod; pre=pre.next; node2=node2.next; }}if(node1!=null){ while(node1!=null){ Node nod= new Node(node1.data); pre.next=nod; pre=pre.next; node1=node1.next; }}if(node2!=null){ while(node2!=null){ Node nod= new Node(node2.data); pre.next=nod; pre=pre.next; node2=node2.next; }}return head; } static Node findmiddle(Node head){ Node slow=head; Node fast=head.next; while(fast!=null&&fast.next!=null){ fast=fast.next.next; slow=slow.next; } return slow; } static Node mergeSort(Node head) { // add your code here if(head==null||head.next==null) return head; Node left=head; Node mid=findmiddle(head); Node right=mid.next; mid.next=null; Node a1=mergeSort(left); Node a2=mergeSort(right); return merge(a1,a2); }" }, { "code": null, "e": 9391, "s": 9389, "text": "0" }, { "code": null, "e": 9415, "s": 9391, "text": "bheniavedant4 weeks ago" }, { "code": null, "e": 9451, "s": 9415, "text": "what is wrong with this python code" }, { "code": null, "e": 10193, "s": 9451, "text": "def sorted(self,x,y): if x and y: if x.data > y.data: x, y = y, x x.next = self.sorted(x.next,y) return x,y def getmiddle(self,head): if head == None: return head slow = head fast = head while fast.next and fast.next.next: slow = slow.next fast = fast.next.next return slow def mergeSort(self, head): if head is None or head.next is None: return head middle = self.getmiddle(head) next_to_middle = middle.next middle.next = None left = self.mergeSort(head) right = self.mergeSort(next_to_middle) sortedlst = self.sorted(left,right) return sortedlst " }, { "code": null, "e": 10196, "s": 10193, "text": "+1" }, { "code": null, "e": 10223, "s": 10196, "text": "shubham211019974 weeks ago" }, { "code": null, "e": 11486, "s": 10223, "text": "static Node merge(Node h1,Node h2){ if(h1==null) return h2; if(h2==null) return h1; Node head,tail; if(h1.data<=h2.data) { head=h1; tail=h1; h1=h1.next; } else { head=h2; tail=h2; h2=h2.next; } while(h1!=null && h2!=null){ if(h1.data<=h2.data){ tail.next=h1; h1=h1.next; tail=tail.next; }else{ tail.next=h2; h2=h2.next; tail=tail.next; } } if(h1!=null) tail.next=h1; else tail.next=h2; return head; } static Node middle(Node head){ Node slow=head,fast=head; while(fast.next!=null && fast.next.next!=null){ slow=slow.next; fast=fast.next.next; } return slow; } //Function to sort the given linked list using Merge Sort. static Node mergeSort(Node head) { if(head==null || head.next==null) return head; Node mid=middle(head); Node part1=head; Node part2=mid.next; mid.next=null; part1=mergeSort(part1); part2=mergeSort(part2); head=merge(part1,part2); return head; }" }, { "code": null, "e": 11489, "s": 11486, "text": "-8" }, { "code": null, "e": 11515, "s": 11489, "text": "sikkusaurav1231 month ago" }, { "code": null, "e": 11575, "s": 11515, "text": "simple But not using merg_sort , But test case pass 100/100" }, { "code": null, "e": 11939, "s": 11577, "text": " Node* mergeSort(Node* head) { // your code here Node *p=head; vector<int>v; while(p!=NULL) { v.push_back(p->data); p=p->next; } sort(v.begin(),v.end()); int i=0; p=head; while(p!=NULL) { p->data=v[i]; p=p->next; i++; } return head; }" }, { "code": null, "e": 11941, "s": 11939, "text": "0" }, { "code": null, "e": 11960, "s": 11941, "text": "rmn51241 month ago" }, { "code": null, "e": 13719, "s": 11960, "text": "// for O(1) space\n // we will apply merge sort algorithm\nclass Solution{\n public:\n // find mid in the linked list\n Node* findMid(Node* head)\n {\n Node* slow = head;\n Node* fast = head->next;\n while(fast!=NULL && fast->next!=NULL)\n {\n fast = fast->next->next;\n slow = slow->next;\n }\n return slow;\n }\n \n // merge sort algorithm \n Node* merge(Node* left,Node* right)\n {\n Node* ans = new Node(-1);\n Node* temp = ans;\n if(left==NULL)\n {\n return right;\n }\n if(right==NULL)\n {\n return left;\n }\n while(left!=NULL && right!=NULL)\n {\n if(left->data < right->data)\n {\n temp->next = left;\n temp = left;\n left = left->next;\n }\n else{\n temp->next = right;\n temp = right;\n right = right->next;\n }\n }\n while(left!=NULL)\n {\n temp->next = left;\n temp = left;\n left = left->next;\n }\n while(right!=NULL)\n {\n temp->next = right;\n temp = right;\n right = right->next;\n }\n ans = ans->next;\n return ans;\n } \n \n //Function to sort the given linked list using Merge Sort.\n Node* mergeSort(Node* head) {\n if(head == NULL || head->next == NULL)\n {\n return head;\n }\n Node* left = head;\n Node* mid = findMid(head);\n Node* right = mid->next;\n mid->next = NULL;\n \n left = mergeSort(left); // sort left half\n right = mergeSort(right); // sort right half\n \n Node* result = merge(left,right); // apply merge function\n return result;\n }\n};\n" }, { "code": null, "e": 13865, "s": 13719, "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": 13901, "s": 13865, "text": " Login to access your submissions. " }, { "code": null, "e": 13911, "s": 13901, "text": "\nProblem\n" }, { "code": null, "e": 13921, "s": 13911, "text": "\nContest\n" }, { "code": null, "e": 13984, "s": 13921, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 14132, "s": 13984, "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": 14340, "s": 14132, "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": 14446, "s": 14340, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Find length of longest substring with at most K normal characters - GeeksforGeeks
03 Jun, 2021 Given a string P consisting of small English letters and a 26-digit bit string Q, where 1 represents the special character and 0 represents a normal character for the 26 English alphabets. The task is to find the length of the longest substring with at most K normal characters. Examples: Input : P = “normal”, Q = “00000000000000000000000000”, K=1 Output : 1 Explanation : In string Q all characters are normal. Hence, we can select any substring of length 1. Input : P = “giraffe”, Q = “01111001111111111011111111”, K=2 Output : 3 Explanation : Normal characters in P from Q are {a, f, g, r}. Therefore, possible substrings with at most 2 normal characters are {gir, ira, ffe}. The maximum length of all substring is 3. Approach: To solve the problem mentioned above we will be using the concept of two pointers. Hence, maintain left and right pointers of the substring, and a count of normal characters. Increment the right index till the count of normal characters is at most K. Then update the answer with a maximum length of substring encountered till now. Increment left index and decrement count till it is greater than K.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to Find// length of longest substring// with at most K normal characters#include <bits/stdc++.h>using namespace std; // Function to find maximum// length of normal substringsint maxNormalSubstring(string& P, string& Q, int K, int N){ if (K == 0) return 0; // keeps count of normal characters int count = 0; // indexes of substring int left = 0, right = 0; // maintain length of longest substring // with at most K normal characters int ans = 0; while (right < N) { while (right < N && count <= K) { // get position of character int pos = P[right] - 'a'; // check if current character is normal if (Q[pos] == '0') { // check if normal characters // count exceeds K if (count + 1 > K) break; else count++; } right++; // update answer with substring length if (count <= K) ans = max(ans, right - left); } while (left < right) { // get position of character int pos = P[left] - 'a'; left++; // check if character is // normal then decrement count if (Q[pos] == '0') count--; if (count < K) break; } } return ans;} // Driver codeint main(){ // initialise the string string P = "giraffe", Q = "01111001111111111011111111"; int K = 2; int N = P.length(); cout << maxNormalSubstring(P, Q, K, N); return 0;} // Java implementation to Find// length of longest subString// with at most K normal charactersclass GFG{ // Function to find maximum// length of normal subStringsstatic int maxNormalSubString(char []P, char []Q, int K, int N){ if (K == 0) return 0; // keeps count of normal characters int count = 0; // indexes of subString int left = 0, right = 0; // maintain length of longest subString // with at most K normal characters int ans = 0; while (right < N) { while (right < N && count <= K) { // get position of character int pos = P[right] - 'a'; // check if current character is normal if (Q[pos] == '0') { // check if normal characters // count exceeds K if (count + 1 > K) break; else count++; } right++; // update answer with subString length if (count <= K) ans = Math.max(ans, right - left); } while (left < right) { // get position of character int pos = P[left] - 'a'; left++; // check if character is // normal then decrement count if (Q[pos] == '0') count--; if (count < K) break; } } return ans;} // Driver codepublic static void main(String[] args){ // initialise the String String P = "giraffe", Q = "01111001111111111011111111"; int K = 2; int N = P.length(); System.out.print(maxNormalSubString(P.toCharArray(), Q.toCharArray(), K, N));}} // This code is contributed by Princi Singh # Function to find maximum# length of normal substringsdef maxNormalSubstring(P, Q, K, N): if (K == 0): return 0 # keeps count of normal characters count = 0 # indexes of substring left, right = 0, 0 # maintain length of longest substring # with at most K normal characters ans = 0 while (right < N): while (right < N and count <= K): # get position of character pos = ord(P[right]) - ord('a') # check if current character is normal if (Q[pos] == '0'): # check if normal characters # count exceeds K if (count + 1 > K): break else: count += 1 right += 1 # update answer with substring length if (count <= K): ans = max(ans, right - left) while (left < right): # get position of character pos = ord(P[left]) - ord('a') left += 1 # check if character is # normal then decrement count if (Q[pos] == '0'): count -= 1 if (count < K): break return ans # Driver codeif(__name__ == "__main__"): # initialise the string P = "giraffe" Q = "01111001111111111011111111" K = 2 N = len(P) print(maxNormalSubstring(P, Q, K, N)) # This code is contributed by skylags // C# implementation to Find// length of longest subString// with at most K normal charactersusing System; public class GFG{ // Function to find maximum// length of normal subStringsstatic int maxNormalSubString(char []P, char []Q, int K, int N){ if (K == 0) return 0; // keeps count of normal characters int count = 0; // indexes of subString int left = 0, right = 0; // maintain length of longest subString // with at most K normal characters int ans = 0; while (right < N) { while (right < N && count <= K) { // get position of character int pos = P[right] - 'a'; // check if current character is normal if (Q[pos] == '0') { // check if normal characters // count exceeds K if (count + 1 > K) break; else count++; } right++; // update answer with subString length if (count <= K) ans = Math.Max(ans, right - left); } while (left < right) { // get position of character int pos = P[left] - 'a'; left++; // check if character is // normal then decrement count if (Q[pos] == '0') count--; if (count < K) break; } } return ans;} // Driver codepublic static void Main(String[] args){ // initialise the String String P = "giraffe", Q = "01111001111111111011111111"; int K = 2; int N = P.Length; Console.Write(maxNormalSubString(P.ToCharArray(), Q.ToCharArray(), K, N));}} // This code contributed by Princi Singh <script> // Javascript implementation to Find// length of longest substring// with at most K normal character // Function to find maximum// length of normal substringsfunction maxNormalSubstring(P, Q, K, N){ if (K == 0) return 0; // keeps count of normal characters var count = 0; // indexes of substring var left = 0, right = 0; // maintain length of longest substring // with at most K normal characters var ans = 0; while (right < N) { while (right < N && count <= K) { // get position of character var pos = P[right].charCodeAt(0) - 'a'.charCodeAt(0); // check if current character is normal if (Q[pos] == '0') { // check if normal characters // count exceeds K if (count + 1 > K) break; else count++; } right++; // update answer with substring length if (count <= K) ans = Math.max(ans, right - left); } while (left < right) { // get position of character var pos = P[left].charCodeAt(0) - 'a'.charCodeAt(0); left++; // check if character is // normal then decrement count if (Q[pos] == '0') count--; if (count < K) break; } } return ans;} // Driver code// initialise the stringvar P = "giraffe", Q = "01111001111111111011111111";var K = 2;var N = P.length;document.write( maxNormalSubstring(P, Q, K, N)); </script> 3 Time Complexity: The above method takes O(N) time. skylags princi singh rrrtnx substring Greedy Pattern Searching Strings Strings Greedy Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Huffman Coding | Greedy Algo-3 Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8 Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) Coin Change | DP-7 Activity Selection Problem | Greedy Algo-1 KMP Algorithm for Pattern Searching Rabin-Karp Algorithm for Pattern Searching Check if a string is substring of another Naive algorithm for Pattern Searching Boyer Moore Algorithm for Pattern Searching
[ { "code": null, "e": 25069, "s": 25041, "text": "\n03 Jun, 2021" }, { "code": null, "e": 25348, "s": 25069, "text": "Given a string P consisting of small English letters and a 26-digit bit string Q, where 1 represents the special character and 0 represents a normal character for the 26 English alphabets. The task is to find the length of the longest substring with at most K normal characters." }, { "code": null, "e": 25359, "s": 25348, "text": "Examples: " }, { "code": null, "e": 25531, "s": 25359, "text": "Input : P = “normal”, Q = “00000000000000000000000000”, K=1 Output : 1 Explanation : In string Q all characters are normal. Hence, we can select any substring of length 1." }, { "code": null, "e": 25793, "s": 25531, "text": "Input : P = “giraffe”, Q = “01111001111111111011111111”, K=2 Output : 3 Explanation : Normal characters in P from Q are {a, f, g, r}. Therefore, possible substrings with at most 2 normal characters are {gir, ira, ffe}. The maximum length of all substring is 3. " }, { "code": null, "e": 26253, "s": 25793, "text": "Approach: To solve the problem mentioned above we will be using the concept of two pointers. Hence, maintain left and right pointers of the substring, and a count of normal characters. Increment the right index till the count of normal characters is at most K. Then update the answer with a maximum length of substring encountered till now. Increment left index and decrement count till it is greater than K.Below is the implementation of the above approach: " }, { "code": null, "e": 26257, "s": 26253, "text": "C++" }, { "code": null, "e": 26262, "s": 26257, "text": "Java" }, { "code": null, "e": 26270, "s": 26262, "text": "Python3" }, { "code": null, "e": 26273, "s": 26270, "text": "C#" }, { "code": null, "e": 26284, "s": 26273, "text": "Javascript" }, { "code": "// C++ implementation to Find// length of longest substring// with at most K normal characters#include <bits/stdc++.h>using namespace std; // Function to find maximum// length of normal substringsint maxNormalSubstring(string& P, string& Q, int K, int N){ if (K == 0) return 0; // keeps count of normal characters int count = 0; // indexes of substring int left = 0, right = 0; // maintain length of longest substring // with at most K normal characters int ans = 0; while (right < N) { while (right < N && count <= K) { // get position of character int pos = P[right] - 'a'; // check if current character is normal if (Q[pos] == '0') { // check if normal characters // count exceeds K if (count + 1 > K) break; else count++; } right++; // update answer with substring length if (count <= K) ans = max(ans, right - left); } while (left < right) { // get position of character int pos = P[left] - 'a'; left++; // check if character is // normal then decrement count if (Q[pos] == '0') count--; if (count < K) break; } } return ans;} // Driver codeint main(){ // initialise the string string P = \"giraffe\", Q = \"01111001111111111011111111\"; int K = 2; int N = P.length(); cout << maxNormalSubstring(P, Q, K, N); return 0;}", "e": 27945, "s": 26284, "text": null }, { "code": "// Java implementation to Find// length of longest subString// with at most K normal charactersclass GFG{ // Function to find maximum// length of normal subStringsstatic int maxNormalSubString(char []P, char []Q, int K, int N){ if (K == 0) return 0; // keeps count of normal characters int count = 0; // indexes of subString int left = 0, right = 0; // maintain length of longest subString // with at most K normal characters int ans = 0; while (right < N) { while (right < N && count <= K) { // get position of character int pos = P[right] - 'a'; // check if current character is normal if (Q[pos] == '0') { // check if normal characters // count exceeds K if (count + 1 > K) break; else count++; } right++; // update answer with subString length if (count <= K) ans = Math.max(ans, right - left); } while (left < right) { // get position of character int pos = P[left] - 'a'; left++; // check if character is // normal then decrement count if (Q[pos] == '0') count--; if (count < K) break; } } return ans;} // Driver codepublic static void main(String[] args){ // initialise the String String P = \"giraffe\", Q = \"01111001111111111011111111\"; int K = 2; int N = P.length(); System.out.print(maxNormalSubString(P.toCharArray(), Q.toCharArray(), K, N));}} // This code is contributed by Princi Singh", "e": 29705, "s": 27945, "text": null }, { "code": "# Function to find maximum# length of normal substringsdef maxNormalSubstring(P, Q, K, N): if (K == 0): return 0 # keeps count of normal characters count = 0 # indexes of substring left, right = 0, 0 # maintain length of longest substring # with at most K normal characters ans = 0 while (right < N): while (right < N and count <= K): # get position of character pos = ord(P[right]) - ord('a') # check if current character is normal if (Q[pos] == '0'): # check if normal characters # count exceeds K if (count + 1 > K): break else: count += 1 right += 1 # update answer with substring length if (count <= K): ans = max(ans, right - left) while (left < right): # get position of character pos = ord(P[left]) - ord('a') left += 1 # check if character is # normal then decrement count if (Q[pos] == '0'): count -= 1 if (count < K): break return ans # Driver codeif(__name__ == \"__main__\"): # initialise the string P = \"giraffe\" Q = \"01111001111111111011111111\" K = 2 N = len(P) print(maxNormalSubstring(P, Q, K, N)) # This code is contributed by skylags", "e": 31188, "s": 29705, "text": null }, { "code": "// C# implementation to Find// length of longest subString// with at most K normal charactersusing System; public class GFG{ // Function to find maximum// length of normal subStringsstatic int maxNormalSubString(char []P, char []Q, int K, int N){ if (K == 0) return 0; // keeps count of normal characters int count = 0; // indexes of subString int left = 0, right = 0; // maintain length of longest subString // with at most K normal characters int ans = 0; while (right < N) { while (right < N && count <= K) { // get position of character int pos = P[right] - 'a'; // check if current character is normal if (Q[pos] == '0') { // check if normal characters // count exceeds K if (count + 1 > K) break; else count++; } right++; // update answer with subString length if (count <= K) ans = Math.Max(ans, right - left); } while (left < right) { // get position of character int pos = P[left] - 'a'; left++; // check if character is // normal then decrement count if (Q[pos] == '0') count--; if (count < K) break; } } return ans;} // Driver codepublic static void Main(String[] args){ // initialise the String String P = \"giraffe\", Q = \"01111001111111111011111111\"; int K = 2; int N = P.Length; Console.Write(maxNormalSubString(P.ToCharArray(), Q.ToCharArray(), K, N));}} // This code contributed by Princi Singh", "e": 32951, "s": 31188, "text": null }, { "code": "<script> // Javascript implementation to Find// length of longest substring// with at most K normal character // Function to find maximum// length of normal substringsfunction maxNormalSubstring(P, Q, K, N){ if (K == 0) return 0; // keeps count of normal characters var count = 0; // indexes of substring var left = 0, right = 0; // maintain length of longest substring // with at most K normal characters var ans = 0; while (right < N) { while (right < N && count <= K) { // get position of character var pos = P[right].charCodeAt(0) - 'a'.charCodeAt(0); // check if current character is normal if (Q[pos] == '0') { // check if normal characters // count exceeds K if (count + 1 > K) break; else count++; } right++; // update answer with substring length if (count <= K) ans = Math.max(ans, right - left); } while (left < right) { // get position of character var pos = P[left].charCodeAt(0) - 'a'.charCodeAt(0); left++; // check if character is // normal then decrement count if (Q[pos] == '0') count--; if (count < K) break; } } return ans;} // Driver code// initialise the stringvar P = \"giraffe\", Q = \"01111001111111111011111111\";var K = 2;var N = P.length;document.write( maxNormalSubstring(P, Q, K, N)); </script>", "e": 34568, "s": 32951, "text": null }, { "code": null, "e": 34570, "s": 34568, "text": "3" }, { "code": null, "e": 34624, "s": 34572, "text": "Time Complexity: The above method takes O(N) time. " }, { "code": null, "e": 34632, "s": 34624, "text": "skylags" }, { "code": null, "e": 34645, "s": 34632, "text": "princi singh" }, { "code": null, "e": 34652, "s": 34645, "text": "rrrtnx" }, { "code": null, "e": 34662, "s": 34652, "text": "substring" }, { "code": null, "e": 34669, "s": 34662, "text": "Greedy" }, { "code": null, "e": 34687, "s": 34669, "text": "Pattern Searching" }, { "code": null, "e": 34695, "s": 34687, "text": "Strings" }, { "code": null, "e": 34703, "s": 34695, "text": "Strings" }, { "code": null, "e": 34710, "s": 34703, "text": "Greedy" }, { "code": null, "e": 34728, "s": 34710, "text": "Pattern Searching" }, { "code": null, "e": 34826, "s": 34728, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34835, "s": 34826, "text": "Comments" }, { "code": null, "e": 34848, "s": 34835, "text": "Old Comments" }, { "code": null, "e": 34879, "s": 34848, "text": "Huffman Coding | Greedy Algo-3" }, { "code": null, "e": 34950, "s": 34879, "text": "Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8" }, { "code": null, "e": 35031, "s": 34950, "text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)" }, { "code": null, "e": 35050, "s": 35031, "text": "Coin Change | DP-7" }, { "code": null, "e": 35093, "s": 35050, "text": "Activity Selection Problem | Greedy Algo-1" }, { "code": null, "e": 35129, "s": 35093, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 35172, "s": 35129, "text": "Rabin-Karp Algorithm for Pattern Searching" }, { "code": null, "e": 35214, "s": 35172, "text": "Check if a string is substring of another" }, { "code": null, "e": 35252, "s": 35214, "text": "Naive algorithm for Pattern Searching" } ]
Distance formula - Coordinate Geometry | Class 10 Maths - GeeksforGeeks
27 Oct, 2020 The distance formula is one of the important concepts in coordinate geometry which is used widely. By using the distance formula we can find the shortest distance i.e drawing a straight line between points. There are two ways to find the distance between points: Pythagorean theoremDistance formula Pythagorean theorem Distance formula This theorem is similar to the Pythagoras theorem but the use of it here is a little different. Normally by Pythagoras theorem, we will find the missing length in the right triangle. Here also we do the same thing but before that, we have to find the coordinates of the triangle. Suppose from a point boy walks 4 m to the west and took a turn to the south and walked 3 m. Now to calculate the shortest distance from the initial point to the final point would be the hypotenuse of the formed triangle as shown below. In the above diagram as you can see the initial and final points are A and C respectively. The distance is given between points A, B is 4 m and between points B, C is 3 m. To find the shortest distance which is nothing but AC we will use the Pythagorean theorem. This is calculated using the Pythagoras theorem as follows: => AC2 = AB2 + BC2 => AC = √(16 + 9) => AC = √25 = 5 m Hence the shortest distance is 5 m. Problem 1: Using the Pythagorean theorem, find the distance between points (-5, 2) and (7, 2)? Solution: Let’s try to visualize the coordinates on the graph Now, let’s join point A and B with a straight line and also draw the horizontal and vertical lines from points A and B respectively. Horizontal and vertical lines coincide at point C. Now we have to find the horizontal and vertical distance i.e length of AC and BC. => AC = (x2 – x1) = (7 – (-5)) = 12 => BC = (y2 – y1) = (2 – 7) = -5 [As distance can’t be negative, we have to only consider numerical value] As you see in the above diagram, now the problem is turned into basic Pythagoras theorem => AB2 = AC2 + BC2 => AB2 = 52 + 122 => AB = √(25 + 144) => AB = √169 = 13 square units Therefore, the distance between the given points is 13 sq units. Problem 2: Using the Pythagorean theorem, find the distance between points (4, 8) and (6, 4)? Solution: The first thing you have to do after seeing the question is to draw a diagram. Sometimes drawing makes the problem simple. As we have to find the distance between points A and B, so first join those points then from point A draw a vertical line and from point B draw a horizontal line and let the point where both extended lines meet be C. Now to find the coordinates of point C, we should keenly observe that point C is at the same level as point B i.e the Y coordinate will be the same, and similarly point A and point C will have the same X coordinate. So coordinates of AC will become (4, 4) Length of line BC will be (6 – 4) = 2 cm Length of line AC will be (8 – 4) = 4 cm Now by using Pythagoras theorem, => AB2 = AC2 + BC2 => AB2 = 42 + 22 => AB = √(16 + 4) => AB = √20 = 4.47 (approx) Hence the distance between point A and B is 4.47 cm Problem 3: Given the distance between the points M (x, 2) and N (2, 5) is 5 cm. Find the value of x? Solution: The first step is to draw the diagram for a clear understanding of the problem. This problem is different from previous problems because here we have to find x coordinate of point M where distance is given between the points MN Point N is fixed but M is not fixed. But we know y coordinate of point M. So we will draw a horizontal at y = 2. But we don’t know the x coordinate we will have several possibilities. Now draw a vertical line from point N and name point C where both lines meet. Length of NC = (5 – 2) = 3 cm Length of MC = (x – 2) cm And it is already given NM = 5 cm Applying Pythagoras theorem, => NM2 = NC2 + MC2 => 52 = 32 + (x – 2)2 => 25 – 9 = (x – 2)2 => 16 = (4)2 = (x – 2)2 After cancelling squares on both sides => x – 2 = 4 => x = 6 Therefore value of x is 6 and point M is (6, 2) The distance formula is used to find the distance between any two given points. By Pythagoras theorem, we can derive the distance formula. Using distance formula is much easier than the Pythagorean theorem. AB = √[(x2 - x1)2 + (y2 - y1)2] where points are A(x1, y1) and B(x2, y2) Let us look at how this formula is derived In the above diagram, there are 2 points A(x1, y1) and B(x2, y2) for which we have to find the distance between them. Join the points A and B with a straight line. Now draw horizontal lines from points A and B, and they both meet at point C. Now the coordinates of point C will become C (x1, y2). Now it looks like a right triangle ACB where side AC is the perpendicular, CB is the base, and AB is the hypotenuse. Now we need to find the distance between points A and C. Now by seeing the diagram, the distance between them will be the difference between their y coordinate. => AC = y2 – y1 .......(1) Similarly, the distance between points C and B will be the difference between x coordinates. => CB = x2 – x1 ........(2) ∆ACB is a right-angled triangle. We need to find hypotenuse AB, by Pythagoras theorem => AB2 = BC2 + AC2 From (1) and (2), => AB2 = (x2 – x1)2 + (y2 – y1)2 Taking Square roots on both sides, => AB = √{(x2 – x 1)2 + (y2 – y1)2} So the Distance Formula is, AB = √[(x2 – x1)2 + (y2 – y1)2] Problem 1: The coordinates of point A are (-4, 0) and the coordinates of point B are (0, 3). Find the distance between these two points. Solution: The coordinates of A are = (-4, 0) The coordinates of B are = (0, 3) Let coordinates of A and B are (x1, y1) and (x2, y2) respectively By Distance Formula, => AB = √[(x2 – x1)2 + (y2 – y1)2] = √[{0 – (-4)}2+ (3 – 0)2] => √(42 + 32) = √(16 + 9) = √25 => 5 units Therefore the distance between points A and B is 5 units. Problem 2: Find the distance between the points (7, 3) and (8, 9). Solution: Let the coordinates of P = (7, 3) = (x1, y1) Let the coordinates of Q = (8, 9) = (x2, y2) By Distance Formula, => PQ = √[(x2 – x1)2 + (y2 – y1)2] => PQ = √[(8 – 7)2 + (9 – 3)2] => PQ = √(1 + 62) => PQ = √37 = 6.08 cm (approx) Therefore the distance between points P and Q is 6.08 cm. Problem 3: If the distance between the points (x, 10) and (1, 5) is 13 cm then find the value of x. Solution: Let the coordinates of M = (x, 10) = (x1, y1) Let the coordinates of N = (1, 5) = (x2, y2) By Distance Formula, => MN = √[(x2 – x1)2 + (y2 – y1)2] => 13 = √[(1 – x)2 + (5 – 10)2] (squaring on both sides) => 169 = (1 – x)2 + 25 => (1 – x)2 = 144 => 1 – x = √144 => x = 13 or x = -11 Here we can 2 values of x, they are 13 and -11 Coordinate Geometry Picked Class 10 School Learning School Mathematics Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. HTML Forms Mobile Technologies - Definition, Types, Uses, Advantages Introduction to Internet Number System and Arithmetic Chemical Indicators - Definition, Types, Examples How to Align Text in HTML? Cloud Deployment Models What is a Storage Device? Definition, Types, Examples Libraries in Python Reading Rows from a CSV File in Python
[ { "code": null, "e": 24700, "s": 24672, "text": "\n27 Oct, 2020" }, { "code": null, "e": 24963, "s": 24700, "text": "The distance formula is one of the important concepts in coordinate geometry which is used widely. By using the distance formula we can find the shortest distance i.e drawing a straight line between points. There are two ways to find the distance between points:" }, { "code": null, "e": 24999, "s": 24963, "text": "Pythagorean theoremDistance formula" }, { "code": null, "e": 25019, "s": 24999, "text": "Pythagorean theorem" }, { "code": null, "e": 25036, "s": 25019, "text": "Distance formula" }, { "code": null, "e": 25316, "s": 25036, "text": "This theorem is similar to the Pythagoras theorem but the use of it here is a little different. Normally by Pythagoras theorem, we will find the missing length in the right triangle. Here also we do the same thing but before that, we have to find the coordinates of the triangle." }, { "code": null, "e": 25552, "s": 25316, "text": "Suppose from a point boy walks 4 m to the west and took a turn to the south and walked 3 m. Now to calculate the shortest distance from the initial point to the final point would be the hypotenuse of the formed triangle as shown below." }, { "code": null, "e": 25815, "s": 25552, "text": "In the above diagram as you can see the initial and final points are A and C respectively. The distance is given between points A, B is 4 m and between points B, C is 3 m. To find the shortest distance which is nothing but AC we will use the Pythagorean theorem." }, { "code": null, "e": 25875, "s": 25815, "text": "This is calculated using the Pythagoras theorem as follows:" }, { "code": null, "e": 25894, "s": 25875, "text": "=> AC2 = AB2 + BC2" }, { "code": null, "e": 25912, "s": 25894, "text": "=> AC = √(16 + 9)" }, { "code": null, "e": 25930, "s": 25912, "text": "=> AC = √25 = 5 m" }, { "code": null, "e": 25966, "s": 25930, "text": "Hence the shortest distance is 5 m." }, { "code": null, "e": 26061, "s": 25966, "text": "Problem 1: Using the Pythagorean theorem, find the distance between points (-5, 2) and (7, 2)?" }, { "code": null, "e": 26123, "s": 26061, "text": "Solution: Let’s try to visualize the coordinates on the graph" }, { "code": null, "e": 26256, "s": 26123, "text": "Now, let’s join point A and B with a straight line and also draw the horizontal and vertical lines from points A and B respectively." }, { "code": null, "e": 26389, "s": 26256, "text": "Horizontal and vertical lines coincide at point C. Now we have to find the horizontal and vertical distance i.e length of AC and BC." }, { "code": null, "e": 26425, "s": 26389, "text": "=> AC = (x2 – x1) = (7 – (-5)) = 12" }, { "code": null, "e": 26536, "s": 26425, "text": "=> BC = (y2 – y1) = (2 – 7) = -5 [As distance can’t be negative, we have to only consider numerical value]" }, { "code": null, "e": 26625, "s": 26536, "text": "As you see in the above diagram, now the problem is turned into basic Pythagoras theorem" }, { "code": null, "e": 26644, "s": 26625, "text": "=> AB2 = AC2 + BC2" }, { "code": null, "e": 26662, "s": 26644, "text": "=> AB2 = 52 + 122" }, { "code": null, "e": 26682, "s": 26662, "text": "=> AB = √(25 + 144)" }, { "code": null, "e": 26713, "s": 26682, "text": "=> AB = √169 = 13 square units" }, { "code": null, "e": 26778, "s": 26713, "text": "Therefore, the distance between the given points is 13 sq units." }, { "code": null, "e": 26872, "s": 26778, "text": "Problem 2: Using the Pythagorean theorem, find the distance between points (4, 8) and (6, 4)?" }, { "code": null, "e": 27005, "s": 26872, "text": "Solution: The first thing you have to do after seeing the question is to draw a diagram. Sometimes drawing makes the problem simple." }, { "code": null, "e": 27222, "s": 27005, "text": "As we have to find the distance between points A and B, so first join those points then from point A draw a vertical line and from point B draw a horizontal line and let the point where both extended lines meet be C." }, { "code": null, "e": 27438, "s": 27222, "text": "Now to find the coordinates of point C, we should keenly observe that point C is at the same level as point B i.e the Y coordinate will be the same, and similarly point A and point C will have the same X coordinate." }, { "code": null, "e": 27478, "s": 27438, "text": "So coordinates of AC will become (4, 4)" }, { "code": null, "e": 27519, "s": 27478, "text": "Length of line BC will be (6 – 4) = 2 cm" }, { "code": null, "e": 27560, "s": 27519, "text": "Length of line AC will be (8 – 4) = 4 cm" }, { "code": null, "e": 27593, "s": 27560, "text": "Now by using Pythagoras theorem," }, { "code": null, "e": 27612, "s": 27593, "text": "=> AB2 = AC2 + BC2" }, { "code": null, "e": 27629, "s": 27612, "text": "=> AB2 = 42 + 22" }, { "code": null, "e": 27647, "s": 27629, "text": "=> AB = √(16 + 4)" }, { "code": null, "e": 27675, "s": 27647, "text": "=> AB = √20 = 4.47 (approx)" }, { "code": null, "e": 27727, "s": 27675, "text": "Hence the distance between point A and B is 4.47 cm" }, { "code": null, "e": 27828, "s": 27727, "text": "Problem 3: Given the distance between the points M (x, 2) and N (2, 5) is 5 cm. Find the value of x?" }, { "code": null, "e": 27918, "s": 27828, "text": "Solution: The first step is to draw the diagram for a clear understanding of the problem." }, { "code": null, "e": 28066, "s": 27918, "text": "This problem is different from previous problems because here we have to find x coordinate of point M where distance is given between the points MN" }, { "code": null, "e": 28140, "s": 28066, "text": "Point N is fixed but M is not fixed. But we know y coordinate of point M." }, { "code": null, "e": 28250, "s": 28140, "text": "So we will draw a horizontal at y = 2. But we don’t know the x coordinate we will have several possibilities." }, { "code": null, "e": 28328, "s": 28250, "text": "Now draw a vertical line from point N and name point C where both lines meet." }, { "code": null, "e": 28358, "s": 28328, "text": "Length of NC = (5 – 2) = 3 cm" }, { "code": null, "e": 28384, "s": 28358, "text": "Length of MC = (x – 2) cm" }, { "code": null, "e": 28418, "s": 28384, "text": "And it is already given NM = 5 cm" }, { "code": null, "e": 28447, "s": 28418, "text": "Applying Pythagoras theorem," }, { "code": null, "e": 28466, "s": 28447, "text": "=> NM2 = NC2 + MC2" }, { "code": null, "e": 28488, "s": 28466, "text": "=> 52 = 32 + (x – 2)2" }, { "code": null, "e": 28509, "s": 28488, "text": "=> 25 – 9 = (x – 2)2" }, { "code": null, "e": 28533, "s": 28509, "text": "=> 16 = (4)2 = (x – 2)2" }, { "code": null, "e": 28573, "s": 28533, "text": "After cancelling squares on both sides " }, { "code": null, "e": 28586, "s": 28573, "text": "=> x – 2 = 4" }, { "code": null, "e": 28595, "s": 28586, "text": "=> x = 6" }, { "code": null, "e": 28643, "s": 28595, "text": "Therefore value of x is 6 and point M is (6, 2)" }, { "code": null, "e": 28850, "s": 28643, "text": "The distance formula is used to find the distance between any two given points. By Pythagoras theorem, we can derive the distance formula. Using distance formula is much easier than the Pythagorean theorem." }, { "code": null, "e": 28926, "s": 28850, "text": "AB = √[(x2 - x1)2 + (y2 - y1)2]\n \nwhere points are A(x1, y1) and B(x2, y2)\n" }, { "code": null, "e": 28969, "s": 28926, "text": "Let us look at how this formula is derived" }, { "code": null, "e": 29211, "s": 28969, "text": "In the above diagram, there are 2 points A(x1, y1) and B(x2, y2) for which we have to find the distance between them. Join the points A and B with a straight line. Now draw horizontal lines from points A and B, and they both meet at point C." }, { "code": null, "e": 29266, "s": 29211, "text": "Now the coordinates of point C will become C (x1, y2)." }, { "code": null, "e": 29383, "s": 29266, "text": "Now it looks like a right triangle ACB where side AC is the perpendicular, CB is the base, and AB is the hypotenuse." }, { "code": null, "e": 29544, "s": 29383, "text": "Now we need to find the distance between points A and C. Now by seeing the diagram, the distance between them will be the difference between their y coordinate." }, { "code": null, "e": 29578, "s": 29544, "text": "=> AC = y2 – y1 .......(1)" }, { "code": null, "e": 29671, "s": 29578, "text": "Similarly, the distance between points C and B will be the difference between x coordinates." }, { "code": null, "e": 29705, "s": 29671, "text": "=> CB = x2 – x1 ........(2)" }, { "code": null, "e": 29791, "s": 29705, "text": "∆ACB is a right-angled triangle. We need to find hypotenuse AB, by Pythagoras theorem" }, { "code": null, "e": 29810, "s": 29791, "text": "=> AB2 = BC2 + AC2" }, { "code": null, "e": 29828, "s": 29810, "text": "From (1) and (2)," }, { "code": null, "e": 29861, "s": 29828, "text": "=> AB2 = (x2 – x1)2 + (y2 – y1)2" }, { "code": null, "e": 29896, "s": 29861, "text": "Taking Square roots on both sides," }, { "code": null, "e": 29932, "s": 29896, "text": "=> AB = √{(x2 – x 1)2 + (y2 – y1)2}" }, { "code": null, "e": 29961, "s": 29932, "text": "So the Distance Formula is, " }, { "code": null, "e": 29993, "s": 29961, "text": "AB = √[(x2 – x1)2 + (y2 – y1)2]" }, { "code": null, "e": 30130, "s": 29993, "text": "Problem 1: The coordinates of point A are (-4, 0) and the coordinates of point B are (0, 3). Find the distance between these two points." }, { "code": null, "e": 30141, "s": 30130, "text": "Solution: " }, { "code": null, "e": 30176, "s": 30141, "text": "The coordinates of A are = (-4, 0)" }, { "code": null, "e": 30210, "s": 30176, "text": "The coordinates of B are = (0, 3)" }, { "code": null, "e": 30276, "s": 30210, "text": "Let coordinates of A and B are (x1, y1) and (x2, y2) respectively" }, { "code": null, "e": 30297, "s": 30276, "text": "By Distance Formula," }, { "code": null, "e": 30359, "s": 30297, "text": "=> AB = √[(x2 – x1)2 + (y2 – y1)2] = √[{0 – (-4)}2+ (3 – 0)2]" }, { "code": null, "e": 30391, "s": 30359, "text": "=> √(42 + 32) = √(16 + 9) = √25" }, { "code": null, "e": 30402, "s": 30391, "text": "=> 5 units" }, { "code": null, "e": 30460, "s": 30402, "text": "Therefore the distance between points A and B is 5 units." }, { "code": null, "e": 30527, "s": 30460, "text": "Problem 2: Find the distance between the points (7, 3) and (8, 9)." }, { "code": null, "e": 30537, "s": 30527, "text": "Solution:" }, { "code": null, "e": 30582, "s": 30537, "text": "Let the coordinates of P = (7, 3) = (x1, y1)" }, { "code": null, "e": 30627, "s": 30582, "text": "Let the coordinates of Q = (8, 9) = (x2, y2)" }, { "code": null, "e": 30648, "s": 30627, "text": "By Distance Formula," }, { "code": null, "e": 30683, "s": 30648, "text": "=> PQ = √[(x2 – x1)2 + (y2 – y1)2]" }, { "code": null, "e": 30715, "s": 30683, "text": "=> PQ = √[(8 – 7)2 + (9 – 3)2] " }, { "code": null, "e": 30734, "s": 30715, "text": "=> PQ = √(1 + 62) " }, { "code": null, "e": 30766, "s": 30734, "text": "=> PQ = √37 = 6.08 cm (approx)" }, { "code": null, "e": 30824, "s": 30766, "text": "Therefore the distance between points P and Q is 6.08 cm." }, { "code": null, "e": 30924, "s": 30824, "text": "Problem 3: If the distance between the points (x, 10) and (1, 5) is 13 cm then find the value of x." }, { "code": null, "e": 30934, "s": 30924, "text": "Solution:" }, { "code": null, "e": 30980, "s": 30934, "text": "Let the coordinates of M = (x, 10) = (x1, y1)" }, { "code": null, "e": 31025, "s": 30980, "text": "Let the coordinates of N = (1, 5) = (x2, y2)" }, { "code": null, "e": 31046, "s": 31025, "text": "By Distance Formula," }, { "code": null, "e": 31081, "s": 31046, "text": "=> MN = √[(x2 – x1)2 + (y2 – y1)2]" }, { "code": null, "e": 31113, "s": 31081, "text": "=> 13 = √[(1 – x)2 + (5 – 10)2]" }, { "code": null, "e": 31138, "s": 31113, "text": "(squaring on both sides)" }, { "code": null, "e": 31162, "s": 31138, "text": "=> 169 = (1 – x)2 + 25" }, { "code": null, "e": 31181, "s": 31162, "text": "=> (1 – x)2 = 144 " }, { "code": null, "e": 31197, "s": 31181, "text": "=> 1 – x = √144" }, { "code": null, "e": 31220, "s": 31197, "text": "=> x = 13 or x = -11 " }, { "code": null, "e": 31267, "s": 31220, "text": "Here we can 2 values of x, they are 13 and -11" }, { "code": null, "e": 31287, "s": 31267, "text": "Coordinate Geometry" }, { "code": null, "e": 31294, "s": 31287, "text": "Picked" }, { "code": null, "e": 31303, "s": 31294, "text": "Class 10" }, { "code": null, "e": 31319, "s": 31303, "text": "School Learning" }, { "code": null, "e": 31338, "s": 31319, "text": "School Mathematics" }, { "code": null, "e": 31436, "s": 31338, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31447, "s": 31436, "text": "HTML Forms" }, { "code": null, "e": 31505, "s": 31447, "text": "Mobile Technologies - Definition, Types, Uses, Advantages" }, { "code": null, "e": 31530, "s": 31505, "text": "Introduction to Internet" }, { "code": null, "e": 31559, "s": 31530, "text": "Number System and Arithmetic" }, { "code": null, "e": 31609, "s": 31559, "text": "Chemical Indicators - Definition, Types, Examples" }, { "code": null, "e": 31636, "s": 31609, "text": "How to Align Text in HTML?" }, { "code": null, "e": 31660, "s": 31636, "text": "Cloud Deployment Models" }, { "code": null, "e": 31714, "s": 31660, "text": "What is a Storage Device? Definition, Types, Examples" }, { "code": null, "e": 31734, "s": 31714, "text": "Libraries in Python" } ]
How to store decimal values in a table using PreparedStatement in JDBC?
To insert records into a table that contains a decimal value using PreparedStatement you need to − Register the driver − Register the driver class using the registerDriver() method of the DriverManager class. Pass the driver class name to it, as parameter. Establish a connection − Connect ot the database using the getConnection() method of the DriverManager class. Passing URL (String), username (String), password (String) as parameters to it. Create Statement − Create a PreparedStatement object using the prepareStatement() method of the Connection interface. Pass the INSERT query with place holders to this method in String format as a parameter. PreparedStatement pstmt = con.prepareStatement("INSERT INTO customers VALUES (?, ?, ?, ?, ?)"); Set values to the bind variables using the setXXX() methods. You can set the value to the bind variable representing the column holding the decimal value using the setDouble() method. pstmt.setInt(1,1); pstmt.setString(2, "Amit"); pstmt.setInt(3, 25); pstmt.setDouble(4, 80.5); pstmt.setString(5,"Hyderabad"); pstmt.executeUpdate(); Execute the Query − Execute the CREATE query using the execute() method of the Statement interface. pstmt.execute(); Let us create a customers table in MySQL database using the CREATE statement as shown below − CREATE TABLE Students( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, PERCENTAGE DECIMAL (18, 2), ADDRESS VARCHAR (25), PRIMARY KEY (ID) ); Following JDBC program inserts 3 records into the customers table using PreparedStatement. Here we are using the setDouble() method to set value to the placement holder representing the column that holds the decimal value − import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; public class InsertingDecimalValue { public static void main(String args[]) throws SQLException { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Creating the Statement PreparedStatement pstmt = con.prepareStatement("INSERT INTO STUDENTS VALUES (?, ?, ?, ?, ?)"); pstmt.setInt(1,1); pstmt.setString(2, "Amit"); pstmt.setInt(3, 25); pstmt.setDouble(4, 80.5); pstmt.setString(5,"Hyderabad"); pstmt.executeUpdate(); pstmt.setInt(1,2); pstmt.setString(2, "Kalyan"); pstmt.setInt(3, 27); pstmt.setDouble(4, 83.4); pstmt.setString(5,"Delhi"); pstmt.executeUpdate(); pstmt.setInt(1,3); pstmt.setString(2, "Renuka"); pstmt.setInt(3, 30); pstmt.setDouble(4, 95.6); pstmt.setString(5,"Hyderabad"); pstmt.executeUpdate(); System.out.println("Records inserted ...."); } } Connection established...... Records inserted ....... You can verify the contents of the Students table using the SELECT statement as − mysql> select * from Students; +----+--------+-----+--------+-----------+ | ID | NAME | AGE | SALARY | ADDRESS | +----+--------+-----+--------+-----------+ | 1 | Amit | 25 | 80.50 | Hyderabad | | 2 | Kalyan | 27 | 83.40 | Dlhi | | 3 | Renuka | 30 | 95.60 | Hyderabad | +----+--------+-----+--------+-----------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1161, "s": 1062, "text": "To insert records into a table that contains a decimal value using PreparedStatement you need to −" }, { "code": null, "e": 1319, "s": 1161, "text": "Register the driver − Register the driver class using the registerDriver() method of the DriverManager class. Pass the driver class name to it, as parameter." }, { "code": null, "e": 1509, "s": 1319, "text": "Establish a connection − Connect ot the database using the getConnection() method of the DriverManager class. Passing URL (String), username (String), password (String) as parameters to it." }, { "code": null, "e": 1716, "s": 1509, "text": "Create Statement − Create a PreparedStatement object using the prepareStatement() method of the Connection interface. Pass the INSERT query with place holders to this method in String format as a parameter." }, { "code": null, "e": 1812, "s": 1716, "text": "PreparedStatement pstmt = con.prepareStatement(\"INSERT INTO customers VALUES (?, ?, ?, ?, ?)\");" }, { "code": null, "e": 1996, "s": 1812, "text": "Set values to the bind variables using the setXXX() methods. You can set the value to the bind variable representing the column holding the decimal value using the setDouble() method." }, { "code": null, "e": 2145, "s": 1996, "text": "pstmt.setInt(1,1);\npstmt.setString(2, \"Amit\");\npstmt.setInt(3, 25);\npstmt.setDouble(4, 80.5);\npstmt.setString(5,\"Hyderabad\");\npstmt.executeUpdate();" }, { "code": null, "e": 2245, "s": 2145, "text": "Execute the Query − Execute the CREATE query using the execute() method of the Statement interface." }, { "code": null, "e": 2262, "s": 2245, "text": "pstmt.execute();" }, { "code": null, "e": 2356, "s": 2262, "text": "Let us create a customers table in MySQL database using the CREATE statement as shown below −" }, { "code": null, "e": 2530, "s": 2356, "text": "CREATE TABLE Students(\n ID INT NOT NULL,\n NAME VARCHAR (20) NOT NULL,\n AGE INT NOT NULL,\n PERCENTAGE DECIMAL (18, 2),\n ADDRESS VARCHAR (25),\n PRIMARY KEY (ID)\n);" }, { "code": null, "e": 2754, "s": 2530, "text": "Following JDBC program inserts 3 records into the customers table using PreparedStatement. Here we are using the setDouble() method to set value to the placement holder representing the column that holds the decimal value −" }, { "code": null, "e": 4079, "s": 2754, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.SQLException;\nimport java.sql.Statement;\npublic class InsertingDecimalValue {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating the Statement\n PreparedStatement pstmt = con.prepareStatement(\"INSERT INTO STUDENTS VALUES (?, ?, ?, ?, ?)\");\n pstmt.setInt(1,1);\n pstmt.setString(2, \"Amit\");\n pstmt.setInt(3, 25);\n pstmt.setDouble(4, 80.5);\n pstmt.setString(5,\"Hyderabad\");\n pstmt.executeUpdate();\n pstmt.setInt(1,2);\n pstmt.setString(2, \"Kalyan\");\n pstmt.setInt(3, 27);\n pstmt.setDouble(4, 83.4);\n pstmt.setString(5,\"Delhi\");\n pstmt.executeUpdate();\n pstmt.setInt(1,3);\n pstmt.setString(2, \"Renuka\");\n pstmt.setInt(3, 30);\n pstmt.setDouble(4, 95.6);\n pstmt.setString(5,\"Hyderabad\");\n pstmt.executeUpdate();\n System.out.println(\"Records inserted ....\");\n }\n}" }, { "code": null, "e": 4133, "s": 4079, "text": "Connection established......\nRecords inserted ......." }, { "code": null, "e": 4215, "s": 4133, "text": "You can verify the contents of the Students table using the SELECT statement as −" }, { "code": null, "e": 4572, "s": 4215, "text": "mysql> select * from Students;\n+----+--------+-----+--------+-----------+\n| ID | NAME | AGE | SALARY | ADDRESS |\n+----+--------+-----+--------+-----------+\n| 1 | Amit | 25 | 80.50 | Hyderabad |\n| 2 | Kalyan | 27 | 83.40 | Dlhi |\n| 3 | Renuka | 30 | 95.60 | Hyderabad |\n+----+--------+-----+--------+-----------+\n3 rows in set (0.00 sec)" } ]
Create and Access a Python Package
In this article, we are going to learn about the packages in Python. Packages help us to structure packages and modules in an organized hierarchy. Let's see how to create packages in Python. We have included a __init__.py, file inside a directory to tell Python that the current directory is a package. Whenever you want to create a package, then you have to include __init__.py file in the directory. You can write code inside or leave it as blank as your wish. It doesn't bothers Python. Follow the below steps to create a package in Python Create a directory and include a __init__.py file in it to tell Python that the current directory is a package. Include other sub-packages or files you want. Next, access them with the valid import statements. Let's create a simple package that has the following structure. Package (university) __init__.py student.py faculty.py Go to any directory in your laptop or desktop and create the above folder structure. After creating the above folder structure include the following code in respective files. # student.py class Student: def __init__(self, student): self.name = student['name'] self.gender = student['gender'] self.year = student['year'] def get_student_details(self): return f"Name: {self.name}\nGender: {self.gender}\nYear: {self.year}" # faculty.py class Faculty: def __init__(self, faculty): self.name = faculty['name'] self.subject = faculty['subject'] def get_faculty_details(self): return f"Name: {self.name}\nSubject: {self.subject}" We have the above in the student.py and faculty.py files. Let's create another file to access those classed inside it. Now, inside the package directory create a file named testing.py and include the following code. # testing.py # importing the Student and Faculty classes from respective files from student import Student from faculty import Faculty # creating dicts for student and faculty student_dict = {'name' : 'John', 'gender': 'Male', 'year': '3'} faculty_dict = {'name': 'Emma', 'subject': 'Programming'} # creating instances of the Student and Faculty classes student = Student(student_dict) faculty = Faculty(faculty_dict) # getting and printing the student and faculty details print(student.get_student_details()) print() print(faculty.get_faculty_details()) If you run the testing.py file, then you will get the following result. Name: John Gender: Male Year: 3 Name: Emma Subject: Programming We have seen how to create and to access a package in Python. And this is a simple package. There might be plenty of sub-packages and files inside a package. Let's see how to access subpackage modules. Create a directory with the following structure Package (university)__init__.pySubpackage (student)__init__.pymain.py...testing.py __init__.py Subpackage (student)__init__.pymain.py... __init__.py main.py ... testing.py Copy the above student code and place it here. Now, let's see how to access it in the testing.py file. Add the following in the testing.py file. # testing.py from student.main import Student # creating dicts for student student_dict = {'name' : 'John', 'gender': 'Male', 'year': '3'} # creating instances of the Student class student = Student(student_dict) # getting and printing the student details print(student.get_student_details()) If you run the testing.py file, then you will get the following result. Name: John Gender: Male Year: 3 We have accessed the Student class from the main.py file inside the subpackage student using a dot (.). You can go to as much deeper as you want based on the package structure. If you have any doubts in the tutorial, mention them in the comment section.
[ { "code": null, "e": 1253, "s": 1062, "text": "In this article, we are going to learn about the packages in Python. Packages help us to structure packages and modules in an organized hierarchy. Let's see how to create packages in Python." }, { "code": null, "e": 1552, "s": 1253, "text": "We have included a __init__.py, file inside a directory to tell Python that the current directory is a package. Whenever you want to create a package, then you have to include __init__.py file in the directory. You can write code inside or leave it as blank as your wish. It doesn't bothers Python." }, { "code": null, "e": 1605, "s": 1552, "text": "Follow the below steps to create a package in Python" }, { "code": null, "e": 1717, "s": 1605, "text": "Create a directory and include a __init__.py file in it to tell Python that the current directory is a package." }, { "code": null, "e": 1763, "s": 1717, "text": "Include other sub-packages or files you want." }, { "code": null, "e": 1815, "s": 1763, "text": "Next, access them with the valid import statements." }, { "code": null, "e": 1879, "s": 1815, "text": "Let's create a simple package that has the following structure." }, { "code": null, "e": 1900, "s": 1879, "text": "Package (university)" }, { "code": null, "e": 1912, "s": 1900, "text": "__init__.py" }, { "code": null, "e": 1923, "s": 1912, "text": "student.py" }, { "code": null, "e": 1934, "s": 1923, "text": "faculty.py" }, { "code": null, "e": 2109, "s": 1934, "text": "Go to any directory in your laptop or desktop and create the above folder structure. After creating the above folder structure include the following code in respective files." }, { "code": null, "e": 2618, "s": 2109, "text": "# student.py\nclass Student:\n\n def __init__(self, student):\n self.name = student['name']\n self.gender = student['gender']\n self.year = student['year']\n\n def get_student_details(self):\n return f\"Name: {self.name}\\nGender: {self.gender}\\nYear: {self.year}\"\n\n\n# faculty.py\nclass Faculty:\n\n def __init__(self, faculty):\n self.name = faculty['name']\n self.subject = faculty['subject']\n\n def get_faculty_details(self):\n return f\"Name: {self.name}\\nSubject: {self.subject}\"" }, { "code": null, "e": 2834, "s": 2618, "text": "We have the above in the student.py and faculty.py files. Let's create another file to access those classed inside it. Now, inside the package directory create a file named testing.py and include the following code." }, { "code": null, "e": 3392, "s": 2834, "text": "# testing.py\n# importing the Student and Faculty classes from respective files\nfrom student import Student\nfrom faculty import Faculty\n\n# creating dicts for student and faculty\nstudent_dict = {'name' : 'John', 'gender': 'Male', 'year': '3'}\nfaculty_dict = {'name': 'Emma', 'subject': 'Programming'}\n\n# creating instances of the Student and Faculty classes\nstudent = Student(student_dict)\nfaculty = Faculty(faculty_dict)\n\n# getting and printing the student and faculty details\nprint(student.get_student_details())\nprint()\nprint(faculty.get_faculty_details())" }, { "code": null, "e": 3464, "s": 3392, "text": "If you run the testing.py file, then you will get the following result." }, { "code": null, "e": 3529, "s": 3464, "text": "Name: John\nGender: Male\nYear: 3\n\nName: Emma\nSubject: Programming" }, { "code": null, "e": 3731, "s": 3529, "text": "We have seen how to create and to access a package in Python. And this is a simple package. There might be plenty of sub-packages and files inside a package. Let's see how to access subpackage modules." }, { "code": null, "e": 3779, "s": 3731, "text": "Create a directory with the following structure" }, { "code": null, "e": 3862, "s": 3779, "text": "Package (university)__init__.pySubpackage (student)__init__.pymain.py...testing.py" }, { "code": null, "e": 3874, "s": 3862, "text": "__init__.py" }, { "code": null, "e": 3916, "s": 3874, "text": "Subpackage (student)__init__.pymain.py..." }, { "code": null, "e": 3928, "s": 3916, "text": "__init__.py" }, { "code": null, "e": 3936, "s": 3928, "text": "main.py" }, { "code": null, "e": 3940, "s": 3936, "text": "..." }, { "code": null, "e": 3951, "s": 3940, "text": "testing.py" }, { "code": null, "e": 4096, "s": 3951, "text": "Copy the above student code and place it here. Now, let's see how to access it in the testing.py file. Add the following in the testing.py file." }, { "code": null, "e": 4392, "s": 4096, "text": "# testing.py\nfrom student.main import Student\n\n# creating dicts for student\nstudent_dict = {'name' : 'John', 'gender': 'Male', 'year': '3'}\n\n# creating instances of the Student class\nstudent = Student(student_dict)\n\n# getting and printing the student details\nprint(student.get_student_details())" }, { "code": null, "e": 4464, "s": 4392, "text": "If you run the testing.py file, then you will get the following result." }, { "code": null, "e": 4496, "s": 4464, "text": "Name: John\nGender: Male\nYear: 3" }, { "code": null, "e": 4673, "s": 4496, "text": "We have accessed the Student class from the main.py file inside the subpackage student using a dot (.). You can go to as much deeper as you want based on the package structure." }, { "code": null, "e": 4750, "s": 4673, "text": "If you have any doubts in the tutorial, mention them in the comment section." } ]
Find the frequency of a digit in a number using C++.
Here we will see how to get the frequency of a digit in a number. Suppose a number is like 12452321, the digit D = 2, then the frequency is 3. To solve this problem, we take the last digit from the number, then check whether this is equal to d or not, if so then increase the counter, then reduce the number by dividing the number by 10. This process will be continued until the number is exhausted. Live Demo #include<iostream> using namespace std; int countDigitInNum(long long number, int d) { int count = 0; while(number){ if((number % 10) == d) count++; number /= 10; } return count; } int main () { long long num = 12452321; int d = 2; cout << "Frequency of " << 2 << " in " << num << " is: " << countDigitInNum(num, d); } Frequency of 2 in 12452321 is: 3
[ { "code": null, "e": 1205, "s": 1062, "text": "Here we will see how to get the frequency of a digit in a number. Suppose a number is like 12452321, the digit D = 2, then the frequency is 3." }, { "code": null, "e": 1462, "s": 1205, "text": "To solve this problem, we take the last digit from the number, then check whether this is equal to d or not, if so then increase the counter, then reduce the number by dividing the number by 10. This process will be continued until the number is exhausted." }, { "code": null, "e": 1473, "s": 1462, "text": " Live Demo" }, { "code": null, "e": 1834, "s": 1473, "text": "#include<iostream>\nusing namespace std;\nint countDigitInNum(long long number, int d) {\n int count = 0;\n while(number){\n if((number % 10) == d)\n count++;\n number /= 10;\n }\n return count;\n}\nint main () {\n long long num = 12452321;\n int d = 2;\n cout << \"Frequency of \" << 2 << \" in \" << num << \" is: \" << countDigitInNum(num, d);\n}" }, { "code": null, "e": 1867, "s": 1834, "text": "Frequency of 2 in 12452321 is: 3" } ]
Lodash _.isNumeric() Method - GeeksforGeeks
30 Sep, 2020 The Lodash _.isNumeric() method checks whether the given value is a Numeric value or not and returns the corresponding boolean value. It can be a string containing a numeric value, exponential notation or a Number object, etc. Syntax: _.isNumeric( value ); Parameters: This method takes single parameter as mentioned above and described below: value: Given value to be checked for Numeric value. Return Value: This method returns a Boolean value true if the given value is Numeric, else false. Note: This will not work in normal JavaScript because it requires the lodash.js contrib library to be installed. Lodash.js contrib library can be installed using npm install lodash-contrib. Example 1: Javascript // Defining lodash contrib variable var _ = require('lodash-contrib'); // Checking for _.isNumeric() methodconsole.log("The Value is Numeric : " + _.isNumeric(10000)); console.log("The Value is Negative : " + _.isNumeric(10.5)); console.log("The Value is Negative : " + _.isNumeric('G')); console.log("The Value is Negative : " + _.isNumeric('Geeks')); Output: The Value is Numeric : true The Value is Negative : true The Value is Negative : false The Value is Negative : false Example 2: Javascript // Defining lodash contrib variable var _ = require('lodash-contrib'); // Checking for _.isNumeric() methodconsole.log("The Value is Numeric : " + _.isNumeric([1,10])); console.log("The Value is Negative : " + _.isNumeric("500")); console.log("The Value is Negative : " + _.isNumeric({})); console.log("The Value is Negative : " + _.isNumeric(null)); Output: The Value is Numeric : false The Value is Negative : true The Value is Negative : false The Value is Negative : false JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array 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? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 27096, "s": 27068, "text": "\n30 Sep, 2020" }, { "code": null, "e": 27323, "s": 27096, "text": "The Lodash _.isNumeric() method checks whether the given value is a Numeric value or not and returns the corresponding boolean value. It can be a string containing a numeric value, exponential notation or a Number object, etc." }, { "code": null, "e": 27331, "s": 27323, "text": "Syntax:" }, { "code": null, "e": 27354, "s": 27331, "text": "_.isNumeric( value );\n" }, { "code": null, "e": 27441, "s": 27354, "text": "Parameters: This method takes single parameter as mentioned above and described below:" }, { "code": null, "e": 27493, "s": 27441, "text": "value: Given value to be checked for Numeric value." }, { "code": null, "e": 27591, "s": 27493, "text": "Return Value: This method returns a Boolean value true if the given value is Numeric, else false." }, { "code": null, "e": 27781, "s": 27591, "text": "Note: This will not work in normal JavaScript because it requires the lodash.js contrib library to be installed. Lodash.js contrib library can be installed using npm install lodash-contrib." }, { "code": null, "e": 27792, "s": 27781, "text": "Example 1:" }, { "code": null, "e": 27803, "s": 27792, "text": "Javascript" }, { "code": "// Defining lodash contrib variable var _ = require('lodash-contrib'); // Checking for _.isNumeric() methodconsole.log(\"The Value is Numeric : \" + _.isNumeric(10000)); console.log(\"The Value is Negative : \" + _.isNumeric(10.5)); console.log(\"The Value is Negative : \" + _.isNumeric('G')); console.log(\"The Value is Negative : \" + _.isNumeric('Geeks'));", "e": 28165, "s": 27803, "text": null }, { "code": null, "e": 28173, "s": 28165, "text": "Output:" }, { "code": null, "e": 28291, "s": 28173, "text": "The Value is Numeric : true\nThe Value is Negative : true\nThe Value is Negative : false\nThe Value is Negative : false\n" }, { "code": null, "e": 28302, "s": 28291, "text": "Example 2:" }, { "code": null, "e": 28313, "s": 28302, "text": "Javascript" }, { "code": "// Defining lodash contrib variable var _ = require('lodash-contrib'); // Checking for _.isNumeric() methodconsole.log(\"The Value is Numeric : \" + _.isNumeric([1,10])); console.log(\"The Value is Negative : \" + _.isNumeric(\"500\")); console.log(\"The Value is Negative : \" + _.isNumeric({})); console.log(\"The Value is Negative : \" + _.isNumeric(null));", "e": 28673, "s": 28313, "text": null }, { "code": null, "e": 28681, "s": 28673, "text": "Output:" }, { "code": null, "e": 28800, "s": 28681, "text": "The Value is Numeric : false\nThe Value is Negative : true\nThe Value is Negative : false\nThe Value is Negative : false\n" }, { "code": null, "e": 28818, "s": 28800, "text": "JavaScript-Lodash" }, { "code": null, "e": 28829, "s": 28818, "text": "JavaScript" }, { "code": null, "e": 28846, "s": 28829, "text": "Web Technologies" }, { "code": null, "e": 28944, "s": 28846, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28984, "s": 28944, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29045, "s": 28984, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29086, "s": 29045, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29108, "s": 29086, "text": "JavaScript | Promises" }, { "code": null, "e": 29162, "s": 29108, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 29202, "s": 29162, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29235, "s": 29202, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29278, "s": 29235, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29328, "s": 29278, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
100x faster Hyperparameter Search Framework with Pyspark | by Rahul Agarwal | Towards Data Science
Recently I was working on tuning hyperparameters for a huge Machine Learning model. Manual tuning was not an option since I had to tweak a lot of parameters. Hyperopt was also not an option as it works serially i.e. at a time, only a single model is being built. So it was taking up a lot of time to train each model and I was pretty short on time. I had to come up with a better more efficient approach if I were to meet the deadline. So I thought of the one thing that helps us data scientists in many such scenarios — Parallelization. Can I parallelize my model hyperparameter search process? As you would have guessed, the answer is Yes. This post is about setting up a hyperparameter tuning framework for Data Science using scikit-learn/xgboost/lightgbm and pySpark. Before we get to implementing the hyperparameter search, we have two options to set up the hyperparameter search — Grid Search or Random search. The figure above gives a definitive answer as to why Random search is better. Let’s say we have to tune two hyperparameters for our Machine Learning model. One is not important, and one is very important. In a grid search, we look at three settings for the important parameter. While in a randomized search, we search through 9 settings for the important parameter. And the amount of time we spent is the same. Since, Randomized search, searches more thoroughly through the whole space and provides us with better hyperparameters, we will go with it in our example. At my workplace, I have access to a pretty darn big cluster with 100s of nodes. It is a data Scientist’s dream. But in this post, I am going to be using the Databricks Community Edition Free server with a toy example. If you want to set up this small server for yourself for practice, check out my post on Spark. You can choose to load your data using Spark, but here I start by creating our own classification data to set up a minimal example which we can work with. X,y = datasets.make_classification(n_samples=10000, n_features=4, n_informative=2, n_classes=2, random_state=1,shuffle=True)train = pd.DataFrame(X)train['target'] = y# Convert this pandas Data to spark Dataframe. train_sp = spark.createDataFrame(train)# Change the column names.train_sp = train_sp.toDF(*['c0', 'c1', 'c2', 'c3', 'target']) The train_sp spark dataset looks like: So now we have got our training dataset in Spark. And we want to run multiple models on this DataFrame. Spark is inherently good with Key-Value pairs. That is all data with a particular key could be sent to a single machine. And we can apply functions to that data. But we want all our data on every machine. How do we do that? We replicate our data n times and add a replication_id to our data so that each key has all the data. Ok, now we can send the whole data to multiple machines using groupby on replication_id. But how do we use pandas and scikit learn on that data? The answer is: we use pandas_udf. This functionality was introduced in the Spark version 2.3.1. And this allows you to utilise pandas functionality with Spark. If you don’t understand this yet, do look at the code as sometimes it is easier to understand the code. We first replicate our train dataframe 100 times here by using cross_join with a data frame that contains a column with 1–100 replication_id. # replicate the spark dataframe into multiple copiesreplication_df = spark.createDataFrame(pd.DataFrame(list(range(1,100)),columns=['replication_id']))replicated_train_df = train_sp.crossJoin(replication_df) We also define a function that takes as input a pandas dataframe, gets random hyperparameters using the python random module, runs a model on data(Here I am training a scikit model, but you can replace it with any model like XGBoost or Lightgbm as well) and returns the result in the form of a Pandas Dataframe. Do take a look at the function and the comments. We can now apply this pandas_udf function to our replicated dataframe using: results = replicated_train_df.groupby("replication_id").apply(run_model) What the above code does is that it sends all the data with the same replication id to a single machine and applies the function run_model to the data. The above call happens lazily so you won’t be able to see the results till you run the below action call. results.sort(F.desc("Accuracy")).show() For this toy example, the accuracy results may look pretty close to one another, but they will differ in the case of noisy real-world datasets. Since all of these 100 models run in parallel on different nodes, we can save a lot of time when doing random hyperparameter search. The speedup factor certainly depends on how many nodes you have in your cluster. For me, I had 100 machines at my disposal, so I got ~ 100x speedup. You can get the full code in this Databricks Notebook or get it from my GitHub repository where I keep codes for all my posts. If you want to learn more about practical data science, do take a look at the “How to win a data science competition” Coursera course. I learned a lot of new things from this course taught by one of the most prolific Kaggler. Thanks for the read. I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz. Also, a small disclaimer — There might be some affiliate links in this post to relevant resources as sharing knowledge is never a bad idea.
[ { "code": null, "e": 255, "s": 171, "text": "Recently I was working on tuning hyperparameters for a huge Machine Learning model." }, { "code": null, "e": 520, "s": 255, "text": "Manual tuning was not an option since I had to tweak a lot of parameters. Hyperopt was also not an option as it works serially i.e. at a time, only a single model is being built. So it was taking up a lot of time to train each model and I was pretty short on time." }, { "code": null, "e": 709, "s": 520, "text": "I had to come up with a better more efficient approach if I were to meet the deadline. So I thought of the one thing that helps us data scientists in many such scenarios — Parallelization." }, { "code": null, "e": 767, "s": 709, "text": "Can I parallelize my model hyperparameter search process?" }, { "code": null, "e": 813, "s": 767, "text": "As you would have guessed, the answer is Yes." }, { "code": null, "e": 943, "s": 813, "text": "This post is about setting up a hyperparameter tuning framework for Data Science using scikit-learn/xgboost/lightgbm and pySpark." }, { "code": null, "e": 1088, "s": 943, "text": "Before we get to implementing the hyperparameter search, we have two options to set up the hyperparameter search — Grid Search or Random search." }, { "code": null, "e": 1166, "s": 1088, "text": "The figure above gives a definitive answer as to why Random search is better." }, { "code": null, "e": 1499, "s": 1166, "text": "Let’s say we have to tune two hyperparameters for our Machine Learning model. One is not important, and one is very important. In a grid search, we look at three settings for the important parameter. While in a randomized search, we search through 9 settings for the important parameter. And the amount of time we spent is the same." }, { "code": null, "e": 1654, "s": 1499, "text": "Since, Randomized search, searches more thoroughly through the whole space and provides us with better hyperparameters, we will go with it in our example." }, { "code": null, "e": 1967, "s": 1654, "text": "At my workplace, I have access to a pretty darn big cluster with 100s of nodes. It is a data Scientist’s dream. But in this post, I am going to be using the Databricks Community Edition Free server with a toy example. If you want to set up this small server for yourself for practice, check out my post on Spark." }, { "code": null, "e": 2122, "s": 1967, "text": "You can choose to load your data using Spark, but here I start by creating our own classification data to set up a minimal example which we can work with." }, { "code": null, "e": 2462, "s": 2122, "text": "X,y = datasets.make_classification(n_samples=10000, n_features=4, n_informative=2, n_classes=2, random_state=1,shuffle=True)train = pd.DataFrame(X)train['target'] = y# Convert this pandas Data to spark Dataframe. train_sp = spark.createDataFrame(train)# Change the column names.train_sp = train_sp.toDF(*['c0', 'c1', 'c2', 'c3', 'target'])" }, { "code": null, "e": 2501, "s": 2462, "text": "The train_sp spark dataset looks like:" }, { "code": null, "e": 2605, "s": 2501, "text": "So now we have got our training dataset in Spark. And we want to run multiple models on this DataFrame." }, { "code": null, "e": 2767, "s": 2605, "text": "Spark is inherently good with Key-Value pairs. That is all data with a particular key could be sent to a single machine. And we can apply functions to that data." }, { "code": null, "e": 2829, "s": 2767, "text": "But we want all our data on every machine. How do we do that?" }, { "code": null, "e": 2931, "s": 2829, "text": "We replicate our data n times and add a replication_id to our data so that each key has all the data." }, { "code": null, "e": 3076, "s": 2931, "text": "Ok, now we can send the whole data to multiple machines using groupby on replication_id. But how do we use pandas and scikit learn on that data?" }, { "code": null, "e": 3236, "s": 3076, "text": "The answer is: we use pandas_udf. This functionality was introduced in the Spark version 2.3.1. And this allows you to utilise pandas functionality with Spark." }, { "code": null, "e": 3340, "s": 3236, "text": "If you don’t understand this yet, do look at the code as sometimes it is easier to understand the code." }, { "code": null, "e": 3482, "s": 3340, "text": "We first replicate our train dataframe 100 times here by using cross_join with a data frame that contains a column with 1–100 replication_id." }, { "code": null, "e": 3690, "s": 3482, "text": "# replicate the spark dataframe into multiple copiesreplication_df = spark.createDataFrame(pd.DataFrame(list(range(1,100)),columns=['replication_id']))replicated_train_df = train_sp.crossJoin(replication_df)" }, { "code": null, "e": 4051, "s": 3690, "text": "We also define a function that takes as input a pandas dataframe, gets random hyperparameters using the python random module, runs a model on data(Here I am training a scikit model, but you can replace it with any model like XGBoost or Lightgbm as well) and returns the result in the form of a Pandas Dataframe. Do take a look at the function and the comments." }, { "code": null, "e": 4128, "s": 4051, "text": "We can now apply this pandas_udf function to our replicated dataframe using:" }, { "code": null, "e": 4201, "s": 4128, "text": "results = replicated_train_df.groupby(\"replication_id\").apply(run_model)" }, { "code": null, "e": 4459, "s": 4201, "text": "What the above code does is that it sends all the data with the same replication id to a single machine and applies the function run_model to the data. The above call happens lazily so you won’t be able to see the results till you run the below action call." }, { "code": null, "e": 4499, "s": 4459, "text": "results.sort(F.desc(\"Accuracy\")).show()" }, { "code": null, "e": 4776, "s": 4499, "text": "For this toy example, the accuracy results may look pretty close to one another, but they will differ in the case of noisy real-world datasets. Since all of these 100 models run in parallel on different nodes, we can save a lot of time when doing random hyperparameter search." }, { "code": null, "e": 4925, "s": 4776, "text": "The speedup factor certainly depends on how many nodes you have in your cluster. For me, I had 100 machines at my disposal, so I got ~ 100x speedup." }, { "code": null, "e": 5052, "s": 4925, "text": "You can get the full code in this Databricks Notebook or get it from my GitHub repository where I keep codes for all my posts." }, { "code": null, "e": 5278, "s": 5052, "text": "If you want to learn more about practical data science, do take a look at the “How to win a data science competition” Coursera course. I learned a lot of new things from this course taught by one of the most prolific Kaggler." }, { "code": null, "e": 5542, "s": 5278, "text": "Thanks for the read. I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz." } ]
Sum of all elements of N-ary Tree - GeeksforGeeks
08 Nov, 2021 Given an N-ary tree, find sum of all elements in it. Example : Input : Above tree Output : Sum is 536 Approach : The approach used is similar to Level Order traversal in a binary tree. Start by pushing the root node in the queue. And for each node, while popping it from queue, add the value of this node in the sum variable and push the children of the popped element in the queue. In case of a generic tree store child nodes in a vector. Thus, put all elements of the vector in the queue.Below is the implementation of the above idea : C++ Java Python3 C# Javascript // C++ program to find sum of all// elements in generic tree#include <bits/stdc++.h>using namespace std; // Represents a node of an n-ary treestruct Node { int key; vector<Node*> child;}; // Utility function to create a new tree nodeNode* newNode(int key){ Node* temp = new Node; temp->key = key; return temp;} // Function to compute the sum// of all elements in generic treeint sumNodes(Node* root){ // initialize the sum variable int sum = 0; if (root == NULL) return 0; // Creating a queue and pushing the root queue<Node*> q; q.push(root); while (!q.empty()) { int n = q.size(); // If this node has children while (n > 0) { // Dequeue an item from queue and // add it to variable "sum" Node* p = q.front(); q.pop(); sum += p->key; // Enqueue all children of the dequeued item for (int i = 0; i < p->child.size(); i++) q.push(p->child[i]); n--; } } return sum;} // Driver programint main(){ // Creating a generic tree Node* root = newNode(20); (root->child).push_back(newNode(2)); (root->child).push_back(newNode(34)); (root->child).push_back(newNode(50)); (root->child).push_back(newNode(60)); (root->child).push_back(newNode(70)); (root->child[0]->child).push_back(newNode(15)); (root->child[0]->child).push_back(newNode(20)); (root->child[1]->child).push_back(newNode(30)); (root->child[2]->child).push_back(newNode(40)); (root->child[2]->child).push_back(newNode(100)); (root->child[2]->child).push_back(newNode(20)); (root->child[0]->child[1]->child).push_back(newNode(25)); (root->child[0]->child[1]->child).push_back(newNode(50)); cout << sumNodes(root) << endl; return 0;} // Java program to find sum of all// elements in generic treeimport java.util.*; class GFG{ // Represents a node of an n-ary treestatic class Node{ int key; Vector<Node> child;}; // Utility function to create a new tree nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.child = new Vector<>(); return temp;} // Function to compute the sum// of all elements in generic treestatic int sumNodes(Node root){ // initialize the sum variable int sum = 0; if (root == null) return 0; // Creating a queue and pushing the root Queue<Node> q = new LinkedList<>(); q.add(root); while (!q.isEmpty()) { int n = q.size(); // If this node has children while (n > 0) { // Dequeue an item from queue and // add it to variable "sum" Node p = q.peek(); q.remove(); sum += p.key; // Enqueue all children of the dequeued item for (int i = 0; i < p.child.size(); i++) q.add(p.child.get(i)); n--; } } return sum;} // Driver programpublic static void main(String[] args){ // Creating a generic tree Node root = newNode(20); (root.child).add(newNode(2)); (root.child).add(newNode(34)); (root.child).add(newNode(50)); (root.child).add(newNode(60)); (root.child).add(newNode(70)); (root.child.get(0).child).add(newNode(15)); (root.child.get(0).child).add(newNode(20)); (root.child.get(1).child).add(newNode(30)); (root.child.get(2).child).add(newNode(40)); (root.child.get(2).child).add(newNode(100)); (root.child.get(2).child).add(newNode(20)); (root.child.get(0).child.get(1).child).add(newNode(25)); (root.child.get(0).child.get(1).child).add(newNode(50)); System.out.print(sumNodes(root) +"\n");}} // This code is contributed by 29AjayKumar # Python3 program to find sum of all# elements in generic tree # Represents a node of an n-ary treeclass Node: def __init__(self): self.key = 0 self.child = [] # Utility function to create a new tree nodedef newNode(key): temp = Node() temp.key = key temp.child = [] return temp # Function to compute the sum# of all elements in generic treedef sumNodes(root): # initialize the sum variable Sum = 0 if root == None: return 0 # Creating a queue and pushing the root q = [] q.append(root) while len(q) != 0: n = len(q) # If this node has children while n > 0: # Dequeue an item from queue and # add it to variable "sum" p = q[0] q.pop(0) Sum += p.key # push all children of the dequeued item for i in range(len(p.child)): q.append(p.child[i]) n-=1 return Sum # Creating a generic treeroot = newNode(20)(root.child).append(newNode(2))(root.child).append(newNode(34))(root.child).append(newNode(50))(root.child).append(newNode(60))(root.child).append(newNode(70))(root.child[0].child).append(newNode(15))(root.child[0].child).append(newNode(20))(root.child[1].child).append(newNode(30))(root.child[2].child).append(newNode(40))(root.child[2].child).append(newNode(100))(root.child[2].child).append(newNode(20))(root.child[0].child[1].child).append(newNode(25))(root.child[0].child[1].child).append(newNode(50))print(sumNodes(root)) # This code is contributed by divyeshrabadiya07. // C# program to find sum of all// elements in generic treeusing System;using System.Collections.Generic; class GFG{ // Represents a node of an n-ary treeclass Node{ public int key; public List<Node> child;}; // Utility function to create a new tree nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.child = new List<Node>(); return temp;} // Function to compute the sum// of all elements in generic treestatic int sumNodes(Node root){ // initialize the sum variable int sum = 0; if (root == null) return 0; // Creating a queue and pushing the root Queue<Node> q = new Queue<Node>(); q.Enqueue(root); while (q.Count != 0) { int n = q.Count; // If this node has children while (n > 0) { // Dequeue an item from queue and // add it to variable "sum" Node p = q.Peek(); q.Dequeue(); sum += p.key; // Enqueue all children of the dequeued item for (int i = 0; i < p.child.Count; i++) q.Enqueue(p.child[i]); n--; } } return sum;} // Driver programpublic static void Main(String[] args){ // Creating a generic tree Node root = newNode(20); (root.child).Add(newNode(2)); (root.child).Add(newNode(34)); (root.child).Add(newNode(50)); (root.child).Add(newNode(60)); (root.child).Add(newNode(70)); (root.child[0].child).Add(newNode(15)); (root.child[0].child).Add(newNode(20)); (root.child[1].child).Add(newNode(30)); (root.child[2].child).Add(newNode(40)); (root.child[2].child).Add(newNode(100)); (root.child[2].child).Add(newNode(20)); (root.child[0].child[1].child).Add(newNode(25)); (root.child[0].child[1].child).Add(newNode(50)); Console.Write(sumNodes(root) +"\n");}} // This code is contributed by PrinciRaj1992 <script> // JavaScript program to find sum of all// elements in generic tree // Represents a node of an n-ary treeclass Node{ constructor() { this.key = 0; this.child = []; }}; // Utility function to create a new tree nodefunction newNode(key){ var temp = new Node(); temp.key = key; temp.child = []; return temp;} // Function to compute the sum// of all elements in generic treefunction sumNodes(root){ // initialize the sum variable var sum = 0; if (root == null) return 0; // Creating a queue and pushing the root var q = []; q.push(root); while (q.length != 0) { var n = q.length; // If this node has children while (n > 0) { // Dequeue an item from queue and // add it to variable "sum" var p = q[0]; q.shift(); sum += p.key; // push all children of the dequeued item for (var i = 0; i < p.child.length; i++) q.push(p.child[i]); n--; } } return sum;} // Driver program// Creating a generic treevar root = newNode(20);(root.child).push(newNode(2));(root.child).push(newNode(34));(root.child).push(newNode(50));(root.child).push(newNode(60));(root.child).push(newNode(70));(root.child[0].child).push(newNode(15));(root.child[0].child).push(newNode(20));(root.child[1].child).push(newNode(30));(root.child[2].child).push(newNode(40));(root.child[2].child).push(newNode(100));(root.child[2].child).push(newNode(20));(root.child[0].child[1].child).push(newNode(25));(root.child[0].child[1].child).push(newNode(50));document.write(sumNodes(root) +"<br>"); </script> Output: 536 Time Complexity: O(N), where N is the number of nodes in tree. Auxiliary Space: O(N), where N is the number of nodes in tree. YouTubeGeeksforGeeks506K subscribersSum of all elements of N-ary Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:42•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=j3xeTJzobEw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> 29AjayKumar princiraj1992 rrrtnx divyeshrabadiya07 cpp-vector n-ary-tree Recursion Technical Scripter Tree Recursion Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Practice Questions for Recursion | Set 1 Recursively Reversing a linked list (A simple implementation) Sum of natural numbers using recursion Count N-length strings consisting only of vowels sorted lexicographically Count number of nodes in a complete Binary Tree Tree Traversals (Inorder, Preorder and Postorder) AVL Tree | Set 1 (Insertion) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal Binary Tree | Set 3 (Types of Binary Tree)
[ { "code": null, "e": 26359, "s": 26331, "text": "\n08 Nov, 2021" }, { "code": null, "e": 26413, "s": 26359, "text": "Given an N-ary tree, find sum of all elements in it. " }, { "code": null, "e": 26425, "s": 26413, "text": "Example : " }, { "code": null, "e": 26464, "s": 26425, "text": "Input : Above tree\nOutput : Sum is 536" }, { "code": null, "e": 26904, "s": 26466, "text": "Approach : The approach used is similar to Level Order traversal in a binary tree. Start by pushing the root node in the queue. And for each node, while popping it from queue, add the value of this node in the sum variable and push the children of the popped element in the queue. In case of a generic tree store child nodes in a vector. Thus, put all elements of the vector in the queue.Below is the implementation of the above idea : " }, { "code": null, "e": 26908, "s": 26904, "text": "C++" }, { "code": null, "e": 26913, "s": 26908, "text": "Java" }, { "code": null, "e": 26921, "s": 26913, "text": "Python3" }, { "code": null, "e": 26924, "s": 26921, "text": "C#" }, { "code": null, "e": 26935, "s": 26924, "text": "Javascript" }, { "code": "// C++ program to find sum of all// elements in generic tree#include <bits/stdc++.h>using namespace std; // Represents a node of an n-ary treestruct Node { int key; vector<Node*> child;}; // Utility function to create a new tree nodeNode* newNode(int key){ Node* temp = new Node; temp->key = key; return temp;} // Function to compute the sum// of all elements in generic treeint sumNodes(Node* root){ // initialize the sum variable int sum = 0; if (root == NULL) return 0; // Creating a queue and pushing the root queue<Node*> q; q.push(root); while (!q.empty()) { int n = q.size(); // If this node has children while (n > 0) { // Dequeue an item from queue and // add it to variable \"sum\" Node* p = q.front(); q.pop(); sum += p->key; // Enqueue all children of the dequeued item for (int i = 0; i < p->child.size(); i++) q.push(p->child[i]); n--; } } return sum;} // Driver programint main(){ // Creating a generic tree Node* root = newNode(20); (root->child).push_back(newNode(2)); (root->child).push_back(newNode(34)); (root->child).push_back(newNode(50)); (root->child).push_back(newNode(60)); (root->child).push_back(newNode(70)); (root->child[0]->child).push_back(newNode(15)); (root->child[0]->child).push_back(newNode(20)); (root->child[1]->child).push_back(newNode(30)); (root->child[2]->child).push_back(newNode(40)); (root->child[2]->child).push_back(newNode(100)); (root->child[2]->child).push_back(newNode(20)); (root->child[0]->child[1]->child).push_back(newNode(25)); (root->child[0]->child[1]->child).push_back(newNode(50)); cout << sumNodes(root) << endl; return 0;}", "e": 28758, "s": 26935, "text": null }, { "code": "// Java program to find sum of all// elements in generic treeimport java.util.*; class GFG{ // Represents a node of an n-ary treestatic class Node{ int key; Vector<Node> child;}; // Utility function to create a new tree nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.child = new Vector<>(); return temp;} // Function to compute the sum// of all elements in generic treestatic int sumNodes(Node root){ // initialize the sum variable int sum = 0; if (root == null) return 0; // Creating a queue and pushing the root Queue<Node> q = new LinkedList<>(); q.add(root); while (!q.isEmpty()) { int n = q.size(); // If this node has children while (n > 0) { // Dequeue an item from queue and // add it to variable \"sum\" Node p = q.peek(); q.remove(); sum += p.key; // Enqueue all children of the dequeued item for (int i = 0; i < p.child.size(); i++) q.add(p.child.get(i)); n--; } } return sum;} // Driver programpublic static void main(String[] args){ // Creating a generic tree Node root = newNode(20); (root.child).add(newNode(2)); (root.child).add(newNode(34)); (root.child).add(newNode(50)); (root.child).add(newNode(60)); (root.child).add(newNode(70)); (root.child.get(0).child).add(newNode(15)); (root.child.get(0).child).add(newNode(20)); (root.child.get(1).child).add(newNode(30)); (root.child.get(2).child).add(newNode(40)); (root.child.get(2).child).add(newNode(100)); (root.child.get(2).child).add(newNode(20)); (root.child.get(0).child.get(1).child).add(newNode(25)); (root.child.get(0).child.get(1).child).add(newNode(50)); System.out.print(sumNodes(root) +\"\\n\");}} // This code is contributed by 29AjayKumar", "e": 30652, "s": 28758, "text": null }, { "code": "# Python3 program to find sum of all# elements in generic tree # Represents a node of an n-ary treeclass Node: def __init__(self): self.key = 0 self.child = [] # Utility function to create a new tree nodedef newNode(key): temp = Node() temp.key = key temp.child = [] return temp # Function to compute the sum# of all elements in generic treedef sumNodes(root): # initialize the sum variable Sum = 0 if root == None: return 0 # Creating a queue and pushing the root q = [] q.append(root) while len(q) != 0: n = len(q) # If this node has children while n > 0: # Dequeue an item from queue and # add it to variable \"sum\" p = q[0] q.pop(0) Sum += p.key # push all children of the dequeued item for i in range(len(p.child)): q.append(p.child[i]) n-=1 return Sum # Creating a generic treeroot = newNode(20)(root.child).append(newNode(2))(root.child).append(newNode(34))(root.child).append(newNode(50))(root.child).append(newNode(60))(root.child).append(newNode(70))(root.child[0].child).append(newNode(15))(root.child[0].child).append(newNode(20))(root.child[1].child).append(newNode(30))(root.child[2].child).append(newNode(40))(root.child[2].child).append(newNode(100))(root.child[2].child).append(newNode(20))(root.child[0].child[1].child).append(newNode(25))(root.child[0].child[1].child).append(newNode(50))print(sumNodes(root)) # This code is contributed by divyeshrabadiya07.", "e": 32224, "s": 30652, "text": null }, { "code": " // C# program to find sum of all// elements in generic treeusing System;using System.Collections.Generic; class GFG{ // Represents a node of an n-ary treeclass Node{ public int key; public List<Node> child;}; // Utility function to create a new tree nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.child = new List<Node>(); return temp;} // Function to compute the sum// of all elements in generic treestatic int sumNodes(Node root){ // initialize the sum variable int sum = 0; if (root == null) return 0; // Creating a queue and pushing the root Queue<Node> q = new Queue<Node>(); q.Enqueue(root); while (q.Count != 0) { int n = q.Count; // If this node has children while (n > 0) { // Dequeue an item from queue and // add it to variable \"sum\" Node p = q.Peek(); q.Dequeue(); sum += p.key; // Enqueue all children of the dequeued item for (int i = 0; i < p.child.Count; i++) q.Enqueue(p.child[i]); n--; } } return sum;} // Driver programpublic static void Main(String[] args){ // Creating a generic tree Node root = newNode(20); (root.child).Add(newNode(2)); (root.child).Add(newNode(34)); (root.child).Add(newNode(50)); (root.child).Add(newNode(60)); (root.child).Add(newNode(70)); (root.child[0].child).Add(newNode(15)); (root.child[0].child).Add(newNode(20)); (root.child[1].child).Add(newNode(30)); (root.child[2].child).Add(newNode(40)); (root.child[2].child).Add(newNode(100)); (root.child[2].child).Add(newNode(20)); (root.child[0].child[1].child).Add(newNode(25)); (root.child[0].child[1].child).Add(newNode(50)); Console.Write(sumNodes(root) +\"\\n\");}} // This code is contributed by PrinciRaj1992", "e": 34116, "s": 32224, "text": null }, { "code": "<script> // JavaScript program to find sum of all// elements in generic tree // Represents a node of an n-ary treeclass Node{ constructor() { this.key = 0; this.child = []; }}; // Utility function to create a new tree nodefunction newNode(key){ var temp = new Node(); temp.key = key; temp.child = []; return temp;} // Function to compute the sum// of all elements in generic treefunction sumNodes(root){ // initialize the sum variable var sum = 0; if (root == null) return 0; // Creating a queue and pushing the root var q = []; q.push(root); while (q.length != 0) { var n = q.length; // If this node has children while (n > 0) { // Dequeue an item from queue and // add it to variable \"sum\" var p = q[0]; q.shift(); sum += p.key; // push all children of the dequeued item for (var i = 0; i < p.child.length; i++) q.push(p.child[i]); n--; } } return sum;} // Driver program// Creating a generic treevar root = newNode(20);(root.child).push(newNode(2));(root.child).push(newNode(34));(root.child).push(newNode(50));(root.child).push(newNode(60));(root.child).push(newNode(70));(root.child[0].child).push(newNode(15));(root.child[0].child).push(newNode(20));(root.child[1].child).push(newNode(30));(root.child[2].child).push(newNode(40));(root.child[2].child).push(newNode(100));(root.child[2].child).push(newNode(20));(root.child[0].child[1].child).push(newNode(25));(root.child[0].child[1].child).push(newNode(50));document.write(sumNodes(root) +\"<br>\"); </script>", "e": 35784, "s": 34116, "text": null }, { "code": null, "e": 35794, "s": 35784, "text": "Output: " }, { "code": null, "e": 35798, "s": 35794, "text": "536" }, { "code": null, "e": 35925, "s": 35798, "text": "Time Complexity: O(N), where N is the number of nodes in tree. Auxiliary Space: O(N), where N is the number of nodes in tree. " }, { "code": null, "e": 36757, "s": 35925, "text": "YouTubeGeeksforGeeks506K subscribersSum of all elements of N-ary Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:42•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=j3xeTJzobEw\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 36771, "s": 36759, "text": "29AjayKumar" }, { "code": null, "e": 36785, "s": 36771, "text": "princiraj1992" }, { "code": null, "e": 36792, "s": 36785, "text": "rrrtnx" }, { "code": null, "e": 36810, "s": 36792, "text": "divyeshrabadiya07" }, { "code": null, "e": 36821, "s": 36810, "text": "cpp-vector" }, { "code": null, "e": 36832, "s": 36821, "text": "n-ary-tree" }, { "code": null, "e": 36842, "s": 36832, "text": "Recursion" }, { "code": null, "e": 36861, "s": 36842, "text": "Technical Scripter" }, { "code": null, "e": 36866, "s": 36861, "text": "Tree" }, { "code": null, "e": 36876, "s": 36866, "text": "Recursion" }, { "code": null, "e": 36881, "s": 36876, "text": "Tree" }, { "code": null, "e": 36979, "s": 36881, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37020, "s": 36979, "text": "Practice Questions for Recursion | Set 1" }, { "code": null, "e": 37082, "s": 37020, "text": "Recursively Reversing a linked list (A simple implementation)" }, { "code": null, "e": 37121, "s": 37082, "text": "Sum of natural numbers using recursion" }, { "code": null, "e": 37195, "s": 37121, "text": "Count N-length strings consisting only of vowels sorted lexicographically" }, { "code": null, "e": 37243, "s": 37195, "text": "Count number of nodes in a complete Binary Tree" }, { "code": null, "e": 37293, "s": 37243, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 37322, "s": 37293, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 37357, "s": 37322, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 37391, "s": 37357, "text": "Level Order Binary Tree Traversal" } ]
Alternative of Array splice() method in JavaScript - GeeksforGeeks
09 Aug, 2021 Array splice() method is a method of JavaScript and In this articles we are discussing what are alternatives of this method. Here are 2 examples discussed below. Approach 1: In this approach, the startIndex(From where to start removing the elements) and count(Number of elements to remove) are the variables. If the count is not passed then treat it as 1. Run a while loop till the count is greater than 0 and start removing the desired elements and push it in a new array. Return this new array after the loop ends. Example: javascript <!DOCTYPE HTML><html><head> <title> Alternative of Array splice() method in JavaScript </title></head><body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <p id="GFG_UP"> </p> <button onclick="myGFG()"> Click Here </button> <p id="GFG_DOWN"> </p> <script> var arr = [0, 3, 1, 5, 2, 7, 4, 9, 10]; var up = document.getElementById("GFG_UP"); up.innerHTML ="Alternative of Array splice() method in JavaScript."+ " <br>Array = [" + arr + "]"; var down = document.getElementById("GFG_DOWN"); function mySplice(arr, ind, ct) { // if ct(count) not passed in function call. if (typeof ct == 'undefined') { ct = 1; } var rem = []; while (ct--) { var indRem = ind + CT; //pushing the elements rem array rem.push(arr[indRem]); // removing the element from original array. arr[indRem] = arr.pop(); } // returning the removed elements return rem; } function myGFG() { down.innerHTML = "Removed Elements - " + mySplice(arr, 4, 3); } </script></body></html> Output: Approach 2: In this approach, slice() method is used to get the removed elements and this method is also used to get the output array. This approach also takes argument to insert the new elements to the array. Example: javascript <!DOCTYPE HTML><html><head> <title> Alternative of Array splice() method in JavaScript </title></head><body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <p id="GFG_UP"> </p> <button onclick="myGFG()"> Click Here </button> <p id="GFG_DOWN"> </p> <script> var arr = [0, 3, 1, 5, 2, 7, 4, 9, 10]; var up = document.getElementById("GFG_UP"); up.innerHTML = "Alternative of Array splice() "+ "method in JavaScript.<br>Array = [" + arr + "]"; var down = document.getElementById("GFG_DOWN"); Array.prototype.altSplice = function(s, tRemv, insert ) { var rem = this.slice( s, s + tRemv ); var temp = this.slice(0, s).concat( insert, this.slice( s + tRemv ) ); this.length = 0; this.push.apply(this, temp ); return rem; }; function myGFG() { down.innerHTML = "Splice result - " + arr.altSplice(3, 2, 6) + "<br>Original array - " + arr; } </script></body></html> Output: sooda367 JavaScript-Methods JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to filter object array based on attributes? Remove elements from a JavaScript Array 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? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26655, "s": 26627, "text": "\n09 Aug, 2021" }, { "code": null, "e": 26817, "s": 26655, "text": "Array splice() method is a method of JavaScript and In this articles we are discussing what are alternatives of this method. Here are 2 examples discussed below." }, { "code": null, "e": 27172, "s": 26817, "text": "Approach 1: In this approach, the startIndex(From where to start removing the elements) and count(Number of elements to remove) are the variables. If the count is not passed then treat it as 1. Run a while loop till the count is greater than 0 and start removing the desired elements and push it in a new array. Return this new array after the loop ends." }, { "code": null, "e": 27181, "s": 27172, "text": "Example:" }, { "code": null, "e": 27192, "s": 27181, "text": "javascript" }, { "code": "<!DOCTYPE HTML><html><head> <title> Alternative of Array splice() method in JavaScript </title></head><body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p id=\"GFG_UP\"> </p> <button onclick=\"myGFG()\"> Click Here </button> <p id=\"GFG_DOWN\"> </p> <script> var arr = [0, 3, 1, 5, 2, 7, 4, 9, 10]; var up = document.getElementById(\"GFG_UP\"); up.innerHTML =\"Alternative of Array splice() method in JavaScript.\"+ \" <br>Array = [\" + arr + \"]\"; var down = document.getElementById(\"GFG_DOWN\"); function mySplice(arr, ind, ct) { // if ct(count) not passed in function call. if (typeof ct == 'undefined') { ct = 1; } var rem = []; while (ct--) { var indRem = ind + CT; //pushing the elements rem array rem.push(arr[indRem]); // removing the element from original array. arr[indRem] = arr.pop(); } // returning the removed elements return rem; } function myGFG() { down.innerHTML = \"Removed Elements - \" + mySplice(arr, 4, 3); } </script></body></html>", "e": 28443, "s": 27192, "text": null }, { "code": null, "e": 28452, "s": 28443, "text": " Output:" }, { "code": null, "e": 28662, "s": 28452, "text": "Approach 2: In this approach, slice() method is used to get the removed elements and this method is also used to get the output array. This approach also takes argument to insert the new elements to the array." }, { "code": null, "e": 28671, "s": 28662, "text": "Example:" }, { "code": null, "e": 28682, "s": 28671, "text": "javascript" }, { "code": "<!DOCTYPE HTML><html><head> <title> Alternative of Array splice() method in JavaScript </title></head><body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p id=\"GFG_UP\"> </p> <button onclick=\"myGFG()\"> Click Here </button> <p id=\"GFG_DOWN\"> </p> <script> var arr = [0, 3, 1, 5, 2, 7, 4, 9, 10]; var up = document.getElementById(\"GFG_UP\"); up.innerHTML = \"Alternative of Array splice() \"+ \"method in JavaScript.<br>Array = [\" + arr + \"]\"; var down = document.getElementById(\"GFG_DOWN\"); Array.prototype.altSplice = function(s, tRemv, insert ) { var rem = this.slice( s, s + tRemv ); var temp = this.slice(0, s).concat( insert, this.slice( s + tRemv ) ); this.length = 0; this.push.apply(this, temp ); return rem; }; function myGFG() { down.innerHTML = \"Splice result - \" + arr.altSplice(3, 2, 6) + \"<br>Original array - \" + arr; } </script></body></html>", "e": 29812, "s": 28682, "text": null }, { "code": null, "e": 29820, "s": 29812, "text": "Output:" }, { "code": null, "e": 29829, "s": 29820, "text": "sooda367" }, { "code": null, "e": 29848, "s": 29829, "text": "JavaScript-Methods" }, { "code": null, "e": 29859, "s": 29848, "text": "JavaScript" }, { "code": null, "e": 29876, "s": 29859, "text": "Web Technologies" }, { "code": null, "e": 29974, "s": 29876, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30014, "s": 29974, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30075, "s": 30014, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30116, "s": 30075, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 30138, "s": 30116, "text": "JavaScript | Promises" }, { "code": null, "e": 30186, "s": 30138, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 30226, "s": 30186, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30259, "s": 30226, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30302, "s": 30259, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30352, "s": 30302, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Absolute Layout in Android with Example - GeeksforGeeks
02 Dec, 2020 An Absolute Layout allows you to specify the exact location .i.e., X and Y coordinates of its children with respect to the origin at the top left corner of the layout. The absolute layout is less flexible and harder to maintain for varying sizes of screens that’s why it is not recommended. Although Absolute Layout is deprecated now. Some of the important Absolute Layout attributes are the following: android:id: It uniquely specifies the absolute layoutandroid:layout_x: It specifies X-Coordinate of the Views (Possible values of this is in density-pixel or pixel)android:layout_y: It specifies Y-Coordinate of the Views (Possible values of this is in dp or px) android:id: It uniquely specifies the absolute layout android:layout_x: It specifies X-Coordinate of the Views (Possible values of this is in density-pixel or pixel) android:layout_y: It specifies Y-Coordinate of the Views (Possible values of this is in dp or px) The Syntax for Absolute Layout XML <AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"><!--add child views--></AbsoluteLayout> In this example, we are going to create a basic application with Absolute Layout that is having two TextView. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Create the layout file For this go to app > res > layout > activity_main.xml file and change the Constraint Layout to Absolute Layout and add TextViews. Below is the code snippet for the activity_mian.xml file. XML <?xml version="1.0" encoding="utf-8"?><AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" tools:context=".MainActivity"> <!--Setting up TextViews--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_x="100px" android:layout_y="300px" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_x="120px" android:layout_y="350px" /> </AbsoluteLayout> Before moving further let’s add some color attributes in order to enhance the app bar. Go to app > res > values > colors.xml and add the following color attributes. XML <resources> <color name="colorPrimary">#0F9D58</color> <color name="colorPrimaryDark">#16E37F</color> <color name="colorAccent">#03DAC5</color> </resources> Step 3: Working with the MainActivity.java file In this step, we will initialize the TextViews in our MainActivity.java file. Java import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView heading, subHeading; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Referencing the TextViews heading = (TextView) findViewById(R.id.heading); subHeading = (TextView) findViewById(R.id.subHeading); // Setting text dynamically heading.setText("Computer Science Portal"); subHeading.setText("GeeksForGeeks"); }} You will see that TextViews are having fixed X and Y Coordinates. android Picked Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? Flexbox-Layout in Android How to Post Data to API using Retrofit in Android? Arrays in Java Split() String method in Java with examples For-each loop in Java Stream In Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 26491, "s": 26463, "text": "\n02 Dec, 2020" }, { "code": null, "e": 26826, "s": 26491, "text": "An Absolute Layout allows you to specify the exact location .i.e., X and Y coordinates of its children with respect to the origin at the top left corner of the layout. The absolute layout is less flexible and harder to maintain for varying sizes of screens that’s why it is not recommended. Although Absolute Layout is deprecated now." }, { "code": null, "e": 26894, "s": 26826, "text": "Some of the important Absolute Layout attributes are the following:" }, { "code": null, "e": 27156, "s": 26894, "text": "android:id: It uniquely specifies the absolute layoutandroid:layout_x: It specifies X-Coordinate of the Views (Possible values of this is in density-pixel or pixel)android:layout_y: It specifies Y-Coordinate of the Views (Possible values of this is in dp or px)" }, { "code": null, "e": 27210, "s": 27156, "text": "android:id: It uniquely specifies the absolute layout" }, { "code": null, "e": 27322, "s": 27210, "text": "android:layout_x: It specifies X-Coordinate of the Views (Possible values of this is in density-pixel or pixel)" }, { "code": null, "e": 27420, "s": 27322, "text": "android:layout_y: It specifies Y-Coordinate of the Views (Possible values of this is in dp or px)" }, { "code": null, "e": 27451, "s": 27420, "text": "The Syntax for Absolute Layout" }, { "code": null, "e": 27455, "s": 27451, "text": "XML" }, { "code": "<AbsoluteLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"fill_parent\" android:layout_height=\"fill_parent\"><!--add child views--></AbsoluteLayout>", "e": 27650, "s": 27455, "text": null }, { "code": null, "e": 27834, "s": 27650, "text": "In this example, we are going to create a basic application with Absolute Layout that is having two TextView. Note that we are going to implement this project using the Java language." }, { "code": null, "e": 27863, "s": 27834, "text": "Step 1: Create a New Project" }, { "code": null, "e": 28025, "s": 27863, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 28056, "s": 28025, "text": "Step 2: Create the layout file" }, { "code": null, "e": 28244, "s": 28056, "text": "For this go to app > res > layout > activity_main.xml file and change the Constraint Layout to Absolute Layout and add TextViews. Below is the code snippet for the activity_mian.xml file." }, { "code": null, "e": 28248, "s": 28244, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><AbsoluteLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"fill_parent\" android:layout_height=\"fill_parent\" tools:context=\".MainActivity\"> <!--Setting up TextViews--> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_x=\"100px\" android:layout_y=\"300px\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_x=\"120px\" android:layout_y=\"350px\" /> </AbsoluteLayout>", "e": 28969, "s": 28248, "text": null }, { "code": null, "e": 29136, "s": 28969, "text": "Before moving further let’s add some color attributes in order to enhance the app bar. Go to app > res > values > colors.xml and add the following color attributes. " }, { "code": null, "e": 29140, "s": 29136, "text": "XML" }, { "code": "<resources> <color name=\"colorPrimary\">#0F9D58</color> <color name=\"colorPrimaryDark\">#16E37F</color> <color name=\"colorAccent\">#03DAC5</color> </resources> ", "e": 29310, "s": 29140, "text": null }, { "code": null, "e": 29358, "s": 29310, "text": "Step 3: Working with the MainActivity.java file" }, { "code": null, "e": 29436, "s": 29358, "text": "In this step, we will initialize the TextViews in our MainActivity.java file." }, { "code": null, "e": 29441, "s": 29436, "text": "Java" }, { "code": "import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView heading, subHeading; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Referencing the TextViews heading = (TextView) findViewById(R.id.heading); subHeading = (TextView) findViewById(R.id.subHeading); // Setting text dynamically heading.setText(\"Computer Science Portal\"); subHeading.setText(\"GeeksForGeeks\"); }}", "e": 30099, "s": 29441, "text": null }, { "code": null, "e": 30165, "s": 30099, "text": "You will see that TextViews are having fixed X and Y Coordinates." }, { "code": null, "e": 30173, "s": 30165, "text": "android" }, { "code": null, "e": 30180, "s": 30173, "text": "Picked" }, { "code": null, "e": 30204, "s": 30180, "text": "Technical Scripter 2020" }, { "code": null, "e": 30212, "s": 30204, "text": "Android" }, { "code": null, "e": 30217, "s": 30212, "text": "Java" }, { "code": null, "e": 30236, "s": 30217, "text": "Technical Scripter" }, { "code": null, "e": 30241, "s": 30236, "text": "Java" }, { "code": null, "e": 30249, "s": 30241, "text": "Android" }, { "code": null, "e": 30347, "s": 30249, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30385, "s": 30347, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 30424, "s": 30385, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 30474, "s": 30424, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 30500, "s": 30474, "text": "Flexbox-Layout in Android" }, { "code": null, "e": 30551, "s": 30500, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 30566, "s": 30551, "text": "Arrays in Java" }, { "code": null, "e": 30610, "s": 30566, "text": "Split() String method in Java with examples" }, { "code": null, "e": 30632, "s": 30610, "text": "For-each loop in Java" }, { "code": null, "e": 30647, "s": 30632, "text": "Stream In Java" } ]
Creating a tabbed browser using PyQt5 - GeeksforGeeks
05 Nov, 2021 In this article, we will see how we can create a tabbed browser using PyQt5. Web browser is a software application for accessing information on the World Wide Web. When a user requests a web page from a particular website, the web browser retrieves the necessary content from a web server and then displays the page on the screen.Tabbing : Adding tabs complicates the internals of the browser a bit, since there will now need to keep track of the currently active browser view, both to update UI elements (URL bar) to changing state in the currently active window and to ensure the UI events are dispatched to the correct web view.PyQt5 is cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library. It has been installed using the command given below pip install PyQt5 GUI Implementation steps : 1. Create a main window 2. Create a QTabWidget for tabbing, set it as central widget, make them documented and closable, below is how the tabs will look like 3. Create a status bar to show the status tips 4. Create a tool bar and add navigation button and the line edit to show the url, below is hot the tool bar will look like Back-End Implementation Steps : 1. Add action to the QTabWidget object when double-clicked is pressed 2. Inside the double click action check if the double click is on no tab then call the open tab method 3. Inside the open tab, method create a QUrl object and the QWebEngineView object and set QUrl to it and get the index of the tab 4. Add update url action to QWebEngineView object when url is changed. 5. Inside the update, url action check if action is called by the opened tab then change the url of url bar and change cursor position 6. Add another update title action to the QWebEngineView object when loading is finished 7. Inside the update title method update the title of the window as the page title if the action is called by the open tab only 8. Add action to the tabs when the tab is changed 9. Inside the tab changed action get the url update the url inline edit and the title 10. Add actions to the navigation buttons using the build-in functions of the QWebEngineView object for reloading, back, stop and forward buttons 11. Add action to the home button and inside the action change the url to google.com 12. Add action to the line edit when the return key is pressed 13. Inside the line, edit action get the text and convert this text to the QUrl object and set the scheme if it is null and set this url to the current tab Below is the implementation Python3 # importing required librariesfrom PyQt5.QtCore import *from PyQt5.QtWidgets import *from PyQt5.QtGui import *from PyQt5.QtWebEngineWidgets import *from PyQt5.QtPrintSupport import *import osimport sys # main windowclass MainWindow(QMainWindow): # constructor def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) # creating a tab widget self.tabs = QTabWidget() # making document mode true self.tabs.setDocumentMode(True) # adding action when double clicked self.tabs.tabBarDoubleClicked.connect(self.tab_open_doubleclick) # adding action when tab is changed self.tabs.currentChanged.connect(self.current_tab_changed) # making tabs closeable self.tabs.setTabsClosable(True) # adding action when tab close is requested self.tabs.tabCloseRequested.connect(self.close_current_tab) # making tabs as central widget self.setCentralWidget(self.tabs) # creating a status bar self.status = QStatusBar() # setting status bar to the main window self.setStatusBar(self.status) # creating a tool bar for navigation navtb = QToolBar("Navigation") # adding tool bar tot he main window self.addToolBar(navtb) # creating back action back_btn = QAction("Back", self) # setting status tip back_btn.setStatusTip("Back to previous page") # adding action to back button # making current tab to go back back_btn.triggered.connect(lambda: self.tabs.currentWidget().back()) # adding this to the navigation tool bar navtb.addAction(back_btn) # similarly adding next button next_btn = QAction("Forward", self) next_btn.setStatusTip("Forward to next page") next_btn.triggered.connect(lambda: self.tabs.currentWidget().forward()) navtb.addAction(next_btn) # similarly adding reload button reload_btn = QAction("Reload", self) reload_btn.setStatusTip("Reload page") reload_btn.triggered.connect(lambda: self.tabs.currentWidget().reload()) navtb.addAction(reload_btn) # creating home action home_btn = QAction("Home", self) home_btn.setStatusTip("Go home") # adding action to home button home_btn.triggered.connect(self.navigate_home) navtb.addAction(home_btn) # adding a separator navtb.addSeparator() # creating a line edit widget for URL self.urlbar = QLineEdit() # adding action to line edit when return key is pressed self.urlbar.returnPressed.connect(self.navigate_to_url) # adding line edit to tool bar navtb.addWidget(self.urlbar) # similarly adding stop action stop_btn = QAction("Stop", self) stop_btn.setStatusTip("Stop loading current page") stop_btn.triggered.connect(lambda: self.tabs.currentWidget().stop()) navtb.addAction(stop_btn) # creating first tab self.add_new_tab(QUrl('http://www.google.com'), 'Homepage') # showing all the components self.show() # setting window title self.setWindowTitle("Geek PyQt5") # method for adding new tab def add_new_tab(self, qurl = None, label ="Blank"): # if url is blank if qurl is None: # creating a google url qurl = QUrl('http://www.google.com') # creating a QWebEngineView object browser = QWebEngineView() # setting url to browser browser.setUrl(qurl) # setting tab index i = self.tabs.addTab(browser, label) self.tabs.setCurrentIndex(i) # adding action to the browser when url is changed # update the url browser.urlChanged.connect(lambda qurl, browser = browser: self.update_urlbar(qurl, browser)) # adding action to the browser when loading is finished # set the tab title browser.loadFinished.connect(lambda _, i = i, browser = browser: self.tabs.setTabText(i, browser.page().title())) # when double clicked is pressed on tabs def tab_open_doubleclick(self, i): # checking index i.e # No tab under the click if i == -1: # creating a new tab self.add_new_tab() # when tab is changed def current_tab_changed(self, i): # get the curl qurl = self.tabs.currentWidget().url() # update the url self.update_urlbar(qurl, self.tabs.currentWidget()) # update the title self.update_title(self.tabs.currentWidget()) # when tab is closed def close_current_tab(self, i): # if there is only one tab if self.tabs.count() < 2: # do nothing return # else remove the tab self.tabs.removeTab(i) # method for updating the title def update_title(self, browser): # if signal is not from the current tab if browser != self.tabs.currentWidget(): # do nothing return # get the page title title = self.tabs.currentWidget().page().title() # set the window title self.setWindowTitle("% s - Geek PyQt5" % title) # action to go to home def navigate_home(self): # go to google self.tabs.currentWidget().setUrl(QUrl("http://www.google.com")) # method for navigate to url def navigate_to_url(self): # get the line edit text # convert it to QUrl object q = QUrl(self.urlbar.text()) # if scheme is blank if q.scheme() == "": # set scheme q.setScheme("http") # set the url self.tabs.currentWidget().setUrl(q) # method to update the url def update_urlbar(self, q, browser = None): # If this signal is not from the current tab, ignore if browser != self.tabs.currentWidget(): return # set text to the url bar self.urlbar.setText(q.toString()) # set cursor position self.urlbar.setCursorPosition(0) # creating a PyQt5 applicationapp = QApplication(sys.argv) # setting name to the applicationapp.setApplicationName("Geek PyQt5") # creating MainWindow objectwindow = MainWindow() # loopapp.exec_() Output : nidhi_biet Akanksha_Rai surindertarika1234 PyQt-exercise Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python 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": 25742, "s": 25714, "text": "\n05 Nov, 2021" }, { "code": null, "e": 25819, "s": 25742, "text": "In this article, we will see how we can create a tabbed browser using PyQt5." }, { "code": null, "e": 26630, "s": 25819, "text": "Web browser is a software application for accessing information on the World Wide Web. When a user requests a web page from a particular website, the web browser retrieves the necessary content from a web server and then displays the page on the screen.Tabbing : Adding tabs complicates the internals of the browser a bit, since there will now need to keep track of the currently active browser view, both to update UI elements (URL bar) to changing state in the currently active window and to ensure the UI events are dispatched to the correct web view.PyQt5 is cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library. It has been installed using the command given below " }, { "code": null, "e": 26648, "s": 26630, "text": "pip install PyQt5" }, { "code": null, "e": 26834, "s": 26648, "text": "GUI Implementation steps : 1. Create a main window 2. Create a QTabWidget for tabbing, set it as central widget, make them documented and closable, below is how the tabs will look like " }, { "code": null, "e": 27005, "s": 26834, "text": "3. Create a status bar to show the status tips 4. Create a tool bar and add navigation button and the line edit to show the url, below is hot the tool bar will look like " }, { "code": null, "e": 28351, "s": 27005, "text": "Back-End Implementation Steps : 1. Add action to the QTabWidget object when double-clicked is pressed 2. Inside the double click action check if the double click is on no tab then call the open tab method 3. Inside the open tab, method create a QUrl object and the QWebEngineView object and set QUrl to it and get the index of the tab 4. Add update url action to QWebEngineView object when url is changed. 5. Inside the update, url action check if action is called by the opened tab then change the url of url bar and change cursor position 6. Add another update title action to the QWebEngineView object when loading is finished 7. Inside the update title method update the title of the window as the page title if the action is called by the open tab only 8. Add action to the tabs when the tab is changed 9. Inside the tab changed action get the url update the url inline edit and the title 10. Add actions to the navigation buttons using the build-in functions of the QWebEngineView object for reloading, back, stop and forward buttons 11. Add action to the home button and inside the action change the url to google.com 12. Add action to the line edit when the return key is pressed 13. Inside the line, edit action get the text and convert this text to the QUrl object and set the scheme if it is null and set this url to the current tab " }, { "code": null, "e": 28381, "s": 28351, "text": "Below is the implementation " }, { "code": null, "e": 28389, "s": 28381, "text": "Python3" }, { "code": "# importing required librariesfrom PyQt5.QtCore import *from PyQt5.QtWidgets import *from PyQt5.QtGui import *from PyQt5.QtWebEngineWidgets import *from PyQt5.QtPrintSupport import *import osimport sys # main windowclass MainWindow(QMainWindow): # constructor def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) # creating a tab widget self.tabs = QTabWidget() # making document mode true self.tabs.setDocumentMode(True) # adding action when double clicked self.tabs.tabBarDoubleClicked.connect(self.tab_open_doubleclick) # adding action when tab is changed self.tabs.currentChanged.connect(self.current_tab_changed) # making tabs closeable self.tabs.setTabsClosable(True) # adding action when tab close is requested self.tabs.tabCloseRequested.connect(self.close_current_tab) # making tabs as central widget self.setCentralWidget(self.tabs) # creating a status bar self.status = QStatusBar() # setting status bar to the main window self.setStatusBar(self.status) # creating a tool bar for navigation navtb = QToolBar(\"Navigation\") # adding tool bar tot he main window self.addToolBar(navtb) # creating back action back_btn = QAction(\"Back\", self) # setting status tip back_btn.setStatusTip(\"Back to previous page\") # adding action to back button # making current tab to go back back_btn.triggered.connect(lambda: self.tabs.currentWidget().back()) # adding this to the navigation tool bar navtb.addAction(back_btn) # similarly adding next button next_btn = QAction(\"Forward\", self) next_btn.setStatusTip(\"Forward to next page\") next_btn.triggered.connect(lambda: self.tabs.currentWidget().forward()) navtb.addAction(next_btn) # similarly adding reload button reload_btn = QAction(\"Reload\", self) reload_btn.setStatusTip(\"Reload page\") reload_btn.triggered.connect(lambda: self.tabs.currentWidget().reload()) navtb.addAction(reload_btn) # creating home action home_btn = QAction(\"Home\", self) home_btn.setStatusTip(\"Go home\") # adding action to home button home_btn.triggered.connect(self.navigate_home) navtb.addAction(home_btn) # adding a separator navtb.addSeparator() # creating a line edit widget for URL self.urlbar = QLineEdit() # adding action to line edit when return key is pressed self.urlbar.returnPressed.connect(self.navigate_to_url) # adding line edit to tool bar navtb.addWidget(self.urlbar) # similarly adding stop action stop_btn = QAction(\"Stop\", self) stop_btn.setStatusTip(\"Stop loading current page\") stop_btn.triggered.connect(lambda: self.tabs.currentWidget().stop()) navtb.addAction(stop_btn) # creating first tab self.add_new_tab(QUrl('http://www.google.com'), 'Homepage') # showing all the components self.show() # setting window title self.setWindowTitle(\"Geek PyQt5\") # method for adding new tab def add_new_tab(self, qurl = None, label =\"Blank\"): # if url is blank if qurl is None: # creating a google url qurl = QUrl('http://www.google.com') # creating a QWebEngineView object browser = QWebEngineView() # setting url to browser browser.setUrl(qurl) # setting tab index i = self.tabs.addTab(browser, label) self.tabs.setCurrentIndex(i) # adding action to the browser when url is changed # update the url browser.urlChanged.connect(lambda qurl, browser = browser: self.update_urlbar(qurl, browser)) # adding action to the browser when loading is finished # set the tab title browser.loadFinished.connect(lambda _, i = i, browser = browser: self.tabs.setTabText(i, browser.page().title())) # when double clicked is pressed on tabs def tab_open_doubleclick(self, i): # checking index i.e # No tab under the click if i == -1: # creating a new tab self.add_new_tab() # when tab is changed def current_tab_changed(self, i): # get the curl qurl = self.tabs.currentWidget().url() # update the url self.update_urlbar(qurl, self.tabs.currentWidget()) # update the title self.update_title(self.tabs.currentWidget()) # when tab is closed def close_current_tab(self, i): # if there is only one tab if self.tabs.count() < 2: # do nothing return # else remove the tab self.tabs.removeTab(i) # method for updating the title def update_title(self, browser): # if signal is not from the current tab if browser != self.tabs.currentWidget(): # do nothing return # get the page title title = self.tabs.currentWidget().page().title() # set the window title self.setWindowTitle(\"% s - Geek PyQt5\" % title) # action to go to home def navigate_home(self): # go to google self.tabs.currentWidget().setUrl(QUrl(\"http://www.google.com\")) # method for navigate to url def navigate_to_url(self): # get the line edit text # convert it to QUrl object q = QUrl(self.urlbar.text()) # if scheme is blank if q.scheme() == \"\": # set scheme q.setScheme(\"http\") # set the url self.tabs.currentWidget().setUrl(q) # method to update the url def update_urlbar(self, q, browser = None): # If this signal is not from the current tab, ignore if browser != self.tabs.currentWidget(): return # set text to the url bar self.urlbar.setText(q.toString()) # set cursor position self.urlbar.setCursorPosition(0) # creating a PyQt5 applicationapp = QApplication(sys.argv) # setting name to the applicationapp.setApplicationName(\"Geek PyQt5\") # creating MainWindow objectwindow = MainWindow() # loopapp.exec_()", "e": 34727, "s": 28389, "text": null }, { "code": null, "e": 34737, "s": 34727, "text": "Output : " }, { "code": null, "e": 34750, "s": 34739, "text": "nidhi_biet" }, { "code": null, "e": 34763, "s": 34750, "text": "Akanksha_Rai" }, { "code": null, "e": 34782, "s": 34763, "text": "surindertarika1234" }, { "code": null, "e": 34796, "s": 34782, "text": "PyQt-exercise" }, { "code": null, "e": 34807, "s": 34796, "text": "Python-gui" }, { "code": null, "e": 34819, "s": 34807, "text": "Python-PyQt" }, { "code": null, "e": 34826, "s": 34819, "text": "Python" }, { "code": null, "e": 34924, "s": 34826, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34942, "s": 34924, "text": "Python Dictionary" }, { "code": null, "e": 34974, "s": 34942, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 34996, "s": 34974, "text": "Enumerate() in Python" }, { "code": null, "e": 35038, "s": 34996, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 35064, "s": 35038, "text": "Python String | replace()" }, { "code": null, "e": 35093, "s": 35064, "text": "*args and **kwargs in Python" }, { "code": null, "e": 35137, "s": 35093, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 35174, "s": 35137, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 35210, "s": 35174, "text": "Convert integer to string in Python" } ]
Nested Lambda Function in Python - GeeksforGeeks
08 Jun, 2020 Prerequisites: Python lambda In Python, anonymous function means that a function is without a name. As we already know the def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions. When we use lambda function inside another lambda function then it is called Nested Lambda Function. Example 1: # Python program to demonstrate# nested lambda functions f = lambda a = 2, b = 3:lambda c: a+b+c o = f()print(o(4)) Output: 9 Here, when the object o with parameter 4 is called, the control shift to f() which is caller object of the whole lambda function. Then the following execution takes place- The nested lambda function takes the value of a and b from the first lambda function as a=2 and b=3. It takes the value of c from its caller object o which passes c = 4. Finally we get the output which is the summation of a, b and c that is 9. Example 2: # Python program to demonstrate# nested lambda functions square = lambda x: x**2product = lambda f, n: lambda x: f(x)*n ans = product(square, 2)(10)print(ans) Output: 200 In the above example, when the product function is called square function gets bound to f and 2 gets bound to n which then returns a function which is bound to the product which when called with 10, x is assigned this and square is called, which returns 100 and this, in turn, is multiplied with n which is 2. So it’ll finally return 200. python-lambda 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": 25379, "s": 25351, "text": "\n08 Jun, 2020" }, { "code": null, "e": 25408, "s": 25379, "text": "Prerequisites: Python lambda" }, { "code": null, "e": 25716, "s": 25408, "text": "In Python, anonymous function means that a function is without a name. As we already know the def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions. When we use lambda function inside another lambda function then it is called Nested Lambda Function." }, { "code": null, "e": 25727, "s": 25716, "text": "Example 1:" }, { "code": "# Python program to demonstrate# nested lambda functions f = lambda a = 2, b = 3:lambda c: a+b+c o = f()print(o(4))", "e": 25847, "s": 25727, "text": null }, { "code": null, "e": 25855, "s": 25847, "text": "Output:" }, { "code": null, "e": 25857, "s": 25855, "text": "9" }, { "code": null, "e": 26029, "s": 25857, "text": "Here, when the object o with parameter 4 is called, the control shift to f() which is caller object of the whole lambda function. Then the following execution takes place-" }, { "code": null, "e": 26130, "s": 26029, "text": "The nested lambda function takes the value of a and b from the first lambda function as a=2 and b=3." }, { "code": null, "e": 26199, "s": 26130, "text": "It takes the value of c from its caller object o which passes c = 4." }, { "code": null, "e": 26273, "s": 26199, "text": "Finally we get the output which is the summation of a, b and c that is 9." }, { "code": null, "e": 26284, "s": 26273, "text": "Example 2:" }, { "code": "# Python program to demonstrate# nested lambda functions square = lambda x: x**2product = lambda f, n: lambda x: f(x)*n ans = product(square, 2)(10)print(ans)", "e": 26447, "s": 26284, "text": null }, { "code": null, "e": 26455, "s": 26447, "text": "Output:" }, { "code": null, "e": 26459, "s": 26455, "text": "200" }, { "code": null, "e": 26798, "s": 26459, "text": "In the above example, when the product function is called square function gets bound to f and 2 gets bound to n which then returns a function which is bound to the product which when called with 10, x is assigned this and square is called, which returns 100 and this, in turn, is multiplied with n which is 2. So it’ll finally return 200." }, { "code": null, "e": 26812, "s": 26798, "text": "python-lambda" }, { "code": null, "e": 26819, "s": 26812, "text": "Python" }, { "code": null, "e": 26917, "s": 26819, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26935, "s": 26917, "text": "Python Dictionary" }, { "code": null, "e": 26970, "s": 26935, "text": "Read a file line by line in Python" }, { "code": null, "e": 27002, "s": 26970, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27024, "s": 27002, "text": "Enumerate() in Python" }, { "code": null, "e": 27066, "s": 27024, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27096, "s": 27066, "text": "Iterate over a list in Python" }, { "code": null, "e": 27122, "s": 27096, "text": "Python String | replace()" }, { "code": null, "e": 27151, "s": 27122, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27195, "s": 27151, "text": "Reading and Writing to text files in Python" } ]
GATE | GATE-CS-2014-(Set-3) | Question 21 - GeeksforGeeks
28 Jun, 2021 The minimum number of arithmetic operations required to evaluate the polynomial P(X) = X5 + 4X3 + 6X + 5 for a given value of X using only one temporary variable.(A) 6(B) 7(C) 8(D) 9Answer: (B)Explanation: P(X) = x5 + 4x3 + 6x + 5 =x ( x4 + 4x2 + 6 ) +5 =x ( x ( x3 + 4x ) + 6 ) + 5 =x ( x ( x ( x2 + 4 ) ) + 6 ) + 5 =x ( x ( x (x (x) + 4 ) ) + 6 ) + 5 Let T be a temporary variable to store intermediate results. 1. T = (x) * (x) 2. T = T + 4 3. T = (x) * (T) 4. T = (x) * (T) 5. T = T + 6 6. T = (x) * T 7. T = T + 5 Thus, we need 7 operations if we are to use only one temporary variable. Please comment below if you find anything wrong in the above post.Quiz of this Question GATE-CS-2014-(Set-3) GATE-GATE-CS-2014-(Set-3) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE-CS-2006 | Question 47 GATE | GATE MOCK 2017 | Question 24 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25720, "s": 25692, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25926, "s": 25720, "text": "The minimum number of arithmetic operations required to evaluate the polynomial P(X) = X5 + 4X3 + 6X + 5 for a given value of X using only one temporary variable.(A) 6(B) 7(C) 8(D) 9Answer: (B)Explanation:" }, { "code": null, "e": 26339, "s": 25926, "text": "P(X) = x5 + 4x3 + 6x + 5\n\n =x ( x4 + 4x2 + 6 ) +5\n\n =x ( x ( x3 + 4x ) + 6 ) + 5\n\n =x ( x ( x ( x2 + 4 ) ) + 6 ) + 5\n\n =x ( x ( x (x (x) + 4 ) ) + 6 ) + 5\n\nLet T be a temporary variable to store intermediate results.\n\n1. T = (x) * (x)\n2. T = T + 4\n3. T = (x) * (T)\n4. T = (x) * (T)\n5. T = T + 6\n6. T = (x) * T\n7. T = T + 5\n\nThus, we need 7 operations if we are to use only one temporary variable." }, { "code": null, "e": 26427, "s": 26339, "text": "Please comment below if you find anything wrong in the above post.Quiz of this Question" }, { "code": null, "e": 26448, "s": 26427, "text": "GATE-CS-2014-(Set-3)" }, { "code": null, "e": 26474, "s": 26448, "text": "GATE-GATE-CS-2014-(Set-3)" }, { "code": null, "e": 26479, "s": 26474, "text": "GATE" }, { "code": null, "e": 26577, "s": 26479, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26611, "s": 26577, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 26645, "s": 26611, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 26679, "s": 26645, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 26712, "s": 26679, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 26748, "s": 26712, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 26782, "s": 26748, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 26818, "s": 26782, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 26852, "s": 26818, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 26886, "s": 26852, "text": "GATE | GATE-CS-2009 | Question 38" } ]
not Keyword in Ruby - GeeksforGeeks
27 Jul, 2020 The keyword “not” is different from the others. The “not” keyword gets an expression and inverts its boolean value – so given a true condition it will return false. It works like “!” operator in Ruby, the only difference between “and” keyword and “!” operator is “!” has the highest precedence of all operators, and “not” one of the lowest. Syntax: not expression Example 1: Ruby # Ruby program to illustrate not keyworduname = "geeks" # Using not keywordif not(uname == "Geeks" )puts "Incorrect username!"else puts "Welcome, GeeksforGeeks!"end Output: Incorrect username! Example 2: Ruby # Ruby program to illustrate not keyworduname = "Geek"password = "Wel123"number = 123if not(uname == "Geek" && password == "Wel123" && number == 123)puts "Hey, Incorrect Credentials"else puts "Welcome to GeeksforGeeks" end Output: Welcome to GeeksforGeeks Ruby Keyword Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Ruby | Array count() operation Ruby | Array slice() function Include v/s Extend in Ruby Global Variable in Ruby Ruby | Hash delete() function Ruby | Types of Variables Ruby | Enumerator each_with_index function Ruby | Case Statement Ruby | Array select() function Ruby | Data Types
[ { "code": null, "e": 25065, "s": 25037, "text": "\n27 Jul, 2020" }, { "code": null, "e": 25407, "s": 25065, "text": "The keyword “not” is different from the others. The “not” keyword gets an expression and inverts its boolean value – so given a true condition it will return false. It works like “!” operator in Ruby, the only difference between “and” keyword and “!” operator is “!” has the highest precedence of all operators, and “not” one of the lowest." }, { "code": null, "e": 25415, "s": 25407, "text": "Syntax:" }, { "code": null, "e": 25432, "s": 25415, "text": "not expression\n\n" }, { "code": null, "e": 25443, "s": 25432, "text": "Example 1:" }, { "code": null, "e": 25448, "s": 25443, "text": "Ruby" }, { "code": "# Ruby program to illustrate not keyworduname = \"geeks\" # Using not keywordif not(uname == \"Geeks\" )puts \"Incorrect username!\"else puts \"Welcome, GeeksforGeeks!\"end", "e": 25615, "s": 25448, "text": null }, { "code": null, "e": 25625, "s": 25617, "text": "Output:" }, { "code": null, "e": 25647, "s": 25625, "text": "Incorrect username!\n\n" }, { "code": null, "e": 25659, "s": 25647, "text": "Example 2: " }, { "code": null, "e": 25666, "s": 25661, "text": "Ruby" }, { "code": "# Ruby program to illustrate not keyworduname = \"Geek\"password = \"Wel123\"number = 123if not(uname == \"Geek\" && password == \"Wel123\" && number == 123)puts \"Hey, Incorrect Credentials\"else puts \"Welcome to GeeksforGeeks\" end", "e": 25904, "s": 25666, "text": null }, { "code": null, "e": 25914, "s": 25906, "text": "Output:" }, { "code": null, "e": 25941, "s": 25914, "text": "Welcome to GeeksforGeeks\n\n" }, { "code": null, "e": 25954, "s": 25941, "text": "Ruby Keyword" }, { "code": null, "e": 25959, "s": 25954, "text": "Ruby" }, { "code": null, "e": 26057, "s": 25959, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26088, "s": 26057, "text": "Ruby | Array count() operation" }, { "code": null, "e": 26118, "s": 26088, "text": "Ruby | Array slice() function" }, { "code": null, "e": 26145, "s": 26118, "text": "Include v/s Extend in Ruby" }, { "code": null, "e": 26169, "s": 26145, "text": "Global Variable in Ruby" }, { "code": null, "e": 26199, "s": 26169, "text": "Ruby | Hash delete() function" }, { "code": null, "e": 26225, "s": 26199, "text": "Ruby | Types of Variables" }, { "code": null, "e": 26268, "s": 26225, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 26290, "s": 26268, "text": "Ruby | Case Statement" }, { "code": null, "e": 26321, "s": 26290, "text": "Ruby | Array select() function" } ]
hostname command in Linux with examples - GeeksforGeeks
21 May, 2019 hostname command in Linux is used to obtain the DNS(Domain Name System) name and set the system’s hostname or NIS(Network Information System) domain name. A hostname is a name which is given to a computer and it attached to the network. Its main purpose is to uniquely identify over a network. Syntax : hostname -[option] [file] Example: We obtain the system hostname by just typing hostname without any attributes. Options: -a : This option is used to get alias name of the host system(if any). It will return an empty line if no alias name is set. This option enumerates all configured addresses on all network interfaces.Syntax:hostname -a Example: Syntax: hostname -a Example: -A : This option is used to get all FQDNs(Fully Qualified Domain Name) of the host system. It enumerates all configured addresses on all network interfaces. An output may display same entries repetitively.Syntax :hostname -A Example: Syntax : hostname -A Example: -b : Used to always set a hostname. Default name is used if none specified.Syntax :hostname -b Example: Syntax : hostname -b Example: -d : This option is used to get the Domain if local domains are set. It will not return anything(not even a blank line) if no local domain is set.Syntax :hostname -d Example : Syntax : hostname -d Example : -f : This option is used to get the Fully Qualified Domain Name(FQDN). It contains short hostname and DNS domain name.Syntax:hostname -f Example: Syntax: hostname -f Example: -F : This option is used to set the hostname specified in a file. Can be performed by the superuser(root) only.Syntax:sudo hostname -F filename Example: Syntax: sudo hostname -F filename Example: -i option:This option is used to get the IP(network) addresses. This option works only if the hostname is resolvable.Syntax:hostname -i Example: Syntax: hostname -i Example: -I : This option is used to get all IP(network) addresses. The option doesn’t depend on resolvability of hostname.hostname -I Example: hostname -I Example: -s : This option is used to get the hostname in short. The short hostname is the section of hostname before the first period/dot(.). If the hostname has no period, the full hostname is displayed.Syntax :hostname -s Example: Syntax : hostname -s Example: -V : Gives version number as output.Syntax:hostname -V Example: Syntax: hostname -V Example: Note: To set the hostname we can use the command given below: sudo hostname NEW_HOSTNAME Here, NEW_HOSTNAME is the new hostname the user wants to give. Example: linux-command Linux-networking-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ZIP command in Linux with examples TCP Server-Client implementation in C SORT command in Linux/Unix with examples tar command in Linux with examples curl command in Linux with Examples Conditional Statements | Shell Script diff command in Linux with examples UDP Server-Client implementation in C Tail command in Linux with examples echo command in Linux with Examples
[ { "code": null, "e": 25501, "s": 25473, "text": "\n21 May, 2019" }, { "code": null, "e": 25795, "s": 25501, "text": "hostname command in Linux is used to obtain the DNS(Domain Name System) name and set the system’s hostname or NIS(Network Information System) domain name. A hostname is a name which is given to a computer and it attached to the network. Its main purpose is to uniquely identify over a network." }, { "code": null, "e": 25804, "s": 25795, "text": "Syntax :" }, { "code": null, "e": 25831, "s": 25804, "text": "hostname -[option] [file]\n" }, { "code": null, "e": 25918, "s": 25831, "text": "Example: We obtain the system hostname by just typing hostname without any attributes." }, { "code": null, "e": 25927, "s": 25918, "text": "Options:" }, { "code": null, "e": 26154, "s": 25927, "text": "-a : This option is used to get alias name of the host system(if any). It will return an empty line if no alias name is set. This option enumerates all configured addresses on all network interfaces.Syntax:hostname -a\nExample:" }, { "code": null, "e": 26162, "s": 26154, "text": "Syntax:" }, { "code": null, "e": 26175, "s": 26162, "text": "hostname -a\n" }, { "code": null, "e": 26184, "s": 26175, "text": "Example:" }, { "code": null, "e": 26418, "s": 26184, "text": "-A : This option is used to get all FQDNs(Fully Qualified Domain Name) of the host system. It enumerates all configured addresses on all network interfaces. An output may display same entries repetitively.Syntax :hostname -A\nExample:" }, { "code": null, "e": 26427, "s": 26418, "text": "Syntax :" }, { "code": null, "e": 26440, "s": 26427, "text": "hostname -A\n" }, { "code": null, "e": 26449, "s": 26440, "text": "Example:" }, { "code": null, "e": 26553, "s": 26449, "text": "-b : Used to always set a hostname. Default name is used if none specified.Syntax :hostname -b\nExample:" }, { "code": null, "e": 26562, "s": 26553, "text": "Syntax :" }, { "code": null, "e": 26575, "s": 26562, "text": "hostname -b\n" }, { "code": null, "e": 26584, "s": 26575, "text": "Example:" }, { "code": null, "e": 26760, "s": 26584, "text": "-d : This option is used to get the Domain if local domains are set. It will not return anything(not even a blank line) if no local domain is set.Syntax :hostname -d\nExample :" }, { "code": null, "e": 26769, "s": 26760, "text": "Syntax :" }, { "code": null, "e": 26782, "s": 26769, "text": "hostname -d\n" }, { "code": null, "e": 26792, "s": 26782, "text": "Example :" }, { "code": null, "e": 26938, "s": 26792, "text": "-f : This option is used to get the Fully Qualified Domain Name(FQDN). It contains short hostname and DNS domain name.Syntax:hostname -f\nExample:" }, { "code": null, "e": 26946, "s": 26938, "text": "Syntax:" }, { "code": null, "e": 26959, "s": 26946, "text": "hostname -f\n" }, { "code": null, "e": 26968, "s": 26959, "text": "Example:" }, { "code": null, "e": 27121, "s": 26968, "text": "-F : This option is used to set the hostname specified in a file. Can be performed by the superuser(root) only.Syntax:sudo hostname -F filename\nExample:" }, { "code": null, "e": 27129, "s": 27121, "text": "Syntax:" }, { "code": null, "e": 27156, "s": 27129, "text": "sudo hostname -F filename\n" }, { "code": null, "e": 27165, "s": 27156, "text": "Example:" }, { "code": null, "e": 27310, "s": 27165, "text": "-i option:This option is used to get the IP(network) addresses. This option works only if the hostname is resolvable.Syntax:hostname -i\nExample:" }, { "code": null, "e": 27318, "s": 27310, "text": "Syntax:" }, { "code": null, "e": 27331, "s": 27318, "text": "hostname -i\n" }, { "code": null, "e": 27340, "s": 27331, "text": "Example:" }, { "code": null, "e": 27475, "s": 27340, "text": "-I : This option is used to get all IP(network) addresses. The option doesn’t depend on resolvability of hostname.hostname -I\nExample:" }, { "code": null, "e": 27488, "s": 27475, "text": "hostname -I\n" }, { "code": null, "e": 27497, "s": 27488, "text": "Example:" }, { "code": null, "e": 27721, "s": 27497, "text": "-s : This option is used to get the hostname in short. The short hostname is the section of hostname before the first period/dot(.). If the hostname has no period, the full hostname is displayed.Syntax :hostname -s\nExample:" }, { "code": null, "e": 27730, "s": 27721, "text": "Syntax :" }, { "code": null, "e": 27743, "s": 27730, "text": "hostname -s\n" }, { "code": null, "e": 27752, "s": 27743, "text": "Example:" }, { "code": null, "e": 27816, "s": 27752, "text": "-V : Gives version number as output.Syntax:hostname -V\nExample:" }, { "code": null, "e": 27824, "s": 27816, "text": "Syntax:" }, { "code": null, "e": 27837, "s": 27824, "text": "hostname -V\n" }, { "code": null, "e": 27846, "s": 27837, "text": "Example:" }, { "code": null, "e": 27908, "s": 27846, "text": "Note: To set the hostname we can use the command given below:" }, { "code": null, "e": 27936, "s": 27908, "text": "sudo hostname NEW_HOSTNAME\n" }, { "code": null, "e": 27999, "s": 27936, "text": "Here, NEW_HOSTNAME is the new hostname the user wants to give." }, { "code": null, "e": 28008, "s": 27999, "text": "Example:" }, { "code": null, "e": 28022, "s": 28008, "text": "linux-command" }, { "code": null, "e": 28048, "s": 28022, "text": "Linux-networking-commands" }, { "code": null, "e": 28055, "s": 28048, "text": "Picked" }, { "code": null, "e": 28066, "s": 28055, "text": "Linux-Unix" }, { "code": null, "e": 28164, "s": 28066, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28199, "s": 28164, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 28237, "s": 28199, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 28278, "s": 28237, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 28313, "s": 28278, "text": "tar command in Linux with examples" }, { "code": null, "e": 28349, "s": 28313, "text": "curl command in Linux with Examples" }, { "code": null, "e": 28387, "s": 28349, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 28423, "s": 28387, "text": "diff command in Linux with examples" }, { "code": null, "e": 28461, "s": 28423, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 28497, "s": 28461, "text": "Tail command in Linux with examples" } ]
std::is_same template in C++ with Examples - GeeksforGeeks
08 Jun, 2020 The std::is_same template of C++ STL is present in the <type_traits> header file. The std::is_same template of C++ STL is used to check whether the type A is same type as of B or not. It return the boolean value true if both are same, otherwise return false. Header File: #include<type_traits> Template Class: template <class A, class B> struct is_same template <class A, class B> inline constexpr bool is_same_v = is_same<A, B>::value Syntax: std::is_same<A, B>::value Parameters: This std::is_same template accepts the following parameters: A: It represent the first type. B: It represent the second type. Return Value: The template std::is_same returns a boolean variable as shown below: True: If the type A is same as the type B. False: If the type A is not same as the type B. Below is the program to demonstrate std::is_same in C++: Program: // C++ program to illustrate std::is_same#include <bits/stdc++.h>#include <type_traits>using namespace std; // Driver Codeint main(){ cout << boolalpha; cout << "is int & int32_t is same? " << is_same<int, int32_t>::value << endl; cout << "is int & int64_t is same? " << is_same<int, int64_t>::value << endl; cout << "is float & int32_t is same? " << is_same<float, int32_t>::value << endl; cout << "is int & int is same? " << is_same<int, int>::value << endl; cout << "is int & unsigned int is same? " << is_same<int, unsigned int>::value << endl; cout << "is int & signed int is same? " << is_same<int, signed int>::value << endl; return 0;} is int & int32_t is same? true is int & int64_t is same? false is float & int32_t is same? false is int & int is same? true is int & unsigned int is same? false is int & signed int is same? true Program 2: // C++ program to illustrate std::is_same#include <bits/stdc++.h>#include <type_traits>using namespace std; typedef int integer_type; // Declare structuresstruct A { int x, y;};struct B { int x, y;};typedef A C; // Driver Codeint main(){ cout << boolalpha; cout << "is_same:" << endl; cout << "int, const int is_same: " << is_same<int, const int>::value << endl; cout << "int, integer_type is_same: " << is_same<int, integer_type>::value << endl; cout << "A, B is_same: " << is_same<A, B>::value << endl; cout << "A, C is_same: " << is_same<A, C>::value << endl; cout << "signed char, int8_t is_same: " << is_same<signed char, int8_t>::value << endl; return 0;} is_same: int, const int is_same: false int, integer_type is_same: true A, B is_same: false A, C is_same: true signed char, int8_t is_same: true Reference: http://www.cplusplus.com/reference/type_traits/is_same/ CPP-Functions C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C++ Classes and Objects Templates in C++ with Examples Operator Overloading in C++ Socket Programming in C/C++ vector erase() and clear() in C++ Substring in C++ Multidimensional Arrays in C / C++ C++ Data Types Sorting a vector in C++ Set in C++ Standard Template Library (STL)
[ { "code": null, "e": 25407, "s": 25379, "text": "\n08 Jun, 2020" }, { "code": null, "e": 25666, "s": 25407, "text": "The std::is_same template of C++ STL is present in the <type_traits> header file. The std::is_same template of C++ STL is used to check whether the type A is same type as of B or not. It return the boolean value true if both are same, otherwise return false." }, { "code": null, "e": 25679, "s": 25666, "text": "Header File:" }, { "code": null, "e": 25702, "s": 25679, "text": "#include<type_traits>\n" }, { "code": null, "e": 25718, "s": 25702, "text": "Template Class:" }, { "code": null, "e": 25863, "s": 25718, "text": "template <class A, class B>\nstruct is_same\n\ntemplate <class A, class B>\ninline constexpr \n bool is_same_v\n = is_same<A, B>::value\n" }, { "code": null, "e": 25871, "s": 25863, "text": "Syntax:" }, { "code": null, "e": 25898, "s": 25871, "text": "std::is_same<A, B>::value\n" }, { "code": null, "e": 25971, "s": 25898, "text": "Parameters: This std::is_same template accepts the following parameters:" }, { "code": null, "e": 26003, "s": 25971, "text": "A: It represent the first type." }, { "code": null, "e": 26036, "s": 26003, "text": "B: It represent the second type." }, { "code": null, "e": 26119, "s": 26036, "text": "Return Value: The template std::is_same returns a boolean variable as shown below:" }, { "code": null, "e": 26162, "s": 26119, "text": "True: If the type A is same as the type B." }, { "code": null, "e": 26210, "s": 26162, "text": "False: If the type A is not same as the type B." }, { "code": null, "e": 26267, "s": 26210, "text": "Below is the program to demonstrate std::is_same in C++:" }, { "code": null, "e": 26276, "s": 26267, "text": "Program:" }, { "code": "// C++ program to illustrate std::is_same#include <bits/stdc++.h>#include <type_traits>using namespace std; // Driver Codeint main(){ cout << boolalpha; cout << \"is int & int32_t is same? \" << is_same<int, int32_t>::value << endl; cout << \"is int & int64_t is same? \" << is_same<int, int64_t>::value << endl; cout << \"is float & int32_t is same? \" << is_same<float, int32_t>::value << endl; cout << \"is int & int is same? \" << is_same<int, int>::value << endl; cout << \"is int & unsigned int is same? \" << is_same<int, unsigned int>::value << endl; cout << \"is int & signed int is same? \" << is_same<int, signed int>::value << endl; return 0;}", "e": 27047, "s": 26276, "text": null }, { "code": null, "e": 27243, "s": 27047, "text": "is int & int32_t is same? true\nis int & int64_t is same? false\nis float & int32_t is same? false\nis int & int is same? true\nis int & unsigned int is same? false\nis int & signed int is same? true\n" }, { "code": null, "e": 27254, "s": 27243, "text": "Program 2:" }, { "code": "// C++ program to illustrate std::is_same#include <bits/stdc++.h>#include <type_traits>using namespace std; typedef int integer_type; // Declare structuresstruct A { int x, y;};struct B { int x, y;};typedef A C; // Driver Codeint main(){ cout << boolalpha; cout << \"is_same:\" << endl; cout << \"int, const int is_same: \" << is_same<int, const int>::value << endl; cout << \"int, integer_type is_same: \" << is_same<int, integer_type>::value << endl; cout << \"A, B is_same: \" << is_same<A, B>::value << endl; cout << \"A, C is_same: \" << is_same<A, C>::value << endl; cout << \"signed char, int8_t is_same: \" << is_same<signed char, int8_t>::value << endl; return 0;}", "e": 28043, "s": 27254, "text": null }, { "code": null, "e": 28188, "s": 28043, "text": "is_same:\nint, const int is_same: false\nint, integer_type is_same: true\nA, B is_same: false\nA, C is_same: true\nsigned char, int8_t is_same: true\n" }, { "code": null, "e": 28255, "s": 28188, "text": "Reference: http://www.cplusplus.com/reference/type_traits/is_same/" }, { "code": null, "e": 28269, "s": 28255, "text": "CPP-Functions" }, { "code": null, "e": 28273, "s": 28269, "text": "C++" }, { "code": null, "e": 28277, "s": 28273, "text": "CPP" }, { "code": null, "e": 28375, "s": 28277, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28399, "s": 28375, "text": "C++ Classes and Objects" }, { "code": null, "e": 28430, "s": 28399, "text": "Templates in C++ with Examples" }, { "code": null, "e": 28458, "s": 28430, "text": "Operator Overloading in C++" }, { "code": null, "e": 28486, "s": 28458, "text": "Socket Programming in C/C++" }, { "code": null, "e": 28520, "s": 28486, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 28537, "s": 28520, "text": "Substring in C++" }, { "code": null, "e": 28572, "s": 28537, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 28587, "s": 28572, "text": "C++ Data Types" }, { "code": null, "e": 28611, "s": 28587, "text": "Sorting a vector in C++" } ]
Flutter - Mark as Favorite Feature - GeeksforGeeks
22 Feb, 2022 Adding to favorites is a prevalent feature in many applications. It enables the users to mark or save images, addressed, links or others stuff for easy future reference. In this article, we are going to see how to implement favorites or add to favorites feature in a flutter application. This article list two methods to do so. In the first method, we will add a simple (stateless widget) icon that changes color on tap, to mark a card for future reference. In the second example, we will be implementing a comparatively complex favorite feature which will involve StateFul widgets, saving the data in a set, and then displaying it on another screen. 1. In the first method we are going to add the heart-shaped button on the card, which will change its color on tap, to mark the card as a favorite or not favorite. The first thing that we need to do it to make a beautiful Card. You can take a look at this article to understand how the flutter Card widget is used. Dart //Code snippet of a card widget// /** Card Widget **/ child: Card( elevation: 50, shadowColor: Colors.black, color: Colors.greenAccent[100], child: SizedBox( width: 300, height: 500, child: Padding( padding: const EdgeInsets.all(20.0), child: Column( children: [ CircleAvatar( backgroundColor: Colors.green[500], radius: 108, child: CircleAvatar( backgroundImage: NetworkImage( "https://pbs.twimg.com/profile_images/1304985167476523008/QNHrwL2q_400x400.jpg"), //NetworkImage radius: 100, ), //CircleAvatar ), //CircleAvatar SizedBox( height: 10, ), //SizedBox Text( 'GeeksforGeeks', style: TextStyle( fontSize: 30, color: Colors.green[900], fontWeight: FontWeight.w500, ), //Textstyle ), //Text SizedBox( height: 10, ), //SizedBox Text( 'GeeksforGeeks is a computer science portal for geeks at geeksforgeeks.org. It contains well written, well thought and well explained computer science and programming articles, quizzes, projects, interview experienxes and much more!!', style: TextStyle( fontSize: 15, color: Colors.green[900], ), //Textstyle ), //Text SizedBox( height: 10, ), //SizedBox SizedBox( width: 80, child: RaisedButton( onPressed: () => null, color: Colors.green, child: Padding( padding: const EdgeInsets.all(4.0), child: Row( children: [ Icon(Icons.touch_app), Text('Visit'), ], ), //Row ), //Padding ), //RaisedButton ) //SizedBox ], ), //Column ), //Padding ), //SizedBox ), //Card This is the code snippet of a card widget which will look like this. For complete more information on the same, refer to this article. Now we will make the screen scrollable by wrapping the body of the flutter app with SingleChild ScrollView and create another card below the first one separated by a SizedBox. Dart //*Code snippet of the body*// body: SingleChildScrollView( padding: EdgeInsets.only(left: 0, right: 0, top: 20, bottom: 20), child: Center( /** Card Widget **/ child: Column( children: [ //Card 1 Card( ... ),//Card 1 SizedBox( height: 20, ), Card( ... ),//Card ), //Center ), //Scaffold And after doing all this we need, implement the favourite feature. The body of the above app contains two Cards in a SingleChildScrollView. Now to apply the above shown favourite feature we need to add the below code in the pubspec.yaml file. dependencies: favorite_button: ^0.0.3 This will add the favourite button package to our app. This package is a library which allows developers to implement heart or star-shaped favourites button with animation in out flutter application. Using this package is very simple the code for the heart-shaped button with the button being already selected is this: FavouriteButton( isFavorite: true, valueChanged: (_isFavourite) { print('Is Favourite $_isFavourite)'); }, ), And in case if we want the button to be unselected we can set the isFavourite parameter to false. This is the final code of the app. Dart import 'package:flutter/material.dart';import 'package:favorite_button/favorite_button.dart'; // importing dependenciesvoid main() { runApp( /**Our App Widget Tree Starts Here**/ MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.greenAccent[400], centerTitle: true, ), //AppBar body: SingleChildScrollView( padding: EdgeInsets.only(left: 0, right: 0, top: 20, bottom: 20), child: Center( /** Card Widget **/ child: Column( children: [ //Card 1 Card( elevation: 50, shadowColor: Colors.black, color: Colors.greenAccent[100], child: SizedBox( width: 310, height: 510, child: Padding( padding: const EdgeInsets.all(20.0), child: Column( children: [ CircleAvatar( backgroundColor: Colors.green[500], radius: 108, child: CircleAvatar( backgroundImage: NetworkImage( "https://pbs.twimg.com/profile_images/1304985167476523008/QNHrwL2q_400x400.jpg"), //NetworkImage radius: 100, ), //CircleAvatar ), //CircleAvatar SizedBox( height: 10, ), //SizedBox Text( 'GeeksforGeeks', style: TextStyle( fontSize: 30, color: Colors.green[900], fontWeight: FontWeight.w500, ), //Textstyle ), //Text SizedBox( height: 10, ), //SizedBox Text( 'GeeksforGeeks is a computer science portalfor geeks at geeksforgeeks.org. It contains well written, well thought and well explained computer science and programming articles, quizzes, projects, interview experienxes and much more!!', style: TextStyle( fontSize: 15, color: Colors.green[900], ), //Textstyle ), //Text SizedBox( height: 10, ), //SizedBox Row( mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox( width: 100, child: RaisedButton( onPressed: () => null, color: Colors.green, child: Padding( padding: const EdgeInsets.all(4.0), child: Row( children: [ Icon(Icons.touch_app), Text('Visit'), ], ), //Row ), //Padding ), //RaisedButton ), // Favourite Button FavoriteButton( isFavorite: false, valueChanged: (_isFavorite) { print('Is Favorite : $_isFavorite'); }, ), ], ), //SizedBox ], ), //Column ), //Padding ), //SizedBox ), SizedBox( height: 20, ), // Card 2 Card( elevation: 50, shadowColor: Colors.black, color: Colors.yellowAccent[100], child: SizedBox( width: 310, height: 510, child: Padding( padding: const EdgeInsets.all(20.0), child: Column( children: [ CircleAvatar( backgroundColor: Colors.yellow[700], radius: 108, child: CircleAvatar( backgroundImage: NetworkImage( "https://pbs.twimg.com/profile_images/1304985167476523008/QNHrwL2q_400x400.jpg"), //NetworkImage radius: 100, ), //CircleAvatar ), //CircleAvatar SizedBox( height: 10, ), //SizedBox Text( 'GeeksforGeeks', style: TextStyle( fontSize: 30, color: Colors.yellow[900], fontWeight: FontWeight.w500, ), //Textstyle ), //Text SizedBox( height: 10, ), //SizedBox Text( 'GeeksforGeeks is a computer science portalfor geeks at geeksforgeeks.org. It contains well written, well thought and well explained computer science and programming articles, quizzes, projects, interview experienxes and much more!!', style: TextStyle( fontSize: 15, color: Colors.yellow[900], ), //Textstyle ), //Text SizedBox( height: 10, ), //SizedBox Row( mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox( width: 100, child: RaisedButton( onPressed: () => null, color: Colors.yellow[600], child: Padding( padding: const EdgeInsets.all(4.0), child: Row( children: [ Icon(Icons.touch_app), Text('Visit'), ], ), //Row ), //Padding ), //RaisedButton ), // Favourite Button FavoriteButton( isFavorite: true, valueChanged: (_isFavorite) { print('Is Favorite : $_isFavorite'); }, ), ], ), //SizedBox ], ), //Column ), //Padding ), //SizedBox ), ], ), //Card ), ), //Center ), //Scaffold ) //MaterialApp );} Output: 2. This second example is a bit more complex compared to the previous one. In this application is a word-pair generator. In front of each word-pair, there is an add icon which changes to a green colored check icon whenever tapped, and in addition to the that the word-pair also gets saved in another screen. In this flutter application, we are generating random word-pairs on the list tile. The flutter package that we are using to get random English words is given below. The code given below needs to be added in the pubspec.yaml file in the dependencies section. english_words: ^3.1.5 Getting started: Dart import 'package:flutter/material.dart';import 'package:english_words/english_words.dart'; //importing dependenciesvoid main() => runApp(MyApp()); //inictating app buildclass MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData(primaryColor: Colors.green), home: RandWords(), debugShowCheckedModeBanner: false, ); }} The above code snippet is going to import dependencies (material design library and English word library) in our main.dart file and initiate the app build. The app that will be built is a material app and in the last line, the debug banner is set to disappear. Dart class RandWords extends StatefulWidget { @override RandWordsState createState() => RandWordsState();} class RandWordsState extends State<RandWords> { final _randomWordPairs = <WordPair>[]; final _addWordPairs = Set<WordPair>(); Widget _buildList() { return ListView.builder( padding: const EdgeInsets.all(16.0), itemBuilder: (context, item) { if (item.isEven) return Divider(); final index = item ~/ 2; if (index >= _randomWordPairs.length) { _randomWordPairs.addAll(generateWordPairs().take(10)); } return _buildRow(_randomWordPairs[index]); }, ); } In the above code, the class RandWordsState is maintaining the state of the RandWords class. Now the RandWordsState class will take in charge of most the app logic. In the RandWordsState class, we have two lists the first one for the random word-pair and the second one to save the word-pairs. After that in the build method, we are generating a ListView widget. The itemBuilder function is called for every word generated and if it is even the ListView widget gets separated by a divider. After that, we are pairing two random words to make a word-pair and when we reach the end of the words then ten new word-pairs are generated each time. Let’s see how the favorite feature works. Dart Widget _buildRow(WordPair pair) { final alreadyadd = _addWordPairs.contains(pair); // word-pair tile return ListTile( title: Text(pair.asPascalCase, style: TextStyle(fontSize: 18.0)), trailing: Icon(alreadyadd ? Icons.check : Icons.add, color: alreadyadd ? Colors.green : null), onTap: () { setState(() { if (alreadyadd) { _addWordPairs.remove(pair); } else { _addWordPairs.add(pair); } }); }); } The above code snippet generated the list tiles for the word-pairs checks if the word is already saved in the list or not to specify the icon. And there is an on-tap function which adds or removes the word-pair from the set and also changes the icon to green check if it is already saved from the pale add icon. Dart void _pushadd() => Navigator.of(context) .push(MaterialPageRoute(builder: (BuildContext context) { final Iterable<ListTile> tiles = _addWordPairs.map((WordPair pair) { return ListTile( title: Text(pair.asPascalCase, style: TextStyle(fontSize: 16.0))); }); final List<Widget> divided = ListTile.divideTiles(context: context, tiles: tiles).toList(); // saved word-pair page return Scaffold( appBar: AppBar(title: Text('Saved Word-Pairs')), body: ListView(children: divided)); }));//MaterialPageRoute The above code snippet generates the screen in which the word-pair along with the ListTile is listed takes from the set in which it was added earlier. Complete Source Code: Dart import 'package:flutter/material.dart';import 'package:english_words/english_words.dart'; // importing dependenciesvoid main() => runApp(MyApp()); // inictating app buildclass MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData(primaryColor: Colors.green), home: RandWords(), debugShowCheckedModeBanner: false, ); }} class RandWords extends StatefulWidget { @override RandWordsState createState() => RandWordsState();} class RandWordsState extends State<RandWords> { final _randomWordPairs = <WordPair>[]; final _addWordPairs = Set<WordPair>(); Widget _buildList() { return ListView.builder( padding: const EdgeInsets.all(16.0), itemBuilder: (context, item) { if (item.isEven) return Divider(); final index = item ~/ 2; if (index >= _randomWordPairs.length) { _randomWordPairs.addAll(generateWordPairs().take(10)); } return _buildRow(_randomWordPairs[index]); }, ); } Widget _buildRow(WordPair pair) { final alreadyadd = _addWordPairs.contains(pair); // word-pair tile return ListTile( title: Text(pair.asPascalCase, style: TextStyle(fontSize: 18.0)), trailing: Icon(alreadyadd ? Icons.check : Icons.add, color: alreadyadd ? Colors.green : null), onTap: () { setState(() { if (alreadyadd) { _addWordPairs.remove(pair); } else { _addWordPairs.add(pair); } }); }); } void _pushadd() => Navigator.of(context) .push(MaterialPageRoute(builder: (BuildContext context) { final Iterable<ListTile> tiles = _addWordPairs.map((WordPair pair) { return ListTile( title: Text(pair.asPascalCase, style: TextStyle(fontSize: 16.0))); }); final List<Widget> divided = ListTile.divideTiles(context: context, tiles: tiles).toList(); // saved word-pair page return Scaffold( appBar: AppBar(title: Text('Saved Word-Pairs')), body: ListView(children: divided)); })); // home page Widget build(BuildContext context) => Scaffold( appBar: AppBar( title: Text('GeeksforGeeks Word-Pair Generator'), actions: <Widget>[ IconButton(icon: Icon(Icons.menu_book), onPressed: _pushadd) ], ), body: _buildList());} Output: gulshankumarar231 simranarora5sos arorakashish0911 android Flutter Picked Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar Flutter - Checkbox Widget ListView Class in Flutter Flutter - Flexible Widget Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar Flutter Tutorial Flutter - Checkbox Widget Flutter - Flexible Widget
[ { "code": null, "e": 25687, "s": 25659, "text": "\n22 Feb, 2022" }, { "code": null, "e": 26338, "s": 25687, "text": "Adding to favorites is a prevalent feature in many applications. It enables the users to mark or save images, addressed, links or others stuff for easy future reference. In this article, we are going to see how to implement favorites or add to favorites feature in a flutter application. This article list two methods to do so. In the first method, we will add a simple (stateless widget) icon that changes color on tap, to mark a card for future reference. In the second example, we will be implementing a comparatively complex favorite feature which will involve StateFul widgets, saving the data in a set, and then displaying it on another screen." }, { "code": null, "e": 26502, "s": 26338, "text": "1. In the first method we are going to add the heart-shaped button on the card, which will change its color on tap, to mark the card as a favorite or not favorite." }, { "code": null, "e": 26653, "s": 26502, "text": "The first thing that we need to do it to make a beautiful Card. You can take a look at this article to understand how the flutter Card widget is used." }, { "code": null, "e": 26658, "s": 26653, "text": "Dart" }, { "code": "//Code snippet of a card widget// /** Card Widget **/ child: Card( elevation: 50, shadowColor: Colors.black, color: Colors.greenAccent[100], child: SizedBox( width: 300, height: 500, child: Padding( padding: const EdgeInsets.all(20.0), child: Column( children: [ CircleAvatar( backgroundColor: Colors.green[500], radius: 108, child: CircleAvatar( backgroundImage: NetworkImage( \"https://pbs.twimg.com/profile_images/1304985167476523008/QNHrwL2q_400x400.jpg\"), //NetworkImage radius: 100, ), //CircleAvatar ), //CircleAvatar SizedBox( height: 10, ), //SizedBox Text( 'GeeksforGeeks', style: TextStyle( fontSize: 30, color: Colors.green[900], fontWeight: FontWeight.w500, ), //Textstyle ), //Text SizedBox( height: 10, ), //SizedBox Text( 'GeeksforGeeks is a computer science portal for geeks at geeksforgeeks.org. It contains well written, well thought and well explained computer science and programming articles, quizzes, projects, interview experienxes and much more!!', style: TextStyle( fontSize: 15, color: Colors.green[900], ), //Textstyle ), //Text SizedBox( height: 10, ), //SizedBox SizedBox( width: 80, child: RaisedButton( onPressed: () => null, color: Colors.green, child: Padding( padding: const EdgeInsets.all(4.0), child: Row( children: [ Icon(Icons.touch_app), Text('Visit'), ], ), //Row ), //Padding ), //RaisedButton ) //SizedBox ], ), //Column ), //Padding ), //SizedBox ), //Card", "e": 29323, "s": 26658, "text": null }, { "code": null, "e": 29458, "s": 29323, "text": "This is the code snippet of a card widget which will look like this. For complete more information on the same, refer to this article." }, { "code": null, "e": 29636, "s": 29458, "text": "Now we will make the screen scrollable by wrapping the body of the flutter app with SingleChild ScrollView and create another card below the first one separated by a SizedBox. " }, { "code": null, "e": 29641, "s": 29636, "text": "Dart" }, { "code": "//*Code snippet of the body*// body: SingleChildScrollView( padding: EdgeInsets.only(left: 0, right: 0, top: 20, bottom: 20), child: Center( /** Card Widget **/ child: Column( children: [ //Card 1 Card( ... ),//Card 1 SizedBox( height: 20, ), Card( ... ),//Card ), //Center ), //Scaffold", "e": 30083, "s": 29641, "text": null }, { "code": null, "e": 30150, "s": 30083, "text": "And after doing all this we need, implement the favourite feature." }, { "code": null, "e": 30326, "s": 30150, "text": "The body of the above app contains two Cards in a SingleChildScrollView. Now to apply the above shown favourite feature we need to add the below code in the pubspec.yaml file." }, { "code": null, "e": 30365, "s": 30326, "text": "dependencies:\n favorite_button: ^0.0.3" }, { "code": null, "e": 30565, "s": 30365, "text": "This will add the favourite button package to our app. This package is a library which allows developers to implement heart or star-shaped favourites button with animation in out flutter application." }, { "code": null, "e": 30684, "s": 30565, "text": "Using this package is very simple the code for the heart-shaped button with the button being already selected is this:" }, { "code": null, "e": 30826, "s": 30684, "text": "FavouriteButton(\n isFavorite: true,\n valueChanged: (_isFavourite) {\n print('Is Favourite $_isFavourite)');\n },\n )," }, { "code": null, "e": 30925, "s": 30826, "text": "And in case if we want the button to be unselected we can set the isFavourite parameter to false. " }, { "code": null, "e": 30960, "s": 30925, "text": "This is the final code of the app." }, { "code": null, "e": 30965, "s": 30960, "text": "Dart" }, { "code": "import 'package:flutter/material.dart';import 'package:favorite_button/favorite_button.dart'; // importing dependenciesvoid main() { runApp( /**Our App Widget Tree Starts Here**/ MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.greenAccent[400], centerTitle: true, ), //AppBar body: SingleChildScrollView( padding: EdgeInsets.only(left: 0, right: 0, top: 20, bottom: 20), child: Center( /** Card Widget **/ child: Column( children: [ //Card 1 Card( elevation: 50, shadowColor: Colors.black, color: Colors.greenAccent[100], child: SizedBox( width: 310, height: 510, child: Padding( padding: const EdgeInsets.all(20.0), child: Column( children: [ CircleAvatar( backgroundColor: Colors.green[500], radius: 108, child: CircleAvatar( backgroundImage: NetworkImage( \"https://pbs.twimg.com/profile_images/1304985167476523008/QNHrwL2q_400x400.jpg\"), //NetworkImage radius: 100, ), //CircleAvatar ), //CircleAvatar SizedBox( height: 10, ), //SizedBox Text( 'GeeksforGeeks', style: TextStyle( fontSize: 30, color: Colors.green[900], fontWeight: FontWeight.w500, ), //Textstyle ), //Text SizedBox( height: 10, ), //SizedBox Text( 'GeeksforGeeks is a computer science portalfor geeks at geeksforgeeks.org. It contains well written, well thought and well explained computer science and programming articles, quizzes, projects, interview experienxes and much more!!', style: TextStyle( fontSize: 15, color: Colors.green[900], ), //Textstyle ), //Text SizedBox( height: 10, ), //SizedBox Row( mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox( width: 100, child: RaisedButton( onPressed: () => null, color: Colors.green, child: Padding( padding: const EdgeInsets.all(4.0), child: Row( children: [ Icon(Icons.touch_app), Text('Visit'), ], ), //Row ), //Padding ), //RaisedButton ), // Favourite Button FavoriteButton( isFavorite: false, valueChanged: (_isFavorite) { print('Is Favorite : $_isFavorite'); }, ), ], ), //SizedBox ], ), //Column ), //Padding ), //SizedBox ), SizedBox( height: 20, ), // Card 2 Card( elevation: 50, shadowColor: Colors.black, color: Colors.yellowAccent[100], child: SizedBox( width: 310, height: 510, child: Padding( padding: const EdgeInsets.all(20.0), child: Column( children: [ CircleAvatar( backgroundColor: Colors.yellow[700], radius: 108, child: CircleAvatar( backgroundImage: NetworkImage( \"https://pbs.twimg.com/profile_images/1304985167476523008/QNHrwL2q_400x400.jpg\"), //NetworkImage radius: 100, ), //CircleAvatar ), //CircleAvatar SizedBox( height: 10, ), //SizedBox Text( 'GeeksforGeeks', style: TextStyle( fontSize: 30, color: Colors.yellow[900], fontWeight: FontWeight.w500, ), //Textstyle ), //Text SizedBox( height: 10, ), //SizedBox Text( 'GeeksforGeeks is a computer science portalfor geeks at geeksforgeeks.org. It contains well written, well thought and well explained computer science and programming articles, quizzes, projects, interview experienxes and much more!!', style: TextStyle( fontSize: 15, color: Colors.yellow[900], ), //Textstyle ), //Text SizedBox( height: 10, ), //SizedBox Row( mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox( width: 100, child: RaisedButton( onPressed: () => null, color: Colors.yellow[600], child: Padding( padding: const EdgeInsets.all(4.0), child: Row( children: [ Icon(Icons.touch_app), Text('Visit'), ], ), //Row ), //Padding ), //RaisedButton ), // Favourite Button FavoriteButton( isFavorite: true, valueChanged: (_isFavorite) { print('Is Favorite : $_isFavorite'); }, ), ], ), //SizedBox ], ), //Column ), //Padding ), //SizedBox ), ], ), //Card ), ), //Center ), //Scaffold ) //MaterialApp );}", "e": 39000, "s": 30965, "text": null }, { "code": null, "e": 39008, "s": 39000, "text": "Output:" }, { "code": null, "e": 39317, "s": 39008, "text": "2. This second example is a bit more complex compared to the previous one. In this application is a word-pair generator. In front of each word-pair, there is an add icon which changes to a green colored check icon whenever tapped, and in addition to the that the word-pair also gets saved in another screen." }, { "code": null, "e": 39576, "s": 39317, "text": " In this flutter application, we are generating random word-pairs on the list tile. The flutter package that we are using to get random English words is given below. The code given below needs to be added in the pubspec.yaml file in the dependencies section." }, { "code": null, "e": 39599, "s": 39576, "text": " english_words: ^3.1.5" }, { "code": null, "e": 39616, "s": 39599, "text": "Getting started:" }, { "code": null, "e": 39621, "s": 39616, "text": "Dart" }, { "code": "import 'package:flutter/material.dart';import 'package:english_words/english_words.dart'; //importing dependenciesvoid main() => runApp(MyApp()); //inictating app buildclass MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData(primaryColor: Colors.green), home: RandWords(), debugShowCheckedModeBanner: false, ); }}", "e": 40024, "s": 39621, "text": null }, { "code": null, "e": 40286, "s": 40024, "text": "The above code snippet is going to import dependencies (material design library and English word library) in our main.dart file and initiate the app build. The app that will be built is a material app and in the last line, the debug banner is set to disappear. " }, { "code": null, "e": 40291, "s": 40286, "text": "Dart" }, { "code": "class RandWords extends StatefulWidget { @override RandWordsState createState() => RandWordsState();} class RandWordsState extends State<RandWords> { final _randomWordPairs = <WordPair>[]; final _addWordPairs = Set<WordPair>(); Widget _buildList() { return ListView.builder( padding: const EdgeInsets.all(16.0), itemBuilder: (context, item) { if (item.isEven) return Divider(); final index = item ~/ 2; if (index >= _randomWordPairs.length) { _randomWordPairs.addAll(generateWordPairs().take(10)); } return _buildRow(_randomWordPairs[index]); }, ); }", "e": 40917, "s": 40291, "text": null }, { "code": null, "e": 41560, "s": 40917, "text": "In the above code, the class RandWordsState is maintaining the state of the RandWords class. Now the RandWordsState class will take in charge of most the app logic. In the RandWordsState class, we have two lists the first one for the random word-pair and the second one to save the word-pairs. After that in the build method, we are generating a ListView widget. The itemBuilder function is called for every word generated and if it is even the ListView widget gets separated by a divider. After that, we are pairing two random words to make a word-pair and when we reach the end of the words then ten new word-pairs are generated each time." }, { "code": null, "e": 41602, "s": 41560, "text": "Let’s see how the favorite feature works." }, { "code": null, "e": 41607, "s": 41602, "text": "Dart" }, { "code": "Widget _buildRow(WordPair pair) { final alreadyadd = _addWordPairs.contains(pair); // word-pair tile return ListTile( title: Text(pair.asPascalCase, style: TextStyle(fontSize: 18.0)), trailing: Icon(alreadyadd ? Icons.check : Icons.add, color: alreadyadd ? Colors.green : null), onTap: () { setState(() { if (alreadyadd) { _addWordPairs.remove(pair); } else { _addWordPairs.add(pair); } }); }); }", "e": 42107, "s": 41607, "text": null }, { "code": null, "e": 42420, "s": 42107, "text": " The above code snippet generated the list tiles for the word-pairs checks if the word is already saved in the list or not to specify the icon. And there is an on-tap function which adds or removes the word-pair from the set and also changes the icon to green check if it is already saved from the pale add icon." }, { "code": null, "e": 42425, "s": 42420, "text": "Dart" }, { "code": "void _pushadd() => Navigator.of(context) .push(MaterialPageRoute(builder: (BuildContext context) { final Iterable<ListTile> tiles = _addWordPairs.map((WordPair pair) { return ListTile( title: Text(pair.asPascalCase, style: TextStyle(fontSize: 16.0))); }); final List<Widget> divided = ListTile.divideTiles(context: context, tiles: tiles).toList(); // saved word-pair page return Scaffold( appBar: AppBar(title: Text('Saved Word-Pairs')), body: ListView(children: divided)); }));//MaterialPageRoute", "e": 43015, "s": 42425, "text": null }, { "code": null, "e": 43167, "s": 43015, "text": " The above code snippet generates the screen in which the word-pair along with the ListTile is listed takes from the set in which it was added earlier." }, { "code": null, "e": 43189, "s": 43167, "text": "Complete Source Code:" }, { "code": null, "e": 43194, "s": 43189, "text": "Dart" }, { "code": "import 'package:flutter/material.dart';import 'package:english_words/english_words.dart'; // importing dependenciesvoid main() => runApp(MyApp()); // inictating app buildclass MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData(primaryColor: Colors.green), home: RandWords(), debugShowCheckedModeBanner: false, ); }} class RandWords extends StatefulWidget { @override RandWordsState createState() => RandWordsState();} class RandWordsState extends State<RandWords> { final _randomWordPairs = <WordPair>[]; final _addWordPairs = Set<WordPair>(); Widget _buildList() { return ListView.builder( padding: const EdgeInsets.all(16.0), itemBuilder: (context, item) { if (item.isEven) return Divider(); final index = item ~/ 2; if (index >= _randomWordPairs.length) { _randomWordPairs.addAll(generateWordPairs().take(10)); } return _buildRow(_randomWordPairs[index]); }, ); } Widget _buildRow(WordPair pair) { final alreadyadd = _addWordPairs.contains(pair); // word-pair tile return ListTile( title: Text(pair.asPascalCase, style: TextStyle(fontSize: 18.0)), trailing: Icon(alreadyadd ? Icons.check : Icons.add, color: alreadyadd ? Colors.green : null), onTap: () { setState(() { if (alreadyadd) { _addWordPairs.remove(pair); } else { _addWordPairs.add(pair); } }); }); } void _pushadd() => Navigator.of(context) .push(MaterialPageRoute(builder: (BuildContext context) { final Iterable<ListTile> tiles = _addWordPairs.map((WordPair pair) { return ListTile( title: Text(pair.asPascalCase, style: TextStyle(fontSize: 16.0))); }); final List<Widget> divided = ListTile.divideTiles(context: context, tiles: tiles).toList(); // saved word-pair page return Scaffold( appBar: AppBar(title: Text('Saved Word-Pairs')), body: ListView(children: divided)); })); // home page Widget build(BuildContext context) => Scaffold( appBar: AppBar( title: Text('GeeksforGeeks Word-Pair Generator'), actions: <Widget>[ IconButton(icon: Icon(Icons.menu_book), onPressed: _pushadd) ], ), body: _buildList());}", "e": 45637, "s": 43194, "text": null }, { "code": null, "e": 45646, "s": 45637, "text": "Output: " }, { "code": null, "e": 45664, "s": 45646, "text": "gulshankumarar231" }, { "code": null, "e": 45680, "s": 45664, "text": "simranarora5sos" }, { "code": null, "e": 45697, "s": 45680, "text": "arorakashish0911" }, { "code": null, "e": 45705, "s": 45697, "text": "android" }, { "code": null, "e": 45713, "s": 45705, "text": "Flutter" }, { "code": null, "e": 45720, "s": 45713, "text": "Picked" }, { "code": null, "e": 45725, "s": 45720, "text": "Dart" }, { "code": null, "e": 45733, "s": 45725, "text": "Flutter" }, { "code": null, "e": 45831, "s": 45733, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45863, "s": 45831, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 45902, "s": 45863, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 45928, "s": 45902, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 45954, "s": 45928, "text": "ListView Class in Flutter" }, { "code": null, "e": 45980, "s": 45954, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 46012, "s": 45980, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 46051, "s": 46012, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 46068, "s": 46051, "text": "Flutter Tutorial" }, { "code": null, "e": 46094, "s": 46068, "text": "Flutter - Checkbox Widget" } ]
Python - Convert key-values list to flat dictionary - GeeksforGeeks
22 Apr, 2020 Sometimes, while working with Python dictionaries, we can have a problem in which we need to flatten dictionary of key-value pair pairing the equal index elements together. This can have utilities in web development and Data Science domain. Lets discuss certain way in which this task can be performed. Method : zip() + dict()The combination of above functions can be used to achieve the required task. In this, we perform the pairing using zip() and dict() is used to convert tuple data returned by zip() to dictionary format. # Python3 code to demonstrate working of # Convert key-values list to flat dictionary# Using dict() + zip()from itertools import product # initializing dictionarytest_dict = {'month' : [1, 2, 3], 'name' : ['Jan', 'Feb', 'March']} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Convert key-values list to flat dictionary# Using dict() + zip()res = dict(zip(test_dict['month'], test_dict['name'])) # printing result print("Flattened dictionary : " + str(res)) The original dictionary is : {‘name’: [‘Jan’, ‘Feb’, ‘March’], ‘month’: [1, 2, 3]}Flattened dictionary : {1: ‘Jan’, 2: ‘Feb’, 3: ‘March’} Python dictionary-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": 25563, "s": 25535, "text": "\n22 Apr, 2020" }, { "code": null, "e": 25866, "s": 25563, "text": "Sometimes, while working with Python dictionaries, we can have a problem in which we need to flatten dictionary of key-value pair pairing the equal index elements together. This can have utilities in web development and Data Science domain. Lets discuss certain way in which this task can be performed." }, { "code": null, "e": 26091, "s": 25866, "text": "Method : zip() + dict()The combination of above functions can be used to achieve the required task. In this, we perform the pairing using zip() and dict() is used to convert tuple data returned by zip() to dictionary format." }, { "code": "# Python3 code to demonstrate working of # Convert key-values list to flat dictionary# Using dict() + zip()from itertools import product # initializing dictionarytest_dict = {'month' : [1, 2, 3], 'name' : ['Jan', 'Feb', 'March']} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Convert key-values list to flat dictionary# Using dict() + zip()res = dict(zip(test_dict['month'], test_dict['name'])) # printing result print(\"Flattened dictionary : \" + str(res)) ", "e": 26607, "s": 26091, "text": null }, { "code": null, "e": 26745, "s": 26607, "text": "The original dictionary is : {‘name’: [‘Jan’, ‘Feb’, ‘March’], ‘month’: [1, 2, 3]}Flattened dictionary : {1: ‘Jan’, 2: ‘Feb’, 3: ‘March’}" }, { "code": null, "e": 26772, "s": 26745, "text": "Python dictionary-programs" }, { "code": null, "e": 26779, "s": 26772, "text": "Python" }, { "code": null, "e": 26795, "s": 26779, "text": "Python Programs" }, { "code": null, "e": 26893, "s": 26795, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26925, "s": 26893, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26967, "s": 26925, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27009, "s": 26967, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27065, "s": 27009, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27092, "s": 27065, "text": "Python Classes and Objects" }, { "code": null, "e": 27114, "s": 27092, "text": "Defaultdict in Python" }, { "code": null, "e": 27153, "s": 27114, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27199, "s": 27153, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27237, "s": 27199, "text": "Python | Convert a list to dictionary" } ]
Switch Case in Dart - GeeksforGeeks
10 May, 2020 In Dart, switch-case statements are a simplified version of the nested if-else statements. Its approach is the same as that in Java. Syntax: switch ( expression ) { case value1: { // Body of value1 } break; case value2: { //Body of value2 } break; . . . default: { //Body of default case } break; } The default case is the case whose body is executed if none of the above cases matches the condition. Rules to follow in switch case: There can be any number of cases. But values should not be repeated.The case statements can include only constants. It should not be a variable or an expression.There should be a flow control i.e break within cases. If it is omitted than it will show error.The default case is optional.Nested switch is also there thus you can have switch inside switch. There can be any number of cases. But values should not be repeated. The case statements can include only constants. It should not be a variable or an expression. There should be a flow control i.e break within cases. If it is omitted than it will show error. The default case is optional. Nested switch is also there thus you can have switch inside switch. Example 1: Normal switch-case statement void main(){ int gfg = 1; switch (gfg) { case 1: { print("GeeksforGeeks number 1"); } break; case 2: { print("GeeksforGeeks number 2"); } break; case 3: { print("GeeksforGeeks number 3"); } break; default: { print("This is default case"); } break; }} Output: GeeksforGeeks number 1 Example 2: Nested switch-case statement void main(){ int gfg1 = 1; String gfg2 = "Geek"; switch (gfg1) { case 1: { switch (gfg2) { case 'Geek': { print("Welcome to GeeksforGeeks"); } } } break; case 2: { print("GeeksforGeeks number 2"); } break; default: { print("This is default case"); } break; }} Output: Welcome to GeeksforGeeks Dart-basics Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Flutter - Checkbox Widget Flutter - Flexible Widget Flutter - BoxShadow Widget Dart Tutorial Container class in Flutter Flutter - Stack Widget Operators in Dart
[ { "code": null, "e": 25277, "s": 25249, "text": "\n10 May, 2020" }, { "code": null, "e": 25410, "s": 25277, "text": "In Dart, switch-case statements are a simplified version of the nested if-else statements. Its approach is the same as that in Java." }, { "code": null, "e": 25418, "s": 25410, "text": "Syntax:" }, { "code": null, "e": 25632, "s": 25418, "text": "switch ( expression ) { \n case value1: { \n // Body of value1\n } break; \n case value2: { \n //Body of value2 \n } break; \n .\n .\n .\n default: { \n //Body of default case \n } break; \n} " }, { "code": null, "e": 25734, "s": 25632, "text": "The default case is the case whose body is executed if none of the above cases matches the condition." }, { "code": null, "e": 25766, "s": 25734, "text": "Rules to follow in switch case:" }, { "code": null, "e": 26120, "s": 25766, "text": "There can be any number of cases. But values should not be repeated.The case statements can include only constants. It should not be a variable or an expression.There should be a flow control i.e break within cases. If it is omitted than it will show error.The default case is optional.Nested switch is also there thus you can have switch inside switch." }, { "code": null, "e": 26189, "s": 26120, "text": "There can be any number of cases. But values should not be repeated." }, { "code": null, "e": 26283, "s": 26189, "text": "The case statements can include only constants. It should not be a variable or an expression." }, { "code": null, "e": 26380, "s": 26283, "text": "There should be a flow control i.e break within cases. If it is omitted than it will show error." }, { "code": null, "e": 26410, "s": 26380, "text": "The default case is optional." }, { "code": null, "e": 26478, "s": 26410, "text": "Nested switch is also there thus you can have switch inside switch." }, { "code": null, "e": 26518, "s": 26478, "text": "Example 1: Normal switch-case statement" }, { "code": "void main(){ int gfg = 1; switch (gfg) { case 1: { print(\"GeeksforGeeks number 1\"); } break; case 2: { print(\"GeeksforGeeks number 2\"); } break; case 3: { print(\"GeeksforGeeks number 3\"); } break; default: { print(\"This is default case\"); } break; }}", "e": 26830, "s": 26518, "text": null }, { "code": null, "e": 26838, "s": 26830, "text": "Output:" }, { "code": null, "e": 26861, "s": 26838, "text": "GeeksforGeeks number 1" }, { "code": null, "e": 26901, "s": 26861, "text": "Example 2: Nested switch-case statement" }, { "code": "void main(){ int gfg1 = 1; String gfg2 = \"Geek\"; switch (gfg1) { case 1: { switch (gfg2) { case 'Geek': { print(\"Welcome to GeeksforGeeks\"); } } } break; case 2: { print(\"GeeksforGeeks number 2\"); } break; default: { print(\"This is default case\"); } break; }}", "e": 27244, "s": 26901, "text": null }, { "code": null, "e": 27252, "s": 27244, "text": "Output:" }, { "code": null, "e": 27277, "s": 27252, "text": "Welcome to GeeksforGeeks" }, { "code": null, "e": 27289, "s": 27277, "text": "Dart-basics" }, { "code": null, "e": 27294, "s": 27289, "text": "Dart" }, { "code": null, "e": 27392, "s": 27294, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27424, "s": 27392, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 27463, "s": 27424, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 27489, "s": 27463, "text": "ListView Class in Flutter" }, { "code": null, "e": 27515, "s": 27489, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 27541, "s": 27515, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 27568, "s": 27541, "text": "Flutter - BoxShadow Widget" }, { "code": null, "e": 27582, "s": 27568, "text": "Dart Tutorial" }, { "code": null, "e": 27609, "s": 27582, "text": "Container class in Flutter" }, { "code": null, "e": 27632, "s": 27609, "text": "Flutter - Stack Widget" } ]
How to Calculate Manhattan Distance in R? - GeeksforGeeks
24 Dec, 2021 Manhattan distance is a distance metric between two points in an N-dimensional vector space. It is defined as the sum of absolute distance between coordinates in corresponding dimensions. For example, In a 2-dimensional space having two points Point1 (x1,y1) and Point2 (x2,y2), the Manhattan distance is given by |x1 – x2| + |y1 – y2|. In R Manhattan distance is calculated with respect to vectors. The Manhattan distance between the two vectors is given by, Σ|vect1i - vect2i| where, vect1 is the first vector vect2 is the second vector For example, we are given two vectors, vect1 as (3, 6, 8, 9) and vect2 as (1, 7, 8, 10). Their Manhattan distance is given by, |3 – 1| + |6 – 7| + |8 – 8| + |9 – 10| which is equal to 4. Below is the implementation using two vectors of equal length: Example 1: R # Function to calculate Manhattan distance# abs() function calculate the absolute difference# between corresponding vector elements# sum() function calculates the sum of the# absolute difference between# corresponding elements of vect1 and vect2manhattanDistance <- function(vect1, vect2){ dist <- abs(vect1 - vect2) dist <- sum(dist) return(dist)} # Initializing a vectorvect1 <- c(3, 6, 8, 9) # Initializing another vectorvect2 <- c(1, 7, 8, 10) print("Manhattan distance between vect1 and vect2 is: ") # Call the function to calculate Manhattan# distance between vectorsmanhattanDistance(vect1, vect2) Output: [1] "Manhattan distance between vect1 and vect2 is: " [1] 4 Example 2: If the two vectors have unequal length then the compiler gives a warning message. Below is the implementation using two vectors having unequal lengths. R # Function to calculate Manhattan distance# abs() function calculate the absolute difference# between corresponding vector elements# sum() function calculates the sum of the# absolute difference between# corresponding elements of vect1 and vect2manhattanDistance <- function(vect1, vect2){ dist <- abs(vect1 - vect2) dist <- sum(dist) return(dist)} # Initializing two vectors having unequal lengthvect1 <- c(14, 13, 24, 18)vect2 <- c(13, 12, 33, 11, 12) print("Manhattan distance between vect1 and vect2 is: ") # Call the function to calculate Manhattan distancemanhattanDistance(vect1, vect2) Output: R provides an inbuilt function using which we can find the Manhattan distance between each unique pair of vectors in a 2-dimensional vector. Syntax: dist(2dVect, method = “manhattan”) Parameters: 2dVect: two-dimensional vector method: the distance measure to be used. This can be one of “euclidean”, “maximum”, “manhattan”, “canberra”, “binary” Return type: It return an object of class “dist” Example 1: Below is the implementation to find Manhattan distance using dist() function: R # Initializing a vectorvect1 < - c(1, 16, 8, 10, 100, 20) # Initializing another vectorvect2 < - c(1, 7, 18, 90, 50, 21) # Initializing another vectorvect3 < - c(3, 10, 11, 40, 150, 210) # Initializing another vectorvect4 < - c(2, 1, 4, 7, 8, 10) # Initializing another vectorvect5 < - c(1, 4, 8, 3, 100, 104) # Initializing another vectorvect6 < - c(3, 7, 11, 23, 110, 114) # Row bind vectors into a single matrixtwoDimensionalVect < - rbind(vect1, vect2, vect3, vect4, vect5, vect6) print("Manhattan distance between each pair of vectors is: ")cat("\n\n") # Calculate Manhattan distance between vectors# using built in dist method# By passing two-dimensional vector as a parameter# Since we want to calculate manhattan distance between# each unique pair of vectors# That is why we are passing manhattan as a methoddist(twoDimensionalVect, method="manhattan") Output: Example 2: Note that the length of all the vectors presented under the 2-dimensional vector is required to be the same otherwise, the R compiler produces a compiler-time error. R # Initializing a vectorvect1 <- c(4, 3, 5, 7, 8, 2, 10, 12) # Initializing another vectorvect2 <- c(5, 9, 4, 9, 7, 17) # Initializing another vectorvect3 <- c(3, 10, 9, 11, 13, 12) # Initializing another vectorvect4 <- c(4, 7, 6, 12, 10, 12) # Initializing another vectorvect5 <- c(3, 5, 12, 10, 1, 17) # Initializing another vectorvect6 <- c(4, 3, 1, 8, 7, 2) # Using rind function to bind vectors in a 2-d vector# Note that all vectors are not of the same lengthtwoDimensionalVect <- rbind(vect1, vect2, vect3, vect4, vect5, vect6) print("Manhattan distance between each pair of vectors is: ")cat("\n\n") # Calculate Manhattan distance between vectors# using built in dist method# By passing two-dimensional vector as a parameter# Since we want to calculate Manhattan distance# between each pair of vectors# That is why we are passing "manhattan" as a methoddist(twoDimensionalVect, method = "manhattan") Output: anikakapoor Picked R-Statistics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R How to filter R dataframe by multiple conditions? R - if statement How to import an Excel File into R ? Time Series Analysis in R
[ { "code": null, "e": 24851, "s": 24823, "text": "\n24 Dec, 2021" }, { "code": null, "e": 25040, "s": 24851, "text": "Manhattan distance is a distance metric between two points in an N-dimensional vector space. It is defined as the sum of absolute distance between coordinates in corresponding dimensions. " }, { "code": null, "e": 25189, "s": 25040, "text": "For example, In a 2-dimensional space having two points Point1 (x1,y1) and Point2 (x2,y2), the Manhattan distance is given by |x1 – x2| + |y1 – y2|." }, { "code": null, "e": 25314, "s": 25189, "text": "In R Manhattan distance is calculated with respect to vectors. The Manhattan distance between the two vectors is given by, " }, { "code": null, "e": 25333, "s": 25314, "text": "Σ|vect1i - vect2i|" }, { "code": null, "e": 25340, "s": 25333, "text": "where," }, { "code": null, "e": 25366, "s": 25340, "text": "vect1 is the first vector" }, { "code": null, "e": 25393, "s": 25366, "text": "vect2 is the second vector" }, { "code": null, "e": 25581, "s": 25393, "text": "For example, we are given two vectors, vect1 as (3, 6, 8, 9) and vect2 as (1, 7, 8, 10). Their Manhattan distance is given by, |3 – 1| + |6 – 7| + |8 – 8| + |9 – 10| which is equal to 4." }, { "code": null, "e": 25644, "s": 25581, "text": "Below is the implementation using two vectors of equal length:" }, { "code": null, "e": 25655, "s": 25644, "text": "Example 1:" }, { "code": null, "e": 25657, "s": 25655, "text": "R" }, { "code": "# Function to calculate Manhattan distance# abs() function calculate the absolute difference# between corresponding vector elements# sum() function calculates the sum of the# absolute difference between# corresponding elements of vect1 and vect2manhattanDistance <- function(vect1, vect2){ dist <- abs(vect1 - vect2) dist <- sum(dist) return(dist)} # Initializing a vectorvect1 <- c(3, 6, 8, 9) # Initializing another vectorvect2 <- c(1, 7, 8, 10) print(\"Manhattan distance between vect1 and vect2 is: \") # Call the function to calculate Manhattan# distance between vectorsmanhattanDistance(vect1, vect2)", "e": 26275, "s": 25657, "text": null }, { "code": null, "e": 26283, "s": 26275, "text": "Output:" }, { "code": null, "e": 26343, "s": 26283, "text": "[1] \"Manhattan distance between vect1 and vect2 is: \"\n[1] 4" }, { "code": null, "e": 26354, "s": 26343, "text": "Example 2:" }, { "code": null, "e": 26506, "s": 26354, "text": "If the two vectors have unequal length then the compiler gives a warning message. Below is the implementation using two vectors having unequal lengths." }, { "code": null, "e": 26508, "s": 26506, "text": "R" }, { "code": "# Function to calculate Manhattan distance# abs() function calculate the absolute difference# between corresponding vector elements# sum() function calculates the sum of the# absolute difference between# corresponding elements of vect1 and vect2manhattanDistance <- function(vect1, vect2){ dist <- abs(vect1 - vect2) dist <- sum(dist) return(dist)} # Initializing two vectors having unequal lengthvect1 <- c(14, 13, 24, 18)vect2 <- c(13, 12, 33, 11, 12) print(\"Manhattan distance between vect1 and vect2 is: \") # Call the function to calculate Manhattan distancemanhattanDistance(vect1, vect2)", "e": 27114, "s": 26508, "text": null }, { "code": null, "e": 27122, "s": 27114, "text": "Output:" }, { "code": null, "e": 27263, "s": 27122, "text": "R provides an inbuilt function using which we can find the Manhattan distance between each unique pair of vectors in a 2-dimensional vector." }, { "code": null, "e": 27271, "s": 27263, "text": "Syntax:" }, { "code": null, "e": 27306, "s": 27271, "text": "dist(2dVect, method = “manhattan”)" }, { "code": null, "e": 27318, "s": 27306, "text": "Parameters:" }, { "code": null, "e": 27349, "s": 27318, "text": "2dVect: two-dimensional vector" }, { "code": null, "e": 27467, "s": 27349, "text": "method: the distance measure to be used. This can be one of “euclidean”, “maximum”, “manhattan”, “canberra”, “binary”" }, { "code": null, "e": 27480, "s": 27467, "text": "Return type:" }, { "code": null, "e": 27516, "s": 27480, "text": "It return an object of class “dist”" }, { "code": null, "e": 27527, "s": 27516, "text": "Example 1:" }, { "code": null, "e": 27605, "s": 27527, "text": "Below is the implementation to find Manhattan distance using dist() function:" }, { "code": null, "e": 27607, "s": 27605, "text": "R" }, { "code": "# Initializing a vectorvect1 < - c(1, 16, 8, 10, 100, 20) # Initializing another vectorvect2 < - c(1, 7, 18, 90, 50, 21) # Initializing another vectorvect3 < - c(3, 10, 11, 40, 150, 210) # Initializing another vectorvect4 < - c(2, 1, 4, 7, 8, 10) # Initializing another vectorvect5 < - c(1, 4, 8, 3, 100, 104) # Initializing another vectorvect6 < - c(3, 7, 11, 23, 110, 114) # Row bind vectors into a single matrixtwoDimensionalVect < - rbind(vect1, vect2, vect3, vect4, vect5, vect6) print(\"Manhattan distance between each pair of vectors is: \")cat(\"\\n\\n\") # Calculate Manhattan distance between vectors# using built in dist method# By passing two-dimensional vector as a parameter# Since we want to calculate manhattan distance between# each unique pair of vectors# That is why we are passing manhattan as a methoddist(twoDimensionalVect, method=\"manhattan\")", "e": 28471, "s": 27607, "text": null }, { "code": null, "e": 28479, "s": 28471, "text": "Output:" }, { "code": null, "e": 28490, "s": 28479, "text": "Example 2:" }, { "code": null, "e": 28656, "s": 28490, "text": "Note that the length of all the vectors presented under the 2-dimensional vector is required to be the same otherwise, the R compiler produces a compiler-time error." }, { "code": null, "e": 28658, "s": 28656, "text": "R" }, { "code": "# Initializing a vectorvect1 <- c(4, 3, 5, 7, 8, 2, 10, 12) # Initializing another vectorvect2 <- c(5, 9, 4, 9, 7, 17) # Initializing another vectorvect3 <- c(3, 10, 9, 11, 13, 12) # Initializing another vectorvect4 <- c(4, 7, 6, 12, 10, 12) # Initializing another vectorvect5 <- c(3, 5, 12, 10, 1, 17) # Initializing another vectorvect6 <- c(4, 3, 1, 8, 7, 2) # Using rind function to bind vectors in a 2-d vector# Note that all vectors are not of the same lengthtwoDimensionalVect <- rbind(vect1, vect2, vect3, vect4, vect5, vect6) print(\"Manhattan distance between each pair of vectors is: \")cat(\"\\n\\n\") # Calculate Manhattan distance between vectors# using built in dist method# By passing two-dimensional vector as a parameter# Since we want to calculate Manhattan distance# between each pair of vectors# That is why we are passing \"manhattan\" as a methoddist(twoDimensionalVect, method = \"manhattan\")", "e": 29569, "s": 28658, "text": null }, { "code": null, "e": 29577, "s": 29569, "text": "Output:" }, { "code": null, "e": 29589, "s": 29577, "text": "anikakapoor" }, { "code": null, "e": 29596, "s": 29589, "text": "Picked" }, { "code": null, "e": 29609, "s": 29596, "text": "R-Statistics" }, { "code": null, "e": 29620, "s": 29609, "text": "R Language" }, { "code": null, "e": 29718, "s": 29620, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29727, "s": 29718, "text": "Comments" }, { "code": null, "e": 29740, "s": 29727, "text": "Old Comments" }, { "code": null, "e": 29792, "s": 29740, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29830, "s": 29792, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29865, "s": 29830, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29923, "s": 29865, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29972, "s": 29923, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 30015, "s": 29972, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 30065, "s": 30015, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 30082, "s": 30065, "text": "R - if statement" }, { "code": null, "e": 30119, "s": 30082, "text": "How to import an Excel File into R ?" } ]
Java Examples - Interrupt a Thread
How to interrupt a running Thread? Following example demonstrates how to interrupt a running thread interrupt() method of thread and check if a thread is interrupted using isInterrupted() method. public class GeneralInterrupt extends Object implements Runnable { public void run() { try { System.out.println("in run() - about to work2()"); work2(); System.out.println("in run() - back from work2()"); } catch (InterruptedException x) { System.out.println("in run() - interrupted in work2()"); return; } System.out.println("in run() - doing stuff after nap"); System.out.println("in run() - leaving normally"); } public void work2() throws InterruptedException { while (true) { if (Thread.currentThread().isInterrupted()) { System.out.println("C isInterrupted()="+ Thread.currentThread().isInterrupted()); Thread.sleep(2000); System.out.println("D isInterrupted()="+ Thread.currentThread().isInterrupted()); } } } public void work() throws InterruptedException { while (true) { for (int i = 0; i < 100000; i++) { int j = i * 2; } System.out.println("A isInterrupted()="+ Thread.currentThread().isInterrupted()); if (Thread.interrupted()) { System.out.println("B isInterrupted()="+ Thread.currentThread().isInterrupted()); throw new InterruptedException(); } } } public static void main(String[] args) { GeneralInterrupt si = new GeneralInterrupt(); Thread t = new Thread(si); t.start(); try { Thread.sleep(2000); } catch (InterruptedException x) { } System.out.println("in main() - interrupting other thread"); t.interrupt(); System.out.println("in main() - leaving"); } } The above code sample will produce the following result. in run() - about to work2() in main() - interrupting other thread in main() - leaving C isInterrupted() = true in run() - interrupted in work2() Print Add Notes Bookmark this page
[ { "code": null, "e": 2103, "s": 2068, "text": "How to interrupt a running Thread?" }, { "code": null, "e": 2264, "s": 2103, "text": "Following example demonstrates how to interrupt a running thread interrupt() method of thread and check if a thread is interrupted using isInterrupted() method." }, { "code": null, "e": 3958, "s": 2264, "text": "public class GeneralInterrupt extends Object implements Runnable {\n public void run() {\n try {\n System.out.println(\"in run() - about to work2()\");\n work2();\n System.out.println(\"in run() - back from work2()\");\n } catch (InterruptedException x) {\n System.out.println(\"in run() - interrupted in work2()\");\n return;\n }\n System.out.println(\"in run() - doing stuff after nap\");\n System.out.println(\"in run() - leaving normally\");\n }\n public void work2() throws InterruptedException {\n while (true) {\n if (Thread.currentThread().isInterrupted()) {\n System.out.println(\"C isInterrupted()=\"+ Thread.currentThread().isInterrupted());\n Thread.sleep(2000);\n System.out.println(\"D isInterrupted()=\"+ Thread.currentThread().isInterrupted());\n }\n }\n }\n public void work() throws InterruptedException {\n while (true) {\n for (int i = 0; i < 100000; i++) {\n int j = i * 2;\n }\n System.out.println(\"A isInterrupted()=\"+ Thread.currentThread().isInterrupted());\n if (Thread.interrupted()) {\n System.out.println(\"B isInterrupted()=\"+ Thread.currentThread().isInterrupted());\n throw new InterruptedException();\n }\n }\n }\n public static void main(String[] args) {\n GeneralInterrupt si = new GeneralInterrupt();\n Thread t = new Thread(si);\n t.start();\n try {\n Thread.sleep(2000);\n } catch (InterruptedException x) { }\n\t\t\n System.out.println(\"in main() - interrupting other thread\");\n t.interrupt();\n System.out.println(\"in main() - leaving\");\n }\n}" }, { "code": null, "e": 4015, "s": 3958, "text": "The above code sample will produce the following result." }, { "code": null, "e": 4161, "s": 4015, "text": "in run() - about to work2()\nin main() - interrupting other thread\nin main() - leaving\nC isInterrupted() = true\nin run() - interrupted in work2()\n" }, { "code": null, "e": 4168, "s": 4161, "text": " Print" }, { "code": null, "e": 4179, "s": 4168, "text": " Add Notes" } ]
jQuery Get Content and Attributes
jQuery contains powerful methods for changing and manipulating HTML elements and attributes. One very important part of jQuery is the possibility to manipulate the DOM. jQuery comes with a bunch of DOM related methods that make it easy to access and manipulate elements and attributes. DOM = Document Object Model The DOM defines a standard for accessing HTML and XML documents: "The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document." Three simple, but useful, jQuery methods for DOM manipulation are: text() - Sets or returns the text content of selected elements html() - Sets or returns the content of selected elements (including HTML markup) val() - Sets or returns the value of form fields The following example demonstrates how to get content with the jQuery text() and html() methods: The following example demonstrates how to get the value of an input field with the jQuery val() method: The jQuery attr() method is used to get attribute values. The following example demonstrates how to get the value of the href attribute in a link: The next chapter explains how to set (change) content and attribute values. Use a jQuery method to return the text content of a <div> element. $("div").(); Start the Exercise For a complete overview of all jQuery HTML methods, please go to our jQuery HTML/CSS Reference. 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": 93, "s": 0, "text": "jQuery contains powerful methods for changing and manipulating HTML elements and attributes." }, { "code": null, "e": 169, "s": 93, "text": "One very important part of jQuery is the possibility to manipulate the DOM." }, { "code": null, "e": 287, "s": 169, "text": "jQuery comes with a bunch of DOM related methods that make it easy to \naccess and manipulate elements and attributes." }, { "code": null, "e": 580, "s": 287, "text": "DOM = Document Object Model\nThe DOM defines a standard for accessing HTML and XML documents:\n\"The W3C Document Object Model (DOM) is a platform and language-neutral \ninterface that allows programs and scripts to dynamically access and update the \ncontent, structure, and style of a document.\"" }, { "code": null, "e": 647, "s": 580, "text": "Three simple, but useful, jQuery methods for DOM manipulation are:" }, { "code": null, "e": 710, "s": 647, "text": "text() - Sets or returns the text content of selected elements" }, { "code": null, "e": 792, "s": 710, "text": "html() - Sets or returns the content of selected elements (including HTML markup)" }, { "code": null, "e": 841, "s": 792, "text": "val() - Sets or returns the value of form fields" }, { "code": null, "e": 938, "s": 841, "text": "The following example demonstrates how to get content with the jQuery text() and html() methods:" }, { "code": null, "e": 1042, "s": 938, "text": "The following example demonstrates how to get the value of an input field with the jQuery val() method:" }, { "code": null, "e": 1100, "s": 1042, "text": "The jQuery attr() method is used to get attribute values." }, { "code": null, "e": 1190, "s": 1100, "text": "The following example demonstrates how to get the value of the href attribute \nin a link:" }, { "code": null, "e": 1266, "s": 1190, "text": "The next chapter explains how to set (change) content and attribute values." }, { "code": null, "e": 1333, "s": 1266, "text": "Use a jQuery method to return the text content of a <div> element." }, { "code": null, "e": 1347, "s": 1333, "text": "$(\"div\").();\n" }, { "code": null, "e": 1366, "s": 1347, "text": "Start the Exercise" }, { "code": null, "e": 1462, "s": 1366, "text": "For a complete overview of all jQuery HTML methods, please go to our\njQuery HTML/CSS Reference." }, { "code": null, "e": 1495, "s": 1462, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1537, "s": 1495, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1644, "s": 1537, "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": 1663, "s": 1644, "text": "help@w3schools.com" } ]
Explainable Deep Neural Networks | by Javier Marin | Towards Data Science
Nature is an infinite sphere whose center is everywhere and whose circumference is nowhere. B. Pascal For some years, black box machine learning has been criticised for its limits in extracting knowledge from data. Deep Neural Networks (DNNs) are one of the most well-known of the ‘black box’ algorithms. Deep Neural Networks (DNNs) are the most widely used and successful image classification and processing technique today. But when it comes to structured data (the most common data problem) there is still a controversial about its advantage. Efforts have been made in recent years to produce explainable machine learning techniques, with the goal of providing a stronger descriptive approach to algorithms as well as additional information to users, hence enhancing data insights. In this work we propose a new way to make Deep Neural Networks more comprehensible when converting data encoded into practical knowledge. In each hidden layer representation, the data structure will be examined to gain a clear idea of how a deep neural network transforms data for classification purposes. The emerging subject of deep learning mathematical analysis [1] has been tasked with answering some “mysterious” facts that appear to be inexplicable using traditional mathematical methodologies. They are attempting to comprehend what a neural network actually does. Deep Neural Networks (DNN) transform data at each layer, producing a new representation as output. DNN attempts to divide data in a classification problem, enhancing this action layer by layer until it reaches an output layer when DNN provides its best possible result. Under the manifold hypothesis (natural data creates lower-dimensional manifolds in its embedding space), this task can be viewed as the separation of lower-dimensional manifolds in a data space. [2][3]. DNN layers are linked by a realization function, Φ (an affine transformation) and a component-wise activation function, ρ. Consider the fully connected feedforward neural network depicted in Figure 2. The network architecture can be described by defining the number of layers N, L, the number of neurons, and the activation function. The network parameters are the weights matrix W and the bias vectors b. Each layer’s output is a new way of describing inputs. This is why they are referred to as representations, as they are essentially abstractions over input data. For each layer, Φ(x , θ)= Wx+b, with parameters θ = (W , b). The weights matrix is W, while the bias vector is b. The activation function is crucial in determining how neural networks are connected and which information is transmitted from one layer to the next. Finally, it controls information exchange, allowing neural networks to “learn” from data. What they learn and why they learn it remains a difficult topic. Some researchers even argue that DNN can learn something particular about the data, and that this research is shared by several layers. So the argument that a layer learns something and then passes a representation to the next layer, which learns something else, is partially correct. Topology of data Visualizing high-dimensional data representations via dimensionality reduction is a well-known technique for examining deep learning models. In figure 3 we can see the layers representation for a network with an architecture, a= ((33, 500, 250, 50, 1), ρ). Aside from dimensionality reduction, there are alternative techniques for visualizing high-dimensional models. Topology analyzes the connection information of elements in a space and deals with qualitative geometric information. Topological data analysis (TDA) uses category theory, algebraic topology, and other pure mathematics methods to enable for a practical investigation of data form [4]. High-dimensional data sets significantly limit our ability to visualize them. This is why TDA can help us in improving our ability to visualize and analyze information. The most frequently observed data topologies include connected components, loops, voids, and so on. The curse of dimensionality is one of the most significant issues we face while evaluating high-dimensional data representations in deep neural nets. In high-dimensional space, points are highly sparse. When DNN transfers data from one layer to another with different dimension, euclidean distances between points, and the distance of a point to a subset grows. Topology studies only properties of geometric objects which do not depend on the chosen coordinates (are coordinates-free). For that reason, this tool is perfect to analyze deep nets representations. Topology avoids the quantitative values of the distance functions and replaces them with the notion of “infinite nearness” of a point to a subset in the underlying space [4]. Topology data analysis methods follows a basic routine: we come across a topological space (a representation of a high dimensional dataset ) and we need to find its fundamental group (data relations as links, loops or voids). But our data set is an unfamiliar space and it’s too difficult to look at explicit loops and relations. Then we look for another space that is homotopy equivalent to our [4], and whose fundamental group is much easier to compute. Since both spaces are homotopy equivalent, we know fundamental group in our space is isomorphic to fundamental group in the new space (gives the same data connectivity information). And its a coordinates-free process . Level-one connectivity information is related to data links, level-two connectivity information to data loops and level-three to voids (figure 4 shows level-one in green color and level-two in blue color. Topological data analysis provides both quantitive methods and tools for qualitative understanding of high-dimensionality data through direct visualization [4]. An example is Mapper algorithm (figure 5). Quantitative data analysis will find the fundamental group of representation, and qualitative data analysis will bring other qualitative insights about data. Topological signatures of a space are its fundamental groups. In TDA these signatures are the quantitative elements used to characterize the data space. To intuitively understand what is Data Topology, we invite you to read this wonderful post: The Mathematical Shape of Things to Come from Tang Yau Hoong, published in Quanta Magazine. As corollary we can say that Topological Data Analysis is about finding connections. What we propose in this post is that Topological Data Analysis in the DNN representations may help us to understand more about how deep nets works and what information we can get from each layer. To perform a DNN representation analysis we are going to use a dataset made publicly accessible by The Government of India as part of their Drug Discovery Hackathon. It’s also posted in Kaggle. It includes a list of drugs that have been tested and their effectiveness against Sars-CoV-2. Kaggle’s user Agrawal completed this list by adding some molecule’s chemical details obtained from PubChem library. The final dataset includes 100 checked molecules, each with 40 features. Among features we have pIC50 (will be our feature label). It is the negative logarithm of the half maximal inhibitory concentration (IC50). This index is used as a measure of the efficacy of a substance in inhibiting a specific biological or biochemical function. Higher the value, higher is the efficacy as inhibitor. Our goal is to find a classification method for this molecules according it’s effectiveness against Sars-CoV-2. The dataset also contains six blinded molecules, which do not show the pIC50 value and can be used for predictive tasks. We used the Giotto-tda library to perform TDA computations. Library gtda is a high-performance topological machine learning toolbox written in Python.The real advantage of using gtda, in my opinion, is its direct integration with scikit-learn and support for tabular data, time series, graphs, or pictures.Both assets make it simple to construct machine learning pipelines. For Deep Neural Networks we are using Keras library. In our experiment we have used a fully connected neural network with architecture, a = ((33, 500, 250, 50, 1), ρ). It is a basic graph with three hidden layers. We have built the network with Keras functional API in order to make the different experiments more reproducible. The functional API can handle models with non-linear topology. # clean is the pandas data frame with the data, # and 'pIC50' is the label feature.input_dim = len(clean.drop(columns='pIC50').columns) model = Sequential()#The Dense function in Keras constructs a fully connected neural network layer, automatically initializing the weights as biases.#First hidden layermodel.add(Dense(50, activation='relu', kernel_initializer='random_normal', kernel_regularizer=regularizers.l2(0.05), input_dim=input_dim))#Second hidden layermodel.add(Dense(40, activation='relu', kernel_initializer='random_normal', kernel_regularizer=regularizers.l2(0.05) ))#Third hidden layermodel.add(Dense(20, activation='relu', kernel_initializer='random_normal', kernel_regularizer=regularizers.l2(0.05) ))#Output layermodel.add(Dense(1, activation='sigmoid', kernel_initializer='random_normal', kernel_regularizer=regularizers.l2(0.05) ))model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) As mentioned earlier, activation functions are critical in mapping data from one layer to another. There are two kinds of activation functions that we’re interested in: invertible (continuous functions with continuous inverses) and not invertible. tanh , sigmoid or softplus, are examples of first-class functions, and ReLU is an example of a non-invertible function. Activation functions can be invertible, but a neural network as a whole, even with invertible activation functions, is not invertible in general. At this point, it’s worth recapping. We want to look into representation’s topology in a deep neural net. The key question will therefore be whether topological signatures preserve from one representation to the next. The answer can be found in category theory: A construction that converts objects (for example, de DNN representations) from one category to objects from another is functorial if it can be extended to a mapping on morphisms while preserving composites and identity morphisms [5]. Such constructions define morphisms between categories, called functors. Such constructions define morphisms between categories, called functors ( functor, F : C → D between categories C and D ). As a result, the task is limited to determining if data mapping from one layer to another is a functor. A functor may describe an equivalence of categories, in which case the objects in one category can be translated into and reconstructed from the objects of another. To check functionality in a DNN first, we analyze the accuracy and loss of our DNN architecture (figure 6). Training accuracy is 0.916 and training accuracy is 0.709. Remember we have a small dataset so accuracy is affected. Now we calculate the topological signatures of every representation(it is, finding fundamental groups in for each layer representation). We do this with gtda library, using Vietori-Rips filtration [4]. Results can be seen in figure 7. To understand this figure, we could say the following: orange points are connected points, it is points that are “close” in the topological space. The green points represent “loops” of points in the space. Green points close to the diagonal are noise (we could say loops not completely formed). Orange points represents also the “size” of the set. This point is a quantitive way to characterize the space. They are called topological signatures. We can see in figure 7 that topological signatures from the input layer to the third hidden layer are kept. We see 4 remarkable loops and several connected points. There is an orange point in the vertical line away from the rest. Remember we have to do a binary classification, so in the vertical line of orange points we have to see two distant “clusters” of points (one for each category), otherwise the set is not classifiable. This is clear in the output layer where we can see a point remarkably away from the rest of points, meaning that there are two categories and that one of them is much smaller than the other (one has only one point and the other one has more than 10 points). That’s it¡ DNN has separated the connected points until she got a clear separation, a maximum “distance” or minimum “nearness” between points. It has binary classified the dataset¡ So, the topological signatures seems to be the same but in the output function where we have asked the DNN to manipulate this to make a classification. So the transformation between representations is functorial: composites and identity morphisms are preserved. We have repeated the experiment varying several hyper-parameters. The most interesting conclusion is that functoriality seems more dependent on network width that on activation function invertibility. We have experimented with a network architecture a = ((33, 50, 25, 10, 1), ρ). Accuracy and Loss are very similar to the wider architecture (figure 8). Then we performed the same Vietory-Rips filtration (figure 9). We see that topological signatures are quite different from the original data set. In the first hidden layer we see less loops that completely disappear in the second hidden layer (we found basically noise). From the second layer, topological signatures are not mapped. The neural network but is capable to separate the connected points as it did with a wider architecture. It could seem a little counterintuitive because means that DNN does not need to consider topological signatures to perform an accurate separation. But it is possible in relative simple operations. DNN ‘forces’ data topology by manipulating distances of points in a way that identity morphisms are not preserved. Another topic is that it may be necessary to consider the equivalence of categories during the ‘learning’ process. When we consider small datasets, despite we are getting relative high accuracy levels, we should try to do it better. Topological data analysis gives us tools to double test network performance in the learning process. We have seen a quantitative topological approach. But topology offers qualitative understanding tools that can be very interesting. Mapper algorithm introduced in figure 5 is a very interesting ‘visualization’ algorithm that can enhance the performance of dimensionality reduction algorithms. Mapper algorithm can be naturally seen as a clustering algorithm with a conversion to a graph with directed edges. In figure 10 we can see the results of applying mapper algorithm to layer’s representation in the network with architecture a = ((33, 500, 250, 50, 1), ρ) -wide layer - . The nodes are colored with a scale of ‘pIC50' values (our label feature). Despite we have been performing binary classification ( 0 for negative pIC50 values and 1 for positive), we are interested now in a regression point of view to get beer insights. We have implemented mapper algorithm with gtda library. Mapper’s difficulty in choosing hyperparameters filter, cover and cluster data. """ 1. Define filter function – can be any scikit-learn transformer. It is returning a selection of columns of the data """filter_func = Eccentricity(metric= 'euclidean')""" 2. Define cover """cover = CubicalCover(n_intervals=20, overlap_frac=0.5)""" 3. Choose clustering algorithm – default is DBSCAN """clusterer = DBSCAN(eps=8, min_samples=2, metric='euclidean')""" 4. Initialise pipeline """pipe_mapper = make_mapper_pipeline(filter_func=filter_func, cover=cover, clusterer=clusterer, verbose=False, n_jobs=-1)""" 5. Plot mapper """plotly_params = {"node_trace": {"marker_colorscale": "RdBu"}}fig = plot_static_mapper_graph(pipe_mapper, X, layout='fruchterman_reingold', color_variable =clean['pIC50'], node_scale = 20, plotly_params=plotly_params)fig.show(config={'scrollZoom': True}) We see in figure 10 the mapper algorithm applied for input, hidden and output layers. Mapper in the input layer shows some “loops”, several connected component of different length, and some not-connected components (isolated nodes). We can also see loops in hidden layer 1, but not in the following layers. In the input layer we see blue points (positive value of pIC50) and red points (negative values of pIC50) totally mixed. With this graph plot, we can’t imagine an easy way to separate blue points from red points. But output layer shows what deep neural network have worked this separation: nodes with blue color and red color are very easy to divide because blue color are in the end of the connected component. We could easily cut the connection and we will have a binary classification. We can see we needed three hidden layer to perform this separation. If we look at the third layer, this separation is still not possible so another transformation have been necessary (output layer). DNN solves the classification problem by connecting as many points as possible. Apart from what we could called the main connected branch, the output layer has only one isolated node and a two-node connected component. Points are more connected than in the previous layers. Another interesting feature from mapper algorithm is that you can visualize every node, extract the data points and translate insights directly from the original data set (figure 11). We see mapper algorithm with the nodes translated to data points, specifically to a feature that is related to molecule drawing. Last but not least we can visualize the graph for every feature in the input data set and for every neuron inside the hidden layers. This feature from mapper can be useful for example to monitor how each molecule is placed in the graph in every layer. There are some works that demonstrate how neural nets transform image data through deep layers in image classification problems. However, there aren’t many examples for structured data classification applications. We’ve seen how Topology Data Analysis can be a great tool for extracting information from hidden layers, allowing us to see the steps a DNN takes to complete its task. We can improve DNN performance by understanding this process, just as we can with image recognition difficulties, giving also additional insights into the data. We have seen DNN can get the same accuracy with or with or without preserving data identities. This result have been tested in small data sets. Maybe preserving topological signatures can be another metric to check DNN’s accuracy in learning from data. You can find the code used in this article here. [1] Berner, J., Grohs, P., Kutyniok, G., & Petersen, P. (2021). The Modern Mathematics of Deep Learning. ArXiv, abs/2105.04026. [2] C. Olah (2014). Neural Networks, Manifolds, and Topology. C. Olah blog. [3] C. Fefferman, S. Mitter, & H. Narayanan (2016).Testing the manifold hypothesis. Journal of the Amer. Math. Soc. 29, 4, 983–1049. [4] G. Carlsson. (2009) Topology and data. Bull. Amer. Math. Soc. 46 , 255–308. [5] E. Riehl. (2017) Category theory in context. Courier Dover Publications.
[ { "code": null, "e": 264, "s": 172, "text": "Nature is an infinite sphere whose center is everywhere and whose circumference is nowhere." }, { "code": null, "e": 274, "s": 264, "text": "B. Pascal" }, { "code": null, "e": 957, "s": 274, "text": "For some years, black box machine learning has been criticised for its limits in extracting knowledge from data. Deep Neural Networks (DNNs) are one of the most well-known of the ‘black box’ algorithms. Deep Neural Networks (DNNs) are the most widely used and successful image classification and processing technique today. But when it comes to structured data (the most common data problem) there is still a controversial about its advantage. Efforts have been made in recent years to produce explainable machine learning techniques, with the goal of providing a stronger descriptive approach to algorithms as well as additional information to users, hence enhancing data insights." }, { "code": null, "e": 1263, "s": 957, "text": "In this work we propose a new way to make Deep Neural Networks more comprehensible when converting data encoded into practical knowledge. In each hidden layer representation, the data structure will be examined to gain a clear idea of how a deep neural network transforms data for classification purposes." }, { "code": null, "e": 2003, "s": 1263, "text": "The emerging subject of deep learning mathematical analysis [1] has been tasked with answering some “mysterious” facts that appear to be inexplicable using traditional mathematical methodologies. They are attempting to comprehend what a neural network actually does. Deep Neural Networks (DNN) transform data at each layer, producing a new representation as output. DNN attempts to divide data in a classification problem, enhancing this action layer by layer until it reaches an output layer when DNN provides its best possible result. Under the manifold hypothesis (natural data creates lower-dimensional manifolds in its embedding space), this task can be viewed as the separation of lower-dimensional manifolds in a data space. [2][3]." }, { "code": null, "e": 2685, "s": 2003, "text": "DNN layers are linked by a realization function, Φ (an affine transformation) and a component-wise activation function, ρ. Consider the fully connected feedforward neural network depicted in Figure 2. The network architecture can be described by defining the number of layers N, L, the number of neurons, and the activation function. The network parameters are the weights matrix W and the bias vectors b. Each layer’s output is a new way of describing inputs. This is why they are referred to as representations, as they are essentially abstractions over input data. For each layer, Φ(x , θ)= Wx+b, with parameters θ = (W , b). The weights matrix is W, while the bias vector is b." }, { "code": null, "e": 3291, "s": 2685, "text": "The activation function is crucial in determining how neural networks are connected and which information is transmitted from one layer to the next. Finally, it controls information exchange, allowing neural networks to “learn” from data. What they learn and why they learn it remains a difficult topic. Some researchers even argue that DNN can learn something particular about the data, and that this research is shared by several layers. So the argument that a layer learns something and then passes a representation to the next layer, which learns something else, is partially correct. Topology of data" }, { "code": null, "e": 3548, "s": 3291, "text": "Visualizing high-dimensional data representations via dimensionality reduction is a well-known technique for examining deep learning models. In figure 3 we can see the layers representation for a network with an architecture, a= ((33, 500, 250, 50, 1), ρ)." }, { "code": null, "e": 4213, "s": 3548, "text": "Aside from dimensionality reduction, there are alternative techniques for visualizing high-dimensional models. Topology analyzes the connection information of elements in a space and deals with qualitative geometric information. Topological data analysis (TDA) uses category theory, algebraic topology, and other pure mathematics methods to enable for a practical investigation of data form [4]. High-dimensional data sets significantly limit our ability to visualize them. This is why TDA can help us in improving our ability to visualize and analyze information. The most frequently observed data topologies include connected components, loops, voids, and so on." }, { "code": null, "e": 4775, "s": 4213, "text": "The curse of dimensionality is one of the most significant issues we face while evaluating high-dimensional data representations in deep neural nets. In high-dimensional space, points are highly sparse. When DNN transfers data from one layer to another with different dimension, euclidean distances between points, and the distance of a point to a subset grows. Topology studies only properties of geometric objects which do not depend on the chosen coordinates (are coordinates-free). For that reason, this tool is perfect to analyze deep nets representations." }, { "code": null, "e": 4950, "s": 4775, "text": "Topology avoids the quantitative values of the distance functions and replaces them with the notion of “infinite nearness” of a point to a subset in the underlying space [4]." }, { "code": null, "e": 5830, "s": 4950, "text": "Topology data analysis methods follows a basic routine: we come across a topological space (a representation of a high dimensional dataset ) and we need to find its fundamental group (data relations as links, loops or voids). But our data set is an unfamiliar space and it’s too difficult to look at explicit loops and relations. Then we look for another space that is homotopy equivalent to our [4], and whose fundamental group is much easier to compute. Since both spaces are homotopy equivalent, we know fundamental group in our space is isomorphic to fundamental group in the new space (gives the same data connectivity information). And its a coordinates-free process . Level-one connectivity information is related to data links, level-two connectivity information to data loops and level-three to voids (figure 4 shows level-one in green color and level-two in blue color." }, { "code": null, "e": 6192, "s": 5830, "text": "Topological data analysis provides both quantitive methods and tools for qualitative understanding of high-dimensionality data through direct visualization [4]. An example is Mapper algorithm (figure 5). Quantitative data analysis will find the fundamental group of representation, and qualitative data analysis will bring other qualitative insights about data." }, { "code": null, "e": 6345, "s": 6192, "text": "Topological signatures of a space are its fundamental groups. In TDA these signatures are the quantitative elements used to characterize the data space." }, { "code": null, "e": 6529, "s": 6345, "text": "To intuitively understand what is Data Topology, we invite you to read this wonderful post: The Mathematical Shape of Things to Come from Tang Yau Hoong, published in Quanta Magazine." }, { "code": null, "e": 6614, "s": 6529, "text": "As corollary we can say that Topological Data Analysis is about finding connections." }, { "code": null, "e": 7839, "s": 6614, "text": "What we propose in this post is that Topological Data Analysis in the DNN representations may help us to understand more about how deep nets works and what information we can get from each layer. To perform a DNN representation analysis we are going to use a dataset made publicly accessible by The Government of India as part of their Drug Discovery Hackathon. It’s also posted in Kaggle. It includes a list of drugs that have been tested and their effectiveness against Sars-CoV-2. Kaggle’s user Agrawal completed this list by adding some molecule’s chemical details obtained from PubChem library. The final dataset includes 100 checked molecules, each with 40 features. Among features we have pIC50 (will be our feature label). It is the negative logarithm of the half maximal inhibitory concentration (IC50). This index is used as a measure of the efficacy of a substance in inhibiting a specific biological or biochemical function. Higher the value, higher is the efficacy as inhibitor. Our goal is to find a classification method for this molecules according it’s effectiveness against Sars-CoV-2. The dataset also contains six blinded molecules, which do not show the pIC50 value and can be used for predictive tasks." }, { "code": null, "e": 8266, "s": 7839, "text": "We used the Giotto-tda library to perform TDA computations. Library gtda is a high-performance topological machine learning toolbox written in Python.The real advantage of using gtda, in my opinion, is its direct integration with scikit-learn and support for tabular data, time series, graphs, or pictures.Both assets make it simple to construct machine learning pipelines. For Deep Neural Networks we are using Keras library." }, { "code": null, "e": 8604, "s": 8266, "text": "In our experiment we have used a fully connected neural network with architecture, a = ((33, 500, 250, 50, 1), ρ). It is a basic graph with three hidden layers. We have built the network with Keras functional API in order to make the different experiments more reproducible. The functional API can handle models with non-linear topology." }, { "code": null, "e": 9675, "s": 8604, "text": "# clean is the pandas data frame with the data, # and 'pIC50' is the label feature.input_dim = len(clean.drop(columns='pIC50').columns) model = Sequential()#The Dense function in Keras constructs a fully connected neural network layer, automatically initializing the weights as biases.#First hidden layermodel.add(Dense(50, activation='relu', kernel_initializer='random_normal', kernel_regularizer=regularizers.l2(0.05), input_dim=input_dim))#Second hidden layermodel.add(Dense(40, activation='relu', kernel_initializer='random_normal', kernel_regularizer=regularizers.l2(0.05) ))#Third hidden layermodel.add(Dense(20, activation='relu', kernel_initializer='random_normal', kernel_regularizer=regularizers.l2(0.05) ))#Output layermodel.add(Dense(1, activation='sigmoid', kernel_initializer='random_normal', kernel_regularizer=regularizers.l2(0.05) ))model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])" }, { "code": null, "e": 10189, "s": 9675, "text": "As mentioned earlier, activation functions are critical in mapping data from one layer to another. There are two kinds of activation functions that we’re interested in: invertible (continuous functions with continuous inverses) and not invertible. tanh , sigmoid or softplus, are examples of first-class functions, and ReLU is an example of a non-invertible function. Activation functions can be invertible, but a neural network as a whole, even with invertible activation functions, is not invertible in general." }, { "code": null, "e": 11151, "s": 10189, "text": "At this point, it’s worth recapping. We want to look into representation’s topology in a deep neural net. The key question will therefore be whether topological signatures preserve from one representation to the next. The answer can be found in category theory: A construction that converts objects (for example, de DNN representations) from one category to objects from another is functorial if it can be extended to a mapping on morphisms while preserving composites and identity morphisms [5]. Such constructions define morphisms between categories, called functors. Such constructions define morphisms between categories, called functors ( functor, F : C → D between categories C and D ). As a result, the task is limited to determining if data mapping from one layer to another is a functor. A functor may describe an equivalence of categories, in which case the objects in one category can be translated into and reconstructed from the objects of another." }, { "code": null, "e": 11259, "s": 11151, "text": "To check functionality in a DNN first, we analyze the accuracy and loss of our DNN architecture (figure 6)." }, { "code": null, "e": 11611, "s": 11259, "text": "Training accuracy is 0.916 and training accuracy is 0.709. Remember we have a small dataset so accuracy is affected. Now we calculate the topological signatures of every representation(it is, finding fundamental groups in for each layer representation). We do this with gtda library, using Vietori-Rips filtration [4]. Results can be seen in figure 7." }, { "code": null, "e": 12488, "s": 11611, "text": "To understand this figure, we could say the following: orange points are connected points, it is points that are “close” in the topological space. The green points represent “loops” of points in the space. Green points close to the diagonal are noise (we could say loops not completely formed). Orange points represents also the “size” of the set. This point is a quantitive way to characterize the space. They are called topological signatures. We can see in figure 7 that topological signatures from the input layer to the third hidden layer are kept. We see 4 remarkable loops and several connected points. There is an orange point in the vertical line away from the rest. Remember we have to do a binary classification, so in the vertical line of orange points we have to see two distant “clusters” of points (one for each category), otherwise the set is not classifiable." }, { "code": null, "e": 13189, "s": 12488, "text": "This is clear in the output layer where we can see a point remarkably away from the rest of points, meaning that there are two categories and that one of them is much smaller than the other (one has only one point and the other one has more than 10 points). That’s it¡ DNN has separated the connected points until she got a clear separation, a maximum “distance” or minimum “nearness” between points. It has binary classified the dataset¡ So, the topological signatures seems to be the same but in the output function where we have asked the DNN to manipulate this to make a classification. So the transformation between representations is functorial: composites and identity morphisms are preserved." }, { "code": null, "e": 13390, "s": 13189, "text": "We have repeated the experiment varying several hyper-parameters. The most interesting conclusion is that functoriality seems more dependent on network width that on activation function invertibility." }, { "code": null, "e": 13875, "s": 13390, "text": "We have experimented with a network architecture a = ((33, 50, 25, 10, 1), ρ). Accuracy and Loss are very similar to the wider architecture (figure 8). Then we performed the same Vietory-Rips filtration (figure 9). We see that topological signatures are quite different from the original data set. In the first hidden layer we see less loops that completely disappear in the second hidden layer (we found basically noise). From the second layer, topological signatures are not mapped." }, { "code": null, "e": 14291, "s": 13875, "text": "The neural network but is capable to separate the connected points as it did with a wider architecture. It could seem a little counterintuitive because means that DNN does not need to consider topological signatures to perform an accurate separation. But it is possible in relative simple operations. DNN ‘forces’ data topology by manipulating distances of points in a way that identity morphisms are not preserved." }, { "code": null, "e": 14625, "s": 14291, "text": "Another topic is that it may be necessary to consider the equivalence of categories during the ‘learning’ process. When we consider small datasets, despite we are getting relative high accuracy levels, we should try to do it better. Topological data analysis gives us tools to double test network performance in the learning process." }, { "code": null, "e": 15593, "s": 14625, "text": "We have seen a quantitative topological approach. But topology offers qualitative understanding tools that can be very interesting. Mapper algorithm introduced in figure 5 is a very interesting ‘visualization’ algorithm that can enhance the performance of dimensionality reduction algorithms. Mapper algorithm can be naturally seen as a clustering algorithm with a conversion to a graph with directed edges. In figure 10 we can see the results of applying mapper algorithm to layer’s representation in the network with architecture a = ((33, 500, 250, 50, 1), ρ) -wide layer - . The nodes are colored with a scale of ‘pIC50' values (our label feature). Despite we have been performing binary classification ( 0 for negative pIC50 values and 1 for positive), we are interested now in a regression point of view to get beer insights. We have implemented mapper algorithm with gtda library. Mapper’s difficulty in choosing hyperparameters filter, cover and cluster data." }, { "code": null, "e": 16709, "s": 15593, "text": "\"\"\" 1. Define filter function – can be any scikit-learn transformer. It is returning a selection of columns of the data \"\"\"filter_func = Eccentricity(metric= 'euclidean')\"\"\" 2. Define cover \"\"\"cover = CubicalCover(n_intervals=20, overlap_frac=0.5)\"\"\" 3. Choose clustering algorithm – default is DBSCAN \"\"\"clusterer = DBSCAN(eps=8, min_samples=2, metric='euclidean')\"\"\" 4. Initialise pipeline \"\"\"pipe_mapper = make_mapper_pipeline(filter_func=filter_func, cover=cover, clusterer=clusterer, verbose=False, n_jobs=-1)\"\"\" 5. Plot mapper \"\"\"plotly_params = {\"node_trace\": {\"marker_colorscale\": \"RdBu\"}}fig = plot_static_mapper_graph(pipe_mapper, X, layout='fruchterman_reingold', color_variable =clean['pIC50'], node_scale = 20, plotly_params=plotly_params)fig.show(config={'scrollZoom': True})" }, { "code": null, "e": 17704, "s": 16709, "text": "We see in figure 10 the mapper algorithm applied for input, hidden and output layers. Mapper in the input layer shows some “loops”, several connected component of different length, and some not-connected components (isolated nodes). We can also see loops in hidden layer 1, but not in the following layers. In the input layer we see blue points (positive value of pIC50) and red points (negative values of pIC50) totally mixed. With this graph plot, we can’t imagine an easy way to separate blue points from red points. But output layer shows what deep neural network have worked this separation: nodes with blue color and red color are very easy to divide because blue color are in the end of the connected component. We could easily cut the connection and we will have a binary classification. We can see we needed three hidden layer to perform this separation. If we look at the third layer, this separation is still not possible so another transformation have been necessary (output layer)." }, { "code": null, "e": 17978, "s": 17704, "text": "DNN solves the classification problem by connecting as many points as possible. Apart from what we could called the main connected branch, the output layer has only one isolated node and a two-node connected component. Points are more connected than in the previous layers." }, { "code": null, "e": 18424, "s": 17978, "text": "Another interesting feature from mapper algorithm is that you can visualize every node, extract the data points and translate insights directly from the original data set (figure 11). We see mapper algorithm with the nodes translated to data points, specifically to a feature that is related to molecule drawing. Last but not least we can visualize the graph for every feature in the input data set and for every neuron inside the hidden layers." }, { "code": null, "e": 18543, "s": 18424, "text": "This feature from mapper can be useful for example to monitor how each molecule is placed in the graph in every layer." }, { "code": null, "e": 19086, "s": 18543, "text": "There are some works that demonstrate how neural nets transform image data through deep layers in image classification problems. However, there aren’t many examples for structured data classification applications. We’ve seen how Topology Data Analysis can be a great tool for extracting information from hidden layers, allowing us to see the steps a DNN takes to complete its task. We can improve DNN performance by understanding this process, just as we can with image recognition difficulties, giving also additional insights into the data." }, { "code": null, "e": 19339, "s": 19086, "text": "We have seen DNN can get the same accuracy with or with or without preserving data identities. This result have been tested in small data sets. Maybe preserving topological signatures can be another metric to check DNN’s accuracy in learning from data." }, { "code": null, "e": 19388, "s": 19339, "text": "You can find the code used in this article here." }, { "code": null, "e": 19516, "s": 19388, "text": "[1] Berner, J., Grohs, P., Kutyniok, G., & Petersen, P. (2021). The Modern Mathematics of Deep Learning. ArXiv, abs/2105.04026." }, { "code": null, "e": 19592, "s": 19516, "text": "[2] C. Olah (2014). Neural Networks, Manifolds, and Topology. C. Olah blog." }, { "code": null, "e": 19725, "s": 19592, "text": "[3] C. Fefferman, S. Mitter, & H. Narayanan (2016).Testing the manifold hypothesis. Journal of the Amer. Math. Soc. 29, 4, 983–1049." }, { "code": null, "e": 19805, "s": 19725, "text": "[4] G. Carlsson. (2009) Topology and data. Bull. Amer. Math. Soc. 46 , 255–308." } ]
RecyclerView using GridLayoutManager in Android With Example - GeeksforGeeks
06 Sep, 2021 RecyclerView is the improvised version of a ListView in Android. It was first introduced in Marshmallow. Recycler view in Android is the class that extends ViewGroup and implements Scrolling Interface. It can be used either in the form of ListView or in the form of Grid View. While implementing Recycler view in Android we generally have to set layout manager to display our Recycler View. There are two types of layout managers for Recycler View to implement. Linear Layout Manager: In linear layout manager, we can align our recycler view in a horizontal or vertical scrolling manner by specifying its orientation as vertical or horizontal. Grid Layout Manager: In Grid Layout manager we can align our recycler in the form of a grid. Here we have to mention the number of columns that are to be displayed in the Grid of Recycler View. Linear Layout Manager: In linear layout manager, we can align our recycler view in a horizontal or vertical scrolling manner by specifying its orientation as vertical or horizontal. Grid Layout Manager: In Grid Layout manager we can align our recycler in the form of a grid. Here we have to mention the number of columns that are to be displayed in the Grid of Recycler View. 1. View Holder Implementation In GridView it was not mandatory to use View holder implementation but in RecyclerView it is mandatory to use View Holder implementation for Recycler View. It makes the code complex but many difficulties that are faced in GridView are solved in RecyclerView. 2. Performance of Recycler View RecyclerView is an improvised version of ListView. The performance of Recycler View has been improvised. In RecyclerView the items are ahead and behind the visible entries. A sample image is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Create a New Project in Android Studio To create a new project in Android Project just refer to this article on How to Create new Project in Android Studio and make sure that the language is Java. To implement Recycler View three sub-parts are needed which are helpful to control RecyclerView. These three subparts include: Card Layout: The card layout is an XML file that will represent each individual grid item inside your Recycler view. View Holder: View Holder Class is the java class that stores the reference to the UI Elements in the Card Layout and they can be modified dynamically during the execution of the program by the list of data. Data Class: Data Class is an object class that holds information to be displayed in each recycler view item that is to be displayed in Recycler View. Step 2: Add google repository in the build.gradle file of the application project. buildscript { repositories { google() mavenCentral() } All Jetpack components are available in the Google Maven repository, include them in the build.gradle file allprojects { repositories { google() mavenCentral() } } Step 3: Create a Card Layout for Recycler View Card Items Go to the app > res > layout> right-click > New >Layout Resource File and name the file as card_layout. In this file, all XML code related to card items in the RecyclerView is written. Below is the code for the card_layout.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="120dp" android:layout_gravity="center" android:layout_margin="5dp" app:cardCornerRadius="5dp" app:cardElevation="5dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <ImageView android:id="@+id/idIVcourseIV" android:layout_width="100dp" android:layout_height="100dp" android:layout_gravity="center" android:contentDescription="@string/image" android:src="@mipmap/ic_launcher" /> <TextView android:id="@+id/idTVCourse" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/app_name" android:textAlignment="center" /> </LinearLayout> </androidx.cardview.widget.CardView> Step 4: Create a Java class for Modal Data Go to the app > java > Right-Click on your app’s package name > New > Java Class and name the file as RecyclerData. This class will handles data for each Recycler item that is to be displayed. Below is the code for the RecyclerData.java file. Java public class RecyclerData { private String title; private int imgid; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getImgid() { return imgid; } public void setImgid(int imgid) { this.imgid = imgid; } public RecyclerData(String title, int imgid) { this.title = title; this.imgid = imgid; }} Step 5: Create a new java class for the Adapter Similarly, create a new Java Class and name the file as RecyclerViewAdapter. The adapter is the main class that is responsible for RecyclerView. It holds all methods which are useful in RecyclerView. Note: View Holder Class is also implemented in Adapter Class itself. These methods to handle Recycler View includes: onCreateViewHolder: This method inflates card layout items for Recycler View. onBindViewHolder: This method sets the data to specific views of card items. It also handles methods related to clicks on items of Recycler view. getItemCount: This method returns the length of the RecyclerView. Below is the code for the RecyclerViewAdapter.java file. Comments are added inside the code to understand the code in more detail. Java import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView;import java.util.ArrayList; public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolder> { private ArrayList<RecyclerData> courseDataArrayList; private Context mcontext; public RecyclerViewAdapter(ArrayList<RecyclerData> recyclerDataArrayList, Context mcontext) { this.courseDataArrayList = recyclerDataArrayList; this.mcontext = mcontext; } @NonNull @Override public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // Inflate Layout View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout, parent, false); return new RecyclerViewHolder(view); } @Override public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) { // Set the data to textview and imageview. RecyclerData recyclerData = courseDataArrayList.get(position); holder.courseTV.setText(recyclerData.getTitle()); holder.courseIV.setImageResource(recyclerData.getImgid()); } @Override public int getItemCount() { // this method returns the size of recyclerview return courseDataArrayList.size(); } // View Holder Class to handle Recycler View. public class RecyclerViewHolder extends RecyclerView.ViewHolder { private TextView courseTV; private ImageView courseIV; public RecyclerViewHolder(@NonNull View itemView) { super(itemView); courseTV = itemView.findViewById(R.id.idTVCourse); courseIV = itemView.findViewById(R.id.idIVcourseIV); } }} Step 6: Working with the activity_main.xml file This is the main screen that displays all data in the form of a grid. Here we have to implement Recycler View. Below is the code snippet of the XML layout in the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><!--XMl Layout for RecyclerView--><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/idCourseRV" android:layout_width="match_parent" android:layout_height="match_parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 7: Working with the MainActivity.java file This is the main java file where we will set LayoutManager, adapter, and set data to RecyclerView which is to be displayed in RecyclerView. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.GridLayoutManager;import androidx.recyclerview.widget.RecyclerView;import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private RecyclerView recyclerView; private ArrayList<RecyclerData> recyclerDataArrayList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView=findViewById(R.id.idCourseRV); // created new array list.. recyclerDataArrayList=new ArrayList<>(); // added data to array list recyclerDataArrayList.add(new RecyclerData("DSA",R.drawable.ic_gfglogo)); recyclerDataArrayList.add(new RecyclerData("JAVA",R.drawable.ic_gfglogo)); recyclerDataArrayList.add(new RecyclerData("C++",R.drawable.ic_gfglogo)); recyclerDataArrayList.add(new RecyclerData("Python",R.drawable.ic_gfglogo)); recyclerDataArrayList.add(new RecyclerData("Node Js",R.drawable.ic_gfglogo)); // added data from arraylist to adapter class. RecyclerViewAdapter adapter=new RecyclerViewAdapter(recyclerDataArrayList,this); // setting grid layout manager to implement grid view. // in this method '2' represents number of columns to be displayed in grid view. GridLayoutManager layoutManager=new GridLayoutManager(this,2); // at last set adapter to recycler view. recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(adapter); }} Output: You can check out the project link mentioned below where you can get all code to implement RecyclerView with Grid Layout Manager. If you want to implement On Click Listener for Recycler Items in Grid Layout then check out this post for implementation of RecyclerView. Project Link: Click Here hemantjain99 android Picked Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Android RecyclerView in Kotlin Services in Android with Example CardView in Android With Example Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 24289, "s": 24261, "text": "\n06 Sep, 2021" }, { "code": null, "e": 24567, "s": 24289, "text": "RecyclerView is the improvised version of a ListView in Android. It was first introduced in Marshmallow. Recycler view in Android is the class that extends ViewGroup and implements Scrolling Interface. It can be used either in the form of ListView or in the form of Grid View. " }, { "code": null, "e": 24753, "s": 24567, "text": "While implementing Recycler view in Android we generally have to set layout manager to display our Recycler View. There are two types of layout managers for Recycler View to implement. " }, { "code": null, "e": 25129, "s": 24753, "text": "Linear Layout Manager: In linear layout manager, we can align our recycler view in a horizontal or vertical scrolling manner by specifying its orientation as vertical or horizontal. Grid Layout Manager: In Grid Layout manager we can align our recycler in the form of a grid. Here we have to mention the number of columns that are to be displayed in the Grid of Recycler View." }, { "code": null, "e": 25312, "s": 25129, "text": "Linear Layout Manager: In linear layout manager, we can align our recycler view in a horizontal or vertical scrolling manner by specifying its orientation as vertical or horizontal. " }, { "code": null, "e": 25506, "s": 25312, "text": "Grid Layout Manager: In Grid Layout manager we can align our recycler in the form of a grid. Here we have to mention the number of columns that are to be displayed in the Grid of Recycler View." }, { "code": null, "e": 25536, "s": 25506, "text": "1. View Holder Implementation" }, { "code": null, "e": 25796, "s": 25536, "text": "In GridView it was not mandatory to use View holder implementation but in RecyclerView it is mandatory to use View Holder implementation for Recycler View. It makes the code complex but many difficulties that are faced in GridView are solved in RecyclerView. " }, { "code": null, "e": 25828, "s": 25796, "text": "2. Performance of Recycler View" }, { "code": null, "e": 26002, "s": 25828, "text": "RecyclerView is an improvised version of ListView. The performance of Recycler View has been improvised. In RecyclerView the items are ahead and behind the visible entries. " }, { "code": null, "e": 26169, "s": 26002, "text": "A sample image is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 26216, "s": 26169, "text": "Step 1: Create a New Project in Android Studio" }, { "code": null, "e": 26502, "s": 26216, "text": "To create a new project in Android Project just refer to this article on How to Create new Project in Android Studio and make sure that the language is Java. To implement Recycler View three sub-parts are needed which are helpful to control RecyclerView. These three subparts include: " }, { "code": null, "e": 26619, "s": 26502, "text": "Card Layout: The card layout is an XML file that will represent each individual grid item inside your Recycler view." }, { "code": null, "e": 26826, "s": 26619, "text": "View Holder: View Holder Class is the java class that stores the reference to the UI Elements in the Card Layout and they can be modified dynamically during the execution of the program by the list of data." }, { "code": null, "e": 26976, "s": 26826, "text": "Data Class: Data Class is an object class that holds information to be displayed in each recycler view item that is to be displayed in Recycler View." }, { "code": null, "e": 27059, "s": 26976, "text": "Step 2: Add google repository in the build.gradle file of the application project." }, { "code": null, "e": 27073, "s": 27059, "text": "buildscript {" }, { "code": null, "e": 27089, "s": 27073, "text": " repositories {" }, { "code": null, "e": 27103, "s": 27089, "text": " google()" }, { "code": null, "e": 27123, "s": 27103, "text": " mavenCentral()" }, { "code": null, "e": 27125, "s": 27123, "text": "}" }, { "code": null, "e": 27232, "s": 27125, "text": "All Jetpack components are available in the Google Maven repository, include them in the build.gradle file" }, { "code": null, "e": 27246, "s": 27232, "text": "allprojects {" }, { "code": null, "e": 27262, "s": 27246, "text": " repositories {" }, { "code": null, "e": 27276, "s": 27262, "text": " google()" }, { "code": null, "e": 27295, "s": 27276, "text": " mavenCentral()" }, { "code": null, "e": 27298, "s": 27295, "text": " }" }, { "code": null, "e": 27300, "s": 27298, "text": "}" }, { "code": null, "e": 27358, "s": 27300, "text": "Step 3: Create a Card Layout for Recycler View Card Items" }, { "code": null, "e": 27591, "s": 27358, "text": "Go to the app > res > layout> right-click > New >Layout Resource File and name the file as card_layout. In this file, all XML code related to card items in the RecyclerView is written. Below is the code for the card_layout.xml file." }, { "code": null, "e": 27595, "s": 27591, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.cardview.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"120dp\" android:layout_gravity=\"center\" android:layout_margin=\"5dp\" app:cardCornerRadius=\"5dp\" app:cardElevation=\"5dp\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <ImageView android:id=\"@+id/idIVcourseIV\" android:layout_width=\"100dp\" android:layout_height=\"100dp\" android:layout_gravity=\"center\" android:contentDescription=\"@string/image\" android:src=\"@mipmap/ic_launcher\" /> <TextView android:id=\"@+id/idTVCourse\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"@string/app_name\" android:textAlignment=\"center\" /> </LinearLayout> </androidx.cardview.widget.CardView>", "e": 28710, "s": 27595, "text": null }, { "code": null, "e": 28753, "s": 28710, "text": "Step 4: Create a Java class for Modal Data" }, { "code": null, "e": 28996, "s": 28753, "text": "Go to the app > java > Right-Click on your app’s package name > New > Java Class and name the file as RecyclerData. This class will handles data for each Recycler item that is to be displayed. Below is the code for the RecyclerData.java file." }, { "code": null, "e": 29001, "s": 28996, "text": "Java" }, { "code": "public class RecyclerData { private String title; private int imgid; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getImgid() { return imgid; } public void setImgid(int imgid) { this.imgid = imgid; } public RecyclerData(String title, int imgid) { this.title = title; this.imgid = imgid; }}", "e": 29442, "s": 29001, "text": null }, { "code": null, "e": 29490, "s": 29442, "text": "Step 5: Create a new java class for the Adapter" }, { "code": null, "e": 29691, "s": 29490, "text": "Similarly, create a new Java Class and name the file as RecyclerViewAdapter. The adapter is the main class that is responsible for RecyclerView. It holds all methods which are useful in RecyclerView. " }, { "code": null, "e": 29761, "s": 29691, "text": "Note: View Holder Class is also implemented in Adapter Class itself. " }, { "code": null, "e": 29811, "s": 29761, "text": "These methods to handle Recycler View includes: " }, { "code": null, "e": 29889, "s": 29811, "text": "onCreateViewHolder: This method inflates card layout items for Recycler View." }, { "code": null, "e": 30035, "s": 29889, "text": "onBindViewHolder: This method sets the data to specific views of card items. It also handles methods related to clicks on items of Recycler view." }, { "code": null, "e": 30101, "s": 30035, "text": "getItemCount: This method returns the length of the RecyclerView." }, { "code": null, "e": 30233, "s": 30101, "text": "Below is the code for the RecyclerViewAdapter.java file. Comments are added inside the code to understand the code in more detail. " }, { "code": null, "e": 30238, "s": 30233, "text": "Java" }, { "code": "import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView;import java.util.ArrayList; public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolder> { private ArrayList<RecyclerData> courseDataArrayList; private Context mcontext; public RecyclerViewAdapter(ArrayList<RecyclerData> recyclerDataArrayList, Context mcontext) { this.courseDataArrayList = recyclerDataArrayList; this.mcontext = mcontext; } @NonNull @Override public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // Inflate Layout View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout, parent, false); return new RecyclerViewHolder(view); } @Override public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) { // Set the data to textview and imageview. RecyclerData recyclerData = courseDataArrayList.get(position); holder.courseTV.setText(recyclerData.getTitle()); holder.courseIV.setImageResource(recyclerData.getImgid()); } @Override public int getItemCount() { // this method returns the size of recyclerview return courseDataArrayList.size(); } // View Holder Class to handle Recycler View. public class RecyclerViewHolder extends RecyclerView.ViewHolder { private TextView courseTV; private ImageView courseIV; public RecyclerViewHolder(@NonNull View itemView) { super(itemView); courseTV = itemView.findViewById(R.id.idTVCourse); courseIV = itemView.findViewById(R.id.idIVcourseIV); } }}", "e": 32125, "s": 30238, "text": null }, { "code": null, "e": 32173, "s": 32125, "text": "Step 6: Working with the activity_main.xml file" }, { "code": null, "e": 32360, "s": 32173, "text": "This is the main screen that displays all data in the form of a grid. Here we have to implement Recycler View. Below is the code snippet of the XML layout in the activity_main.xml file. " }, { "code": null, "e": 32364, "s": 32360, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><!--XMl Layout for RecyclerView--><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/idCourseRV\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 32938, "s": 32364, "text": null }, { "code": null, "e": 32987, "s": 32938, "text": "Step 7: Working with the MainActivity.java file " }, { "code": null, "e": 33252, "s": 32987, "text": "This is the main java file where we will set LayoutManager, adapter, and set data to RecyclerView which is to be displayed in RecyclerView. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. " }, { "code": null, "e": 33257, "s": 33252, "text": "Java" }, { "code": "import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.GridLayoutManager;import androidx.recyclerview.widget.RecyclerView;import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private RecyclerView recyclerView; private ArrayList<RecyclerData> recyclerDataArrayList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView=findViewById(R.id.idCourseRV); // created new array list.. recyclerDataArrayList=new ArrayList<>(); // added data to array list recyclerDataArrayList.add(new RecyclerData(\"DSA\",R.drawable.ic_gfglogo)); recyclerDataArrayList.add(new RecyclerData(\"JAVA\",R.drawable.ic_gfglogo)); recyclerDataArrayList.add(new RecyclerData(\"C++\",R.drawable.ic_gfglogo)); recyclerDataArrayList.add(new RecyclerData(\"Python\",R.drawable.ic_gfglogo)); recyclerDataArrayList.add(new RecyclerData(\"Node Js\",R.drawable.ic_gfglogo)); // added data from arraylist to adapter class. RecyclerViewAdapter adapter=new RecyclerViewAdapter(recyclerDataArrayList,this); // setting grid layout manager to implement grid view. // in this method '2' represents number of columns to be displayed in grid view. GridLayoutManager layoutManager=new GridLayoutManager(this,2); // at last set adapter to recycler view. recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(adapter); }}", "e": 34885, "s": 33257, "text": null }, { "code": null, "e": 34895, "s": 34885, "text": "Output: " }, { "code": null, "e": 35164, "s": 34895, "text": "You can check out the project link mentioned below where you can get all code to implement RecyclerView with Grid Layout Manager. If you want to implement On Click Listener for Recycler Items in Grid Layout then check out this post for implementation of RecyclerView. " }, { "code": null, "e": 35189, "s": 35164, "text": "Project Link: Click Here" }, { "code": null, "e": 35202, "s": 35189, "text": "hemantjain99" }, { "code": null, "e": 35210, "s": 35202, "text": "android" }, { "code": null, "e": 35217, "s": 35210, "text": "Picked" }, { "code": null, "e": 35225, "s": 35217, "text": "Android" }, { "code": null, "e": 35230, "s": 35225, "text": "Java" }, { "code": null, "e": 35235, "s": 35230, "text": "Java" }, { "code": null, "e": 35243, "s": 35235, "text": "Android" }, { "code": null, "e": 35341, "s": 35243, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35350, "s": 35341, "text": "Comments" }, { "code": null, "e": 35363, "s": 35350, "text": "Old Comments" }, { "code": null, "e": 35421, "s": 35363, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 35464, "s": 35421, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 35495, "s": 35464, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 35528, "s": 35495, "text": "Services in Android with Example" }, { "code": null, "e": 35561, "s": 35528, "text": "CardView in Android With Example" }, { "code": null, "e": 35576, "s": 35561, "text": "Arrays in Java" }, { "code": null, "e": 35620, "s": 35576, "text": "Split() String method in Java with examples" }, { "code": null, "e": 35642, "s": 35620, "text": "For-each loop in Java" }, { "code": null, "e": 35667, "s": 35642, "text": "Reverse a string in Java" } ]
How to display the background color of an element in HTML?
Use the bgcolor attribute in HTML to display the background color of an element. It is used to control the background of an HTML element, specifically page body and table backgrounds. Note − This attribute is not supported in HTML5. You can try to run the following code to learn how to implement bgcolor attribute in HTML − <!DOCTYPE html> <html> <head> <title>HTML Background Colors</title> </head> <body> <!-- Format 1 - Use color name --> <table bgcolor = "yellow" width = "100%"> <tr> <td> This background is yellow </td> </tr> </table> <!-- Format 2 - Use hex value --> <table bgcolor = "#6666FF" width = "100%"> <tr> <td> This background is sky blue </td> </tr> </table> <!-- Format 3 - Use color value in RGB terms --> <table bgcolor = "rgb(255,0,255)" width = "100%"> <tr> <td> This background is green </td> </tr> </table> </body> </html>
[ { "code": null, "e": 1246, "s": 1062, "text": "Use the bgcolor attribute in HTML to display the background color of an element. It is used to control the background of an HTML element, specifically page body and table backgrounds." }, { "code": null, "e": 1295, "s": 1246, "text": "Note − This attribute is not supported in HTML5." }, { "code": null, "e": 1387, "s": 1295, "text": "You can try to run the following code to learn how to implement bgcolor attribute in HTML −" }, { "code": null, "e": 2156, "s": 1387, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML Background Colors</title>\n </head>\n <body>\n <!-- Format 1 - Use color name -->\n <table bgcolor = \"yellow\" width = \"100%\">\n <tr>\n <td>\n This background is yellow\n </td>\n </tr>\n </table>\n\n <!-- Format 2 - Use hex value -->\n <table bgcolor = \"#6666FF\" width = \"100%\">\n <tr>\n <td>\n This background is sky blue\n </td>\n </tr>\n </table>\n\n <!-- Format 3 - Use color value in RGB terms -->\n <table bgcolor = \"rgb(255,0,255)\" width = \"100%\">\n <tr>\n <td>\n This background is green\n </td>\n </tr>\n </table>\n </body>\n</html>" } ]
Perl - Socket Programming
Socket is a Berkeley UNIX mechanism of creating a virtual duplex connection between different processes. This was later ported on to every known OS enabling communication between systems across geographical location running on different OS software. If not for the socket, most of the network communication between systems would never ever have happened. Taking a closer look; a typical computer system on a network receives and sends information as desired by the various applications running on it. This information is routed to the system, since a unique IP address is designated to it. On the system, this information is given to the relevant applications, which listen on different ports. For example an internet browser listens on port 80 for information received from the web server. Also we can write our custom applications which may listen and send/receive information on a specific port number. For now, let's sum up that a socket is an IP address and a port, enabling connection to send and recieve data over a network. To explain above mentioned socket concept we will take an example of Client - Server Programming using Perl. To complete a client server architecture we would have to go through the following steps − Create a socket using socket call. Create a socket using socket call. Bind the socket to a port address using bind call. Bind the socket to a port address using bind call. Listen to the socket at the port address using listen call. Listen to the socket at the port address using listen call. Accept client connections using accept call. Accept client connections using accept call. Create a socket with socket call. Create a socket with socket call. Connect (the socket) to the server using connect call. Connect (the socket) to the server using connect call. Following diagram shows the complete sequence of the calls used by Client and Server to communicate with each other − The socket() call is the first call in establishing a network connection is creating a socket. This call has the following syntax − socket( SOCKET, DOMAIN, TYPE, PROTOCOL ); The above call creates a SOCKET and other three arguments are integers which should have the following values for TCP/IP connections. DOMAIN should be PF_INET. It's probable 2 on your computer. DOMAIN should be PF_INET. It's probable 2 on your computer. TYPE should be SOCK_STREAM for TCP/IP connection. TYPE should be SOCK_STREAM for TCP/IP connection. PROTOCOL should be (getprotobyname('tcp'))[2]. It is the particular protocol such as TCP to be spoken over the socket. PROTOCOL should be (getprotobyname('tcp'))[2]. It is the particular protocol such as TCP to be spoken over the socket. So socket function call issued by the server will be something like this − use Socket # This defines PF_INET and SOCK_STREAM socket(SOCKET,PF_INET,SOCK_STREAM,(getprotobyname('tcp'))[2]); The sockets created by socket() call are useless until they are bound to a hostname and a port number. Server uses the following bind() function to specify the port at which they will be accepting connections from the clients. bind( SOCKET, ADDRESS ); Here SOCKET is the descriptor returned by socket() call and ADDRESS is a socket address ( for TCP/IP ) containing three elements − The address family (For TCP/IP, that's AF_INET, probably 2 on your system). The address family (For TCP/IP, that's AF_INET, probably 2 on your system). The port number (for example 21). The port number (for example 21). The internet address of the computer (for example 10.12.12.168). The internet address of the computer (for example 10.12.12.168). As the bind() is used by a server, which does not need to know its own address so the argument list looks like this − use Socket # This defines PF_INET and SOCK_STREAM $port = 12345; # The unique port used by the sever to listen requests $server_ip_address = "10.12.12.168"; bind( SOCKET, pack_sockaddr_in($port, inet_aton($server_ip_address))) or die "Can't bind to port $port! \n"; The or die clause is very important because if a server dies without outstanding connections, the port won't be immediately reusable unless you use the option SO_REUSEADDR using setsockopt() function. Here pack_sockaddr_in() function is being used to pack the Port and IP address into binary format. If this is a server program, then it is required to issue a call to listen() on the specified port to listen, i.e., wait for the incoming requests. This call has the following syntax − listen( SOCKET, QUEUESIZE ); The above call uses SOCKET descriptor returned by socket() call and QUEUESIZE is the maximum number of outstanding connection request allowed simultaneously. If this is a server program then it is required to issue a call to the access() function to accept the incoming connections. This call has the following syntax − accept( NEW_SOCKET, SOCKET ); The accept call receive SOCKET descriptor returned by socket() function and upon successful completion, a new socket descriptor NEW_SOCKET is returned for all future communication between the client and the server. If access() call fails, then it returns FLASE which is defined in Socket module which we have used initially. Generally, accept() is used in an infinite loop. As soon as one connection arrives the server either creates a child process to deal with it or serves it himself and then goes back to listen for more connections. while(1) { accept( NEW_SOCKET, SOCKT ); ....... } Now all the calls related to server are over and let us see a call which will be required by the client. If you are going to prepare client program, then first you will use socket() call to create a socket and then you would have to use connect() call to connect to the server. You already have seen socket() call syntax and it will remain similar to server socket() call, but here is the syntax for connect() call − connect( SOCKET, ADDRESS ); Here SCOKET is the socket descriptor returned by socket() call issued by the client and ADDRESS is a socket address similar to bind call, except that it contains the IP address of the remote server. $port = 21; # For example, the ftp port $server_ip_address = "10.12.12.168"; connect( SOCKET, pack_sockaddr_in($port, inet_aton($server_ip_address))) or die "Can't connect to port $port! \n"; If you connect to the server successfully, then you can start sending your commands to the server using SOCKET descriptor, otherwise your client will come out by giving an error message. Following is a Perl code to implement a simple client-server program using Perl socket. Here server listens for incoming requests and once connection is established, it simply replies Smile from the server. The client reads that message and print on the screen. Let's see how it has been done, assuming we have our server and client on the same machine. #!/usr/bin/perl -w # Filename : server.pl use strict; use Socket; # use port 7890 as default my $port = shift || 7890; my $proto = getprotobyname('tcp'); my $server = "localhost"; # Host IP running the server # create a socket, make it reusable socket(SOCKET, PF_INET, SOCK_STREAM, $proto) or die "Can't open socket $!\n"; setsockopt(SOCKET, SOL_SOCKET, SO_REUSEADDR, 1) or die "Can't set socket option to SO_REUSEADDR $!\n"; # bind to a port, then listen bind( SOCKET, pack_sockaddr_in($port, inet_aton($server))) or die "Can't bind to port $port! \n"; listen(SOCKET, 5) or die "listen: $!"; print "SERVER started on port $port\n"; # accepting a connection my $client_addr; while ($client_addr = accept(NEW_SOCKET, SOCKET)) { # send them a message, close connection my $name = gethostbyaddr($client_addr, AF_INET ); print NEW_SOCKET "Smile from the server"; print "Connection recieved from $name\n"; close NEW_SOCKET; } To run the server in background mode issue the following command on Unix prompt − $perl sever.pl& !/usr/bin/perl -w # Filename : client.pl use strict; use Socket; # initialize host and port my $host = shift || 'localhost'; my $port = shift || 7890; my $server = "localhost"; # Host IP running the server # create the socket, connect to the port socket(SOCKET,PF_INET,SOCK_STREAM,(getprotobyname('tcp'))[2]) or die "Can't create a socket $!\n"; connect( SOCKET, pack_sockaddr_in($port, inet_aton($server))) or die "Can't connect to port $port! \n"; my $line; while ($line = <SOCKET>) { print "$line\n"; } close SOCKET or die "close: $!"; Now let's start our client at the command prompt, which will connect to the server and read message sent by the server and displays the same on the screen as follows − $perl client.pl Smile from the server NOTE − If you are giving the actual IP address in dot notation, then it is recommended to provide IP address in the same format in both client as well as server to avoid any confusion. 46 Lectures 4.5 hours Devi Killada 11 Lectures 1.5 hours Harshit Srivastava 30 Lectures 6 hours TELCOMA Global 24 Lectures 2 hours Mohammad Nauman 68 Lectures 7 hours Stone River ELearning 58 Lectures 6.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2575, "s": 2220, "text": "Socket is a Berkeley UNIX mechanism of creating a virtual duplex connection between different processes. This was later ported on to every known OS enabling communication between systems across geographical location running on different OS software. If not for the socket, most of the network communication between systems would never ever have happened." }, { "code": null, "e": 3126, "s": 2575, "text": "Taking a closer look; a typical computer system on a network receives and sends information as desired by the various applications running on it. This information is routed to the system, since a unique IP address is designated to it. On the system, this information is given to the relevant applications, which listen on different ports. For example an internet browser listens on port 80 for information received from the web server. Also we can write our custom applications which may listen and send/receive information on a specific port number." }, { "code": null, "e": 3252, "s": 3126, "text": "For now, let's sum up that a socket is an IP address and a port, enabling connection to send and recieve data over a network." }, { "code": null, "e": 3452, "s": 3252, "text": "To explain above mentioned socket concept we will take an example of Client - Server Programming using Perl. To complete a client server architecture we would have to go through the following steps −" }, { "code": null, "e": 3487, "s": 3452, "text": "Create a socket using socket call." }, { "code": null, "e": 3522, "s": 3487, "text": "Create a socket using socket call." }, { "code": null, "e": 3573, "s": 3522, "text": "Bind the socket to a port address using bind call." }, { "code": null, "e": 3624, "s": 3573, "text": "Bind the socket to a port address using bind call." }, { "code": null, "e": 3685, "s": 3624, "text": "Listen to the socket at the port address using listen call. " }, { "code": null, "e": 3746, "s": 3685, "text": "Listen to the socket at the port address using listen call. " }, { "code": null, "e": 3791, "s": 3746, "text": "Accept client connections using accept call." }, { "code": null, "e": 3836, "s": 3791, "text": "Accept client connections using accept call." }, { "code": null, "e": 3870, "s": 3836, "text": "Create a socket with socket call." }, { "code": null, "e": 3904, "s": 3870, "text": "Create a socket with socket call." }, { "code": null, "e": 3959, "s": 3904, "text": "Connect (the socket) to the server using connect call." }, { "code": null, "e": 4014, "s": 3959, "text": "Connect (the socket) to the server using connect call." }, { "code": null, "e": 4132, "s": 4014, "text": "Following diagram shows the complete sequence of the calls used by Client and Server to communicate with each other −" }, { "code": null, "e": 4264, "s": 4132, "text": "The socket() call is the first call in establishing a network connection is creating a socket. This call has the following syntax −" }, { "code": null, "e": 4307, "s": 4264, "text": "socket( SOCKET, DOMAIN, TYPE, PROTOCOL );\n" }, { "code": null, "e": 4441, "s": 4307, "text": "The above call creates a SOCKET and other three arguments are integers which should have the following values for TCP/IP connections." }, { "code": null, "e": 4501, "s": 4441, "text": "DOMAIN should be PF_INET. It's probable 2 on your computer." }, { "code": null, "e": 4561, "s": 4501, "text": "DOMAIN should be PF_INET. It's probable 2 on your computer." }, { "code": null, "e": 4611, "s": 4561, "text": "TYPE should be SOCK_STREAM for TCP/IP connection." }, { "code": null, "e": 4661, "s": 4611, "text": "TYPE should be SOCK_STREAM for TCP/IP connection." }, { "code": null, "e": 4780, "s": 4661, "text": "PROTOCOL should be (getprotobyname('tcp'))[2]. It is the particular protocol such as TCP to be spoken over the socket." }, { "code": null, "e": 4899, "s": 4780, "text": "PROTOCOL should be (getprotobyname('tcp'))[2]. It is the particular protocol such as TCP to be spoken over the socket." }, { "code": null, "e": 4974, "s": 4899, "text": "So socket function call issued by the server will be something like this −" }, { "code": null, "e": 5092, "s": 4974, "text": "use Socket # This defines PF_INET and SOCK_STREAM\n\nsocket(SOCKET,PF_INET,SOCK_STREAM,(getprotobyname('tcp'))[2]);" }, { "code": null, "e": 5319, "s": 5092, "text": "The sockets created by socket() call are useless until they are bound to a hostname and a port number. Server uses the following bind() function to specify the port at which they will be accepting connections from the clients." }, { "code": null, "e": 5344, "s": 5319, "text": "bind( SOCKET, ADDRESS );" }, { "code": null, "e": 5475, "s": 5344, "text": "Here SOCKET is the descriptor returned by socket() call and ADDRESS is a socket address ( for TCP/IP ) containing three elements −" }, { "code": null, "e": 5551, "s": 5475, "text": "The address family (For TCP/IP, that's AF_INET, probably 2 on your system)." }, { "code": null, "e": 5627, "s": 5551, "text": "The address family (For TCP/IP, that's AF_INET, probably 2 on your system)." }, { "code": null, "e": 5661, "s": 5627, "text": "The port number (for example 21)." }, { "code": null, "e": 5695, "s": 5661, "text": "The port number (for example 21)." }, { "code": null, "e": 5760, "s": 5695, "text": "The internet address of the computer (for example 10.12.12.168)." }, { "code": null, "e": 5825, "s": 5760, "text": "The internet address of the computer (for example 10.12.12.168)." }, { "code": null, "e": 5943, "s": 5825, "text": "As the bind() is used by a server, which does not need to know its own address so the argument list looks like this −" }, { "code": null, "e": 6223, "s": 5943, "text": "use Socket # This defines PF_INET and SOCK_STREAM\n\n$port = 12345; # The unique port used by the sever to listen requests\n$server_ip_address = \"10.12.12.168\";\nbind( SOCKET, pack_sockaddr_in($port, inet_aton($server_ip_address)))\n or die \"Can't bind to port $port! \\n\";" }, { "code": null, "e": 6523, "s": 6223, "text": "The or die clause is very important because if a server dies without outstanding connections, the port won't be immediately reusable unless you use the option SO_REUSEADDR using setsockopt() function. Here pack_sockaddr_in() function is being used to pack the Port and IP address into binary format." }, { "code": null, "e": 6708, "s": 6523, "text": "If this is a server program, then it is required to issue a call to listen() on the specified port to listen, i.e., wait for the incoming requests. This call has the following syntax −" }, { "code": null, "e": 6738, "s": 6708, "text": "listen( SOCKET, QUEUESIZE );\n" }, { "code": null, "e": 6896, "s": 6738, "text": "The above call uses SOCKET descriptor returned by socket() call and QUEUESIZE is the maximum number of outstanding connection request allowed simultaneously." }, { "code": null, "e": 7058, "s": 6896, "text": "If this is a server program then it is required to issue a call to the access() function to accept the incoming connections. This call has the following syntax −" }, { "code": null, "e": 7089, "s": 7058, "text": "accept( NEW_SOCKET, SOCKET );\n" }, { "code": null, "e": 7414, "s": 7089, "text": "The accept call receive SOCKET descriptor returned by socket() function and upon successful completion, a new socket descriptor NEW_SOCKET is returned for all future communication between the client and the server. If access() call fails, then it returns FLASE which is defined in Socket module which we have used initially." }, { "code": null, "e": 7627, "s": 7414, "text": "Generally, accept() is used in an infinite loop. As soon as one connection arrives the server either creates a child process to deal with it or serves it himself and then goes back to listen for more connections." }, { "code": null, "e": 7683, "s": 7627, "text": "while(1) {\n accept( NEW_SOCKET, SOCKT );\n .......\n}" }, { "code": null, "e": 7788, "s": 7683, "text": "Now all the calls related to server are over and let us see a call which will be required by the client." }, { "code": null, "e": 8100, "s": 7788, "text": "If you are going to prepare client program, then first you will use socket() call to create a socket and then you would have to use connect() call to connect to the server. You already have seen socket() call syntax and it will remain similar to server socket() call, but here is the syntax for connect() call −" }, { "code": null, "e": 8128, "s": 8100, "text": "connect( SOCKET, ADDRESS );" }, { "code": null, "e": 8327, "s": 8128, "text": "Here SCOKET is the socket descriptor returned by socket() call issued by the client and ADDRESS is a socket address similar to bind call, except that it contains the IP address of the remote server." }, { "code": null, "e": 8525, "s": 8327, "text": "$port = 21; # For example, the ftp port\n$server_ip_address = \"10.12.12.168\";\nconnect( SOCKET, pack_sockaddr_in($port, inet_aton($server_ip_address)))\n or die \"Can't connect to port $port! \\n\";" }, { "code": null, "e": 8712, "s": 8525, "text": "If you connect to the server successfully, then you can start sending your commands to the server using SOCKET descriptor, otherwise your client will come out by giving an error message." }, { "code": null, "e": 9066, "s": 8712, "text": "Following is a Perl code to implement a simple client-server program using Perl socket. Here server listens for incoming requests and once connection is established, it simply replies Smile from the server. The client reads that message and print on the screen. Let's see how it has been done, assuming we have our server and client on the same machine." }, { "code": null, "e": 10018, "s": 9066, "text": "#!/usr/bin/perl -w\n# Filename : server.pl\n\nuse strict;\nuse Socket;\n\n# use port 7890 as default\nmy $port = shift || 7890;\nmy $proto = getprotobyname('tcp');\nmy $server = \"localhost\"; # Host IP running the server\n\n# create a socket, make it reusable\nsocket(SOCKET, PF_INET, SOCK_STREAM, $proto)\n or die \"Can't open socket $!\\n\";\nsetsockopt(SOCKET, SOL_SOCKET, SO_REUSEADDR, 1)\n or die \"Can't set socket option to SO_REUSEADDR $!\\n\";\n\n# bind to a port, then listen\nbind( SOCKET, pack_sockaddr_in($port, inet_aton($server)))\n or die \"Can't bind to port $port! \\n\";\n\nlisten(SOCKET, 5) or die \"listen: $!\";\nprint \"SERVER started on port $port\\n\";\n\n# accepting a connection\nmy $client_addr;\nwhile ($client_addr = accept(NEW_SOCKET, SOCKET)) {\n # send them a message, close connection\n my $name = gethostbyaddr($client_addr, AF_INET );\n print NEW_SOCKET \"Smile from the server\";\n print \"Connection recieved from $name\\n\";\n close NEW_SOCKET;\n}" }, { "code": null, "e": 10100, "s": 10018, "text": "To run the server in background mode issue the following command on Unix prompt −" }, { "code": null, "e": 10116, "s": 10100, "text": "$perl sever.pl&" }, { "code": null, "e": 10669, "s": 10116, "text": "!/usr/bin/perl -w\n# Filename : client.pl\n\nuse strict;\nuse Socket;\n\n# initialize host and port\nmy $host = shift || 'localhost';\nmy $port = shift || 7890;\nmy $server = \"localhost\"; # Host IP running the server\n\n# create the socket, connect to the port\nsocket(SOCKET,PF_INET,SOCK_STREAM,(getprotobyname('tcp'))[2])\n or die \"Can't create a socket $!\\n\";\nconnect( SOCKET, pack_sockaddr_in($port, inet_aton($server)))\n or die \"Can't connect to port $port! \\n\";\n\nmy $line;\nwhile ($line = <SOCKET>) {\n print \"$line\\n\";\n}\nclose SOCKET or die \"close: $!\";" }, { "code": null, "e": 10837, "s": 10669, "text": "Now let's start our client at the command prompt, which will connect to the server and read message sent by the server and displays the same on the screen as follows −" }, { "code": null, "e": 10875, "s": 10837, "text": "$perl client.pl\nSmile from the server" }, { "code": null, "e": 11060, "s": 10875, "text": "NOTE − If you are giving the actual IP address in dot notation, then it is recommended to provide IP address in the same format in both client as well as server to avoid any confusion." }, { "code": null, "e": 11095, "s": 11060, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 11109, "s": 11095, "text": " Devi Killada" }, { "code": null, "e": 11144, "s": 11109, "text": "\n 11 Lectures \n 1.5 hours \n" }, { "code": null, "e": 11164, "s": 11144, "text": " Harshit Srivastava" }, { "code": null, "e": 11197, "s": 11164, "text": "\n 30 Lectures \n 6 hours \n" }, { "code": null, "e": 11213, "s": 11197, "text": " TELCOMA Global" }, { "code": null, "e": 11246, "s": 11213, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 11263, "s": 11246, "text": " Mohammad Nauman" }, { "code": null, "e": 11296, "s": 11263, "text": "\n 68 Lectures \n 7 hours \n" }, { "code": null, "e": 11319, "s": 11296, "text": " Stone River ELearning" }, { "code": null, "e": 11354, "s": 11319, "text": "\n 58 Lectures \n 6.5 hours \n" }, { "code": null, "e": 11377, "s": 11354, "text": " Stone River ELearning" }, { "code": null, "e": 11384, "s": 11377, "text": " Print" }, { "code": null, "e": 11395, "s": 11384, "text": " Add Notes" } ]
How to Install Pillow on Linux? - GeeksforGeeks
30 Sep, 2021 In this article, we will look into the various methods of installing the PIL package on a Linux machine. Python Imaging Library (expansion of PIL) is the de facto image processing package for Python language. It incorporates lightweight image processing tools that aid in editing, creating, and saving images. The only thing that you need for installing Numpy on Windows are: Python PIP or Conda (Depending upon the user preference) If you want the installation to be done through conda, you can use the below command: conda install -c anaconda pillow Type in “y” for yes when prompted. You will get a similar message once the installation is complete Make sure you follow the best practices for installation using conda as: Use an environment for installation rather than in the base environment using the below command: conda create -n my-env conda activate my-env Note: If your preferred method of installation is conda-forge, use the below command: conda config --env --add channels conda-forge Use the below command to verify if the above package has successfully installed: conda list pillow You will get a similar message as shown below if the installation has been successful: Users who prefer to use pip can use the below command to install the package: pip install pillow You will get a similar message once the installation is complete: It is a good programming practice to install packages in a virtual environment rather than installing them globally. PIP users can use the below command to create a virtual environment: python3 -m venv my-env Activate the virtual environment (ie, my-env) using the below command: source my-env/bin/activate Use the below command to check if the package has been successfully installed: python3 -m pip show pillow You will get a similar message as shown below if the installation is successful: how-to-install Picked How To Installation Guide Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install FFmpeg on Windows? How to Set Git Username and Password in GitBash? How to Install Jupyter Notebook on MacOS? How to Add External JAR File to an IntelliJ IDEA Project? How to Create and Setup Spring Boot Project in Eclipse IDE? Installation of Node.js on Linux How to Install FFmpeg on Windows? How to Install Pygame on Windows ? How to Install Jupyter Notebook on MacOS? How to Add External JAR File to an IntelliJ IDEA Project?
[ { "code": null, "e": 24561, "s": 24533, "text": "\n30 Sep, 2021" }, { "code": null, "e": 24872, "s": 24561, "text": "In this article, we will look into the various methods of installing the PIL package on a Linux machine. Python Imaging Library (expansion of PIL) is the de facto image processing package for Python language. It incorporates lightweight image processing tools that aid in editing, creating, and saving images. " }, { "code": null, "e": 24938, "s": 24872, "text": "The only thing that you need for installing Numpy on Windows are:" }, { "code": null, "e": 24945, "s": 24938, "text": "Python" }, { "code": null, "e": 24995, "s": 24945, "text": "PIP or Conda (Depending upon the user preference)" }, { "code": null, "e": 25081, "s": 24995, "text": "If you want the installation to be done through conda, you can use the below command:" }, { "code": null, "e": 25114, "s": 25081, "text": "conda install -c anaconda pillow" }, { "code": null, "e": 25149, "s": 25114, "text": "Type in “y” for yes when prompted." }, { "code": null, "e": 25214, "s": 25149, "text": "You will get a similar message once the installation is complete" }, { "code": null, "e": 25287, "s": 25214, "text": "Make sure you follow the best practices for installation using conda as:" }, { "code": null, "e": 25384, "s": 25287, "text": "Use an environment for installation rather than in the base environment using the below command:" }, { "code": null, "e": 25429, "s": 25384, "text": "conda create -n my-env\nconda activate my-env" }, { "code": null, "e": 25515, "s": 25429, "text": "Note: If your preferred method of installation is conda-forge, use the below command:" }, { "code": null, "e": 25561, "s": 25515, "text": "conda config --env --add channels conda-forge" }, { "code": null, "e": 25642, "s": 25561, "text": "Use the below command to verify if the above package has successfully installed:" }, { "code": null, "e": 25660, "s": 25642, "text": "conda list pillow" }, { "code": null, "e": 25747, "s": 25660, "text": "You will get a similar message as shown below if the installation has been successful:" }, { "code": null, "e": 25825, "s": 25747, "text": "Users who prefer to use pip can use the below command to install the package:" }, { "code": null, "e": 25844, "s": 25825, "text": "pip install pillow" }, { "code": null, "e": 25910, "s": 25844, "text": "You will get a similar message once the installation is complete:" }, { "code": null, "e": 26096, "s": 25910, "text": "It is a good programming practice to install packages in a virtual environment rather than installing them globally. PIP users can use the below command to create a virtual environment:" }, { "code": null, "e": 26119, "s": 26096, "text": "python3 -m venv my-env" }, { "code": null, "e": 26190, "s": 26119, "text": "Activate the virtual environment (ie, my-env) using the below command:" }, { "code": null, "e": 26217, "s": 26190, "text": "source my-env/bin/activate" }, { "code": null, "e": 26296, "s": 26217, "text": "Use the below command to check if the package has been successfully installed:" }, { "code": null, "e": 26323, "s": 26296, "text": "python3 -m pip show pillow" }, { "code": null, "e": 26404, "s": 26323, "text": "You will get a similar message as shown below if the installation is successful:" }, { "code": null, "e": 26419, "s": 26404, "text": "how-to-install" }, { "code": null, "e": 26426, "s": 26419, "text": "Picked" }, { "code": null, "e": 26433, "s": 26426, "text": "How To" }, { "code": null, "e": 26452, "s": 26433, "text": "Installation Guide" }, { "code": null, "e": 26550, "s": 26452, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26559, "s": 26550, "text": "Comments" }, { "code": null, "e": 26572, "s": 26559, "text": "Old Comments" }, { "code": null, "e": 26606, "s": 26572, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 26655, "s": 26606, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 26697, "s": 26655, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 26755, "s": 26697, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 26815, "s": 26755, "text": "How to Create and Setup Spring Boot Project in Eclipse IDE?" }, { "code": null, "e": 26848, "s": 26815, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26882, "s": 26848, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 26917, "s": 26882, "text": "How to Install Pygame on Windows ?" }, { "code": null, "e": 26959, "s": 26917, "text": "How to Install Jupyter Notebook on MacOS?" } ]
How to lock the Android device programmatically?
This example demonstrate about How to lock the Android device programmatically. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml <? xml version= "1.0" encoding= "utf-8" ?> <RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android :layout_width= "match_parent" android :layout_height= "match_parent" android :layout_margin= "16dp" tools :context= ".MainActivity" > <LinearLayout android :layout_width= "match_parent" android :layout_height= "wrap_content" android :layout_centerInParent= "true" android :orientation= "horizontal" > <Button android :id= "@+id/btnEnable" android :layout_width= "0dp" android :layout_height= "wrap_content" android :layout_weight= "1" android :onClick= "enablePhone" android :text= "Enable" /> <Button android :id= "@+id/btnLock" android :layout_width= "0dp" android :layout_height= "wrap_content" android :layout_weight= "1" android :onClick= "lockPhone" android :text= "Lock" /> </LinearLayout> </RelativeLayout> Step 3 − Add the following code to res/xml/policies.xml <? xml version= "1.0" encoding= "utf-8" ?> <device-admin xmlns: android = "http://schemas.android.com/apk/res/android" > <uses-policies> <force-lock /> </uses-policies> </device-admin> Step 4 − Add the following code to src/DeviceAdmin package app.tutorialspoint.com.sample ; import android.app.admin.DeviceAdminReceiver ; import android.content.Context ; import android.content.Intent ; import android.widget.Toast ; public class DeviceAdmin extends DeviceAdminReceiver { @Override public void onEnabled (Context context , Intent intent) { super .onEnabled(context , intent) ; Toast. makeText (context , "Enabled" , Toast. LENGTH_SHORT ).show() ; } @Override public void onDisabled (Context context , Intent intent) { super .onDisabled(context , intent) ; Toast. makeText (context , "Disabled" , Toast. LENGTH_SHORT ).show() ; } } Step 5 − Add the following code to src/MainActivity package app.tutorialspoint.com.sample ; import android.app.Activity ; import android.app.admin.DevicePolicyManager ; import android.content.ComponentName ; import android.content.Context ; import android.content.Intent ; import android.support.annotation. Nullable ; import android.support.v7.app.AppCompatActivity ; import android.os.Bundle ; import android.view.View ; import android.widget.Button ; import android.widget.Toast ; public class MainActivity extends AppCompatActivity { static final int RESULT_ENABLE = 1 ; DevicePolicyManager deviceManger ; ComponentName compName ; Button btnEnable , btnLock ; @Override protected void onCreate (Bundle savedInstanceState) { super .onCreate(savedInstanceState) ; setContentView(R.layout. activity_main ) ; btnEnable = findViewById(R.id. btnEnable ) ; btnLock = findViewById(R.id. btnLock ) ; deviceManger = (DevicePolicyManager) getSystemService(Context. DEVICE_POLICY_SERVICE ) ; compName = new ComponentName( this, DeviceAdmin. class ) ; boolean active = deviceManger .isAdminActive( compName ) ; if (active) { btnEnable .setText( "Disable" ) ; btnLock .setVisibility(View. VISIBLE ) ; } else { btnEnable .setText( "Enable" ) ; btnLock .setVisibility(View. GONE ) ; } } public void enablePhone (View view) { boolean active = deviceManger .isAdminActive( compName ) ; if (active) { deviceManger .removeActiveAdmin( compName ) ; btnEnable .setText( "Enable" ) ; btnLock .setVisibility(View. GONE ) ; } else { Intent intent = new Intent(DevicePolicyManager. ACTION_ADD_DEVICE_ADMIN ) ; intent.putExtra(DevicePolicyManager. EXTRA_DEVICE_ADMIN , compName ) ; intent.putExtra(DevicePolicyManager. EXTRA_ADD_EXPLANATION , "You should enable the app!" ) ; startActivityForResult(intent , RESULT_ENABLE ) ; } } public void lockPhone (View view) { deviceManger .lockNow() ; } @Override protected void onActivityResult ( int requestCode , int resultCode , @Nullable Intent data) { super .onActivityResult(requestCode , resultCode , data) ; switch (requestCode) { case RESULT_ENABLE : if (resultCode == Activity. RESULT_OK ) { btnEnable .setText( "Disable" ) ; btnLock .setVisibility(View. VISIBLE ) ; } else { Toast. makeText (getApplicationContext() , "Failed!" , Toast. LENGTH_SHORT ).show() ; } return; } } } Step 6 − 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.tutorialspoint.com.sample" > <uses-permission android :name= "android.permission.CALL_PHONE" /> <application android :allowBackup= "true" android :icon= "@mipmap/ic_launcher" android :label= "@string/app_name" android :roundIcon= "@mipmap/ic_launcher_round" android :supportsRtl= "true" android :theme= "@style/AppTheme" > <activity android :name= ".MainActivity" > <intent-filter> <action android :name= "android.intent.action.MAIN" /> <category android :name= "android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android :name= ".DeviceAdmin" android :description= "@string/app_description" android :label= "@string/app_name" android :permission= "android.permission.BIND_DEVICE_ADMIN" > <meta-data android :name= "android.app.device_admin" android :resource= "@xml/policies" /> <intent-filter> <action android :name= "android.app.action.DEVICE_ADMIN_ENABLED" /> </intent-filter> </receiver> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
[ { "code": null, "e": 1142, "s": 1062, "text": "This example demonstrate about How to lock the Android device programmatically." }, { "code": null, "e": 1271, "s": 1142, "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": 1335, "s": 1271, "text": "Step 2 − Add the following code to res/layout/activity_main.xml" }, { "code": null, "e": 2394, "s": 1335, "text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<RelativeLayout xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n android :layout_width= \"match_parent\"\n android :layout_height= \"match_parent\"\n android :layout_margin= \"16dp\"\n tools :context= \".MainActivity\" >\n <LinearLayout\n android :layout_width= \"match_parent\"\n android :layout_height= \"wrap_content\"\n android :layout_centerInParent= \"true\"\n android :orientation= \"horizontal\" >\n <Button\n android :id= \"@+id/btnEnable\"\n android :layout_width= \"0dp\"\n android :layout_height= \"wrap_content\"\n android :layout_weight= \"1\"\n android :onClick= \"enablePhone\"\n android :text= \"Enable\" />\n <Button\n android :id= \"@+id/btnLock\"\n android :layout_width= \"0dp\"\n android :layout_height= \"wrap_content\"\n android :layout_weight= \"1\"\n android :onClick= \"lockPhone\"\n android :text= \"Lock\" />\n </LinearLayout>\n</RelativeLayout>" }, { "code": null, "e": 2450, "s": 2394, "text": "Step 3 − Add the following code to res/xml/policies.xml" }, { "code": null, "e": 2647, "s": 2450, "text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<device-admin xmlns: android = \"http://schemas.android.com/apk/res/android\" >\n <uses-policies>\n <force-lock />\n </uses-policies>\n</device-admin>" }, { "code": null, "e": 2698, "s": 2647, "text": "Step 4 − Add the following code to src/DeviceAdmin" }, { "code": null, "e": 3336, "s": 2698, "text": "package app.tutorialspoint.com.sample ;\nimport android.app.admin.DeviceAdminReceiver ;\nimport android.content.Context ;\nimport android.content.Intent ;\nimport android.widget.Toast ;\npublic class DeviceAdmin extends DeviceAdminReceiver {\n @Override\n public void onEnabled (Context context , Intent intent) {\n super .onEnabled(context , intent) ;\n Toast. makeText (context , \"Enabled\" , Toast. LENGTH_SHORT ).show() ;\n }\n @Override\n public void onDisabled (Context context , Intent intent) {\n super .onDisabled(context , intent) ;\n Toast. makeText (context , \"Disabled\" , Toast. LENGTH_SHORT ).show() ;\n }\n}" }, { "code": null, "e": 3388, "s": 3336, "text": "Step 5 − Add the following code to src/MainActivity" }, { "code": null, "e": 6014, "s": 3388, "text": "package app.tutorialspoint.com.sample ;\nimport android.app.Activity ;\nimport android.app.admin.DevicePolicyManager ;\nimport android.content.ComponentName ;\nimport android.content.Context ;\nimport android.content.Intent ;\nimport android.support.annotation. Nullable ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.os.Bundle ;\nimport android.view.View ;\nimport android.widget.Button ;\nimport android.widget.Toast ;\npublic class MainActivity extends AppCompatActivity {\n static final int RESULT_ENABLE = 1 ;\n DevicePolicyManager deviceManger ;\n ComponentName compName ;\n Button btnEnable , btnLock ;\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n btnEnable = findViewById(R.id. btnEnable ) ;\n btnLock = findViewById(R.id. btnLock ) ;\n deviceManger = (DevicePolicyManager)\n getSystemService(Context. DEVICE_POLICY_SERVICE ) ;\n compName = new ComponentName( this, DeviceAdmin. class ) ;\n boolean active = deviceManger .isAdminActive( compName ) ;\n if (active) {\n btnEnable .setText( \"Disable\" ) ;\n btnLock .setVisibility(View. VISIBLE ) ;\n } else {\n btnEnable .setText( \"Enable\" ) ;\n btnLock .setVisibility(View. GONE ) ;\n }\n }\n public void enablePhone (View view) {\n boolean active = deviceManger .isAdminActive( compName ) ;\n if (active) {\n deviceManger .removeActiveAdmin( compName ) ;\n btnEnable .setText( \"Enable\" ) ;\n btnLock .setVisibility(View. GONE ) ;\n } else {\n Intent intent = new Intent(DevicePolicyManager. ACTION_ADD_DEVICE_ADMIN ) ;\n intent.putExtra(DevicePolicyManager. EXTRA_DEVICE_ADMIN , compName ) ;\n intent.putExtra(DevicePolicyManager. EXTRA_ADD_EXPLANATION , \"You should enable the app!\" ) ;\n startActivityForResult(intent , RESULT_ENABLE ) ;\n }\n }\n public void lockPhone (View view) {\n deviceManger .lockNow() ;\n }\n @Override\n protected void onActivityResult ( int requestCode , int resultCode , @Nullable Intent\n data) {\n super .onActivityResult(requestCode , resultCode , data) ;\n switch (requestCode) {\n case RESULT_ENABLE :\n if (resultCode == Activity. RESULT_OK ) {\n btnEnable .setText( \"Disable\" ) ;\n btnLock .setVisibility(View. VISIBLE ) ;\n } else {\n Toast. makeText (getApplicationContext() , \"Failed!\" ,\n Toast. LENGTH_SHORT ).show() ;\n }\n return;\n }\n }\n}" }, { "code": null, "e": 6069, "s": 6014, "text": "Step 6 − Add the following code to androidManifest.xml" }, { "code": null, "e": 7356, "s": 6069, "text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package= \"app.tutorialspoint.com.sample\" >\n <uses-permission android :name= \"android.permission.CALL_PHONE\" />\n <application\n android :allowBackup= \"true\"\n android :icon= \"@mipmap/ic_launcher\"\n android :label= \"@string/app_name\"\n android :roundIcon= \"@mipmap/ic_launcher_round\"\n android :supportsRtl= \"true\"\n android :theme= \"@style/AppTheme\" >\n <activity android :name= \".MainActivity\" >\n <intent-filter>\n <action android :name= \"android.intent.action.MAIN\" />\n <category android :name= \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n <receiver\n android :name= \".DeviceAdmin\"\n android :description= \"@string/app_description\"\n android :label= \"@string/app_name\"\n android :permission= \"android.permission.BIND_DEVICE_ADMIN\" >\n <meta-data\n android :name= \"android.app.device_admin\"\n android :resource= \"@xml/policies\" />\n <intent-filter>\n <action android :name= \"android.app.action.DEVICE_ADMIN_ENABLED\" />\n </intent-filter>\n </receiver>\n </application>\n</manifest>" }, { "code": null, "e": 7703, "s": 7356, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" } ]
CREATE SCHEMA in SQL Server - GeeksforGeeks
02 Sep, 2020 A schema is a collection of database objects like tables, triggers, stored procedures, etc. A schema is connected with a user which is known as the schema owner. Database may have one or more schema. SQL Server have some built-in schema, for example: dbo, guest, sys, and INFORMATION_SCHEMA. dbo is default schema for a new database, owned by dbo user. While creating a new user with CREATE USER command, user will take dbo as its default schema. CREATE SCHEMA statement used to create a new schema in current database. Syntax : CREATE SCHEMA schemaname [AUTHORIZATION ownername] GO Example – CREATE SCHEMA geeks_sch; GO To select SQL Server SCHEMA :To list all schema in the current database, use query as shown below : SELECT * FROM sys.schemas Result – Create objects for the schema :To create a new table named Geektab in the geeks_sch schema : Syntax : CREATE TABLE schemaname.tablename( values... ); Example – CREATE TABLE geeks_sch.Geektab( G_id INT PRIMARY KEY IDENTITY, Name VARCHAR(200), DOJ DATETIME2 NOT NULL ); DBMS-SQL SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? SQL | Views SQL Interview Questions Difference between DELETE, DROP and TRUNCATE Difference between DDL and DML in DBMS MySQL | Group_CONCAT() Function What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL - ORDER BY
[ { "code": null, "e": 23790, "s": 23762, "text": "\n02 Sep, 2020" }, { "code": null, "e": 23990, "s": 23790, "text": "A schema is a collection of database objects like tables, triggers, stored procedures, etc. A schema is connected with a user which is known as the schema owner. Database may have one or more schema." }, { "code": null, "e": 24082, "s": 23990, "text": "SQL Server have some built-in schema, for example: dbo, guest, sys, and INFORMATION_SCHEMA." }, { "code": null, "e": 24237, "s": 24082, "text": "dbo is default schema for a new database, owned by dbo user. While creating a new user with CREATE USER command, user will take dbo as its default schema." }, { "code": null, "e": 24310, "s": 24237, "text": "CREATE SCHEMA statement used to create a new schema in current database." }, { "code": null, "e": 24319, "s": 24310, "text": "Syntax :" }, { "code": null, "e": 24376, "s": 24319, "text": "CREATE SCHEMA schemaname\n [AUTHORIZATION ownername]\nGO" }, { "code": null, "e": 24386, "s": 24376, "text": "Example –" }, { "code": null, "e": 24415, "s": 24386, "text": "CREATE SCHEMA geeks_sch;\nGO " }, { "code": null, "e": 24515, "s": 24415, "text": "To select SQL Server SCHEMA :To list all schema in the current database, use query as shown below :" }, { "code": null, "e": 24543, "s": 24515, "text": "SELECT *\nFROM sys.schemas " }, { "code": null, "e": 24552, "s": 24543, "text": "Result –" }, { "code": null, "e": 24645, "s": 24552, "text": "Create objects for the schema :To create a new table named Geektab in the geeks_sch schema :" }, { "code": null, "e": 24654, "s": 24645, "text": "Syntax :" }, { "code": null, "e": 24703, "s": 24654, "text": "CREATE TABLE schemaname.tablename(\n values... );" }, { "code": null, "e": 24713, "s": 24703, "text": "Example –" }, { "code": null, "e": 24824, "s": 24713, "text": "CREATE TABLE geeks_sch.Geektab(\nG_id INT PRIMARY KEY IDENTITY, \nName VARCHAR(200), \nDOJ DATETIME2 NOT NULL\n); " }, { "code": null, "e": 24833, "s": 24824, "text": "DBMS-SQL" }, { "code": null, "e": 24844, "s": 24833, "text": "SQL-Server" }, { "code": null, "e": 24848, "s": 24844, "text": "SQL" }, { "code": null, "e": 24852, "s": 24848, "text": "SQL" }, { "code": null, "e": 24950, "s": 24852, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24961, "s": 24950, "text": "CTE in SQL" }, { "code": null, "e": 25027, "s": 24961, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 25039, "s": 25027, "text": "SQL | Views" }, { "code": null, "e": 25063, "s": 25039, "text": "SQL Interview Questions" }, { "code": null, "e": 25108, "s": 25063, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 25147, "s": 25108, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 25179, "s": 25147, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 25211, "s": 25179, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 25289, "s": 25211, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" } ]
Consuming a GraphQL API using fetch - React Client - GeeksforGeeks
13 Dec, 2021 In this article, we will learn to develop a React application, which will fetch the data from a public GraphQL API using Fetch. We will use The Movie Database Wrapper ( TMDB ) API to fetch the shows available with name/keyword. You can find the API reference and source code links at the end of this article. Before moving onto the development part, to initialize a simple react application you can follow the steps mentioned below: Step 1: Create React application. npx create-react-app foldername Step 2: Move into the project folder. cd foldername Step 3: Create a components folder and now Project Structure will look like: Project Structure This was basically the initial setup we require for our application. Now let us take a look at each of the components individually. Custom components reside in the components folder, with everything put together in the MainComponent.jsx, we will place this component inside App.js, which itself goes under the “root” DOM node, and everything inside this node will be managed by React DOM. We are going to develop three components: Main Component: Responsible for fetch operation and state changes in the application. Search Bar: A search bar to get the user input for the show name/keyword. ShowInfoCard: A reusable component to display the show information. Step 4: In the MainComponent.jsx component, we have a state variable, data which will hold the response for the GraphQL API. const [data, setData] = useState(Object); To fetch the information, we make a call to the apiEndpoint, but first let us break the GraphQL query apart, in general, to form a query, you must specify fields within fields until those fields resolve to actual data. In this way, you ask for specific fields on objects and get back exactly what you asked for. The structure of any GraphQL query looks like this: query { JSON objects to retrieve } With our query variable, we are trying to fetch all the shows available, using name/keyword, which is passed as an argument with $term. MainComponent.jsx (query part) const apiEndpoint = "https://tmdb.apps.quintero.io/";const query = ` query FetchData($term: String!){ tv{ search(term:$term){ edges{ node{ id originalName } } } } }`; To make the request using Fetch API, we send the GraphQL query and variables as a JSON object to the endpoint. GraphQL endpoint expects the body of the request to be a stringified JSON object that contains query and variables parameters. When the request is complete, the promise is resolved with the response object. This object is basically a generic placeholder for various response formats. response.json() is used to extract the JSON object from the response, it returns a promise, which is again resolved and data is updated.MainComponent.jsx ( request part ) MainComponent.jsx (request part) const getData = (term) => { fetch(apiEndpoint, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ query, variables: { term } }) }) .then(res => res.json()) .then((data) => setData(data)) .catch(console.error); }; So finally our MainComponent.jsx looks like: MainComponent.jsx import React, { useState } from "react";import SearchBar from "./SearchBar";import ShowInfoCard from "./ShowInfoCard"; function Main() { const [data, setData] = useState(Object); const apiEndpoint = "https://tmdb.apps.quintero.io/"; const query = ` query FetchData($term: String!){ tv{ search(term:$term){ edges{ node{ id originalName } } } } } `; const getData = (term) => { fetch(apiEndpoint, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ query, variables: { term } }) }) .then(res => res.json()) .then((data) => setData(data)) .catch(console.error); }; // console.log(data) return ( <div> <SearchBar getData={getData} /> {data.data ? data.data.tv.search.edges.map(({ node }) => ( <ShowInfoCard key={node.id} node={node} /> )) : <div></div> } </div> ); } export default Main; Step 5: Now, moving on to the SearchBar component, which serves the purpose of receiving the user input for name/keyword. It is a simple component, with an input field of text type, and a button to make the search request. The state variable term is updated holds the input from user, and is passed as an argument to getData() when the user makes the search request. SearchBar.jsx import React, { useState } from "react"; function SearchBar({getData}){ const [term, setTerm] = useState(""); const onChange = (e) =>{ setTerm(e.target.value) } const onSearch = () =>{ getData(term) } return( <div className="searchbar"> <input placeholder="Enter the name..." type="text" value={term} onChange={(event) => {onChange(event)}} onKeyUp={(event) => {onChange(event)}} onPaste={(event) => {onChange(event)}} /> <button type="button" className="searchButton" onClick={onSearch}>Search </button> </div> );} export default SearchBar; Step 6: Our last component, is a reusable UI component, which is basically a Card Component that receives node ( contains the show information ) as props, and just displays it in any chosen format. You can tweak the App.css file to understand the various design aspects. ShowInfoCard.jsx import React from "react"; function ShowInfoCard({ node }) { return ( <div className="datacontainer"> <div className="dataitem"> Name : {node.originalName} </div> </div> );} export default ShowInfoCard; Step 7: Finally, we need to include the MainComponent in App.js file: App.js import './App.css';import React from "react";import Main from './components/MainComponent'; function App() { return ( <div className="App"> <header className="App-header"> <h2>Consuming a GraphQL API</h2> </header> <Main /> </div> );} export default App; Step to run the application: To run the application on your system, run the following command: npm start Output: GraphQL API: https://github.com/nerdsupremacist/tmdb Fetch API: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API anikakapoor React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set background images in ReactJS ? How to create a table in ReactJS ? How to navigate on path by button click in react router ? ReactJS useNavigate() Hook React-Router Hooks Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills Convert a string to an integer in JavaScript
[ { "code": null, "e": 24826, "s": 24798, "text": "\n13 Dec, 2021" }, { "code": null, "e": 25135, "s": 24826, "text": "In this article, we will learn to develop a React application, which will fetch the data from a public GraphQL API using Fetch. We will use The Movie Database Wrapper ( TMDB ) API to fetch the shows available with name/keyword. You can find the API reference and source code links at the end of this article." }, { "code": null, "e": 25260, "s": 25135, "text": "Before moving onto the development part, to initialize a simple react application you can follow the steps mentioned below: " }, { "code": null, "e": 25294, "s": 25260, "text": "Step 1: Create React application." }, { "code": null, "e": 25326, "s": 25294, "text": "npx create-react-app foldername" }, { "code": null, "e": 25364, "s": 25326, "text": "Step 2: Move into the project folder." }, { "code": null, "e": 25378, "s": 25364, "text": "cd foldername" }, { "code": null, "e": 25457, "s": 25380, "text": "Step 3: Create a components folder and now Project Structure will look like:" }, { "code": null, "e": 25475, "s": 25457, "text": "Project Structure" }, { "code": null, "e": 25864, "s": 25475, "text": "This was basically the initial setup we require for our application. Now let us take a look at each of the components individually. Custom components reside in the components folder, with everything put together in the MainComponent.jsx, we will place this component inside App.js, which itself goes under the “root” DOM node, and everything inside this node will be managed by React DOM." }, { "code": null, "e": 25906, "s": 25864, "text": "We are going to develop three components:" }, { "code": null, "e": 25992, "s": 25906, "text": "Main Component: Responsible for fetch operation and state changes in the application." }, { "code": null, "e": 26066, "s": 25992, "text": "Search Bar: A search bar to get the user input for the show name/keyword." }, { "code": null, "e": 26134, "s": 26066, "text": "ShowInfoCard: A reusable component to display the show information." }, { "code": null, "e": 26260, "s": 26134, "text": "Step 4: In the MainComponent.jsx component, we have a state variable, data which will hold the response for the GraphQL API. " }, { "code": null, "e": 26302, "s": 26260, "text": "const [data, setData] = useState(Object);" }, { "code": null, "e": 26667, "s": 26302, "text": "To fetch the information, we make a call to the apiEndpoint, but first let us break the GraphQL query apart, in general, to form a query, you must specify fields within fields until those fields resolve to actual data. In this way, you ask for specific fields on objects and get back exactly what you asked for. The structure of any GraphQL query looks like this: " }, { "code": null, "e": 26707, "s": 26667, "text": "query {\n JSON objects to retrieve\n}\n" }, { "code": null, "e": 26844, "s": 26707, "text": "With our query variable, we are trying to fetch all the shows available, using name/keyword, which is passed as an argument with $term. " }, { "code": null, "e": 26875, "s": 26844, "text": "MainComponent.jsx (query part)" }, { "code": "const apiEndpoint = \"https://tmdb.apps.quintero.io/\";const query = ` query FetchData($term: String!){ tv{ search(term:$term){ edges{ node{ id originalName } } } } }`;", "e": 27178, "s": 26875, "text": null }, { "code": null, "e": 27745, "s": 27178, "text": "To make the request using Fetch API, we send the GraphQL query and variables as a JSON object to the endpoint. GraphQL endpoint expects the body of the request to be a stringified JSON object that contains query and variables parameters. When the request is complete, the promise is resolved with the response object. This object is basically a generic placeholder for various response formats. response.json() is used to extract the JSON object from the response, it returns a promise, which is again resolved and data is updated.MainComponent.jsx ( request part )" }, { "code": null, "e": 27780, "s": 27747, "text": "MainComponent.jsx (request part)" }, { "code": "const getData = (term) => { fetch(apiEndpoint, { method: \"POST\", headers: { \"Content-Type\": \"application/json\" }, body: JSON.stringify({ query, variables: { term } }) }) .then(res => res.json()) .then((data) => setData(data)) .catch(console.error); };", "e": 28142, "s": 27780, "text": null }, { "code": null, "e": 28187, "s": 28142, "text": "So finally our MainComponent.jsx looks like:" }, { "code": null, "e": 28205, "s": 28187, "text": "MainComponent.jsx" }, { "code": "import React, { useState } from \"react\";import SearchBar from \"./SearchBar\";import ShowInfoCard from \"./ShowInfoCard\"; function Main() { const [data, setData] = useState(Object); const apiEndpoint = \"https://tmdb.apps.quintero.io/\"; const query = ` query FetchData($term: String!){ tv{ search(term:$term){ edges{ node{ id originalName } } } } } `; const getData = (term) => { fetch(apiEndpoint, { method: \"POST\", headers: { \"Content-Type\": \"application/json\" }, body: JSON.stringify({ query, variables: { term } }) }) .then(res => res.json()) .then((data) => setData(data)) .catch(console.error); }; // console.log(data) return ( <div> <SearchBar getData={getData} /> {data.data ? data.data.tv.search.edges.map(({ node }) => ( <ShowInfoCard key={node.id} node={node} /> )) : <div></div> } </div> ); } export default Main;", "e": 29439, "s": 28205, "text": null }, { "code": null, "e": 29806, "s": 29439, "text": "Step 5: Now, moving on to the SearchBar component, which serves the purpose of receiving the user input for name/keyword. It is a simple component, with an input field of text type, and a button to make the search request. The state variable term is updated holds the input from user, and is passed as an argument to getData() when the user makes the search request." }, { "code": null, "e": 29820, "s": 29806, "text": "SearchBar.jsx" }, { "code": "import React, { useState } from \"react\"; function SearchBar({getData}){ const [term, setTerm] = useState(\"\"); const onChange = (e) =>{ setTerm(e.target.value) } const onSearch = () =>{ getData(term) } return( <div className=\"searchbar\"> <input placeholder=\"Enter the name...\" type=\"text\" value={term} onChange={(event) => {onChange(event)}} onKeyUp={(event) => {onChange(event)}} onPaste={(event) => {onChange(event)}} /> <button type=\"button\" className=\"searchButton\" onClick={onSearch}>Search </button> </div> );} export default SearchBar;", "e": 30525, "s": 29820, "text": null }, { "code": null, "e": 30797, "s": 30525, "text": "Step 6: Our last component, is a reusable UI component, which is basically a Card Component that receives node ( contains the show information ) as props, and just displays it in any chosen format. You can tweak the App.css file to understand the various design aspects. " }, { "code": null, "e": 30814, "s": 30797, "text": "ShowInfoCard.jsx" }, { "code": "import React from \"react\"; function ShowInfoCard({ node }) { return ( <div className=\"datacontainer\"> <div className=\"dataitem\"> Name : {node.originalName} </div> </div> );} export default ShowInfoCard;", "e": 31074, "s": 30814, "text": null }, { "code": null, "e": 31144, "s": 31074, "text": "Step 7: Finally, we need to include the MainComponent in App.js file:" }, { "code": null, "e": 31151, "s": 31144, "text": "App.js" }, { "code": "import './App.css';import React from \"react\";import Main from './components/MainComponent'; function App() { return ( <div className=\"App\"> <header className=\"App-header\"> <h2>Consuming a GraphQL API</h2> </header> <Main /> </div> );} export default App;", "e": 31438, "s": 31151, "text": null }, { "code": null, "e": 31533, "s": 31438, "text": "Step to run the application: To run the application on your system, run the following command:" }, { "code": null, "e": 31543, "s": 31533, "text": "npm start" }, { "code": null, "e": 31551, "s": 31543, "text": "Output:" }, { "code": null, "e": 31604, "s": 31551, "text": "GraphQL API: https://github.com/nerdsupremacist/tmdb" }, { "code": null, "e": 31674, "s": 31604, "text": "Fetch API: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API" }, { "code": null, "e": 31686, "s": 31674, "text": "anikakapoor" }, { "code": null, "e": 31702, "s": 31686, "text": "React-Questions" }, { "code": null, "e": 31710, "s": 31702, "text": "ReactJS" }, { "code": null, "e": 31727, "s": 31710, "text": "Web Technologies" }, { "code": null, "e": 31825, "s": 31727, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31867, "s": 31825, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 31902, "s": 31867, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 31960, "s": 31902, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 31987, "s": 31960, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 32006, "s": 31987, "text": "React-Router Hooks" }, { "code": null, "e": 32048, "s": 32006, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 32081, "s": 32048, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 32131, "s": 32081, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 32193, "s": 32131, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
C++ Conditional ? : Operator
Exp1 ? Exp2 : Exp3; where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon. The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression. The ? is called a ternary operator because it requires three operands and can be used to replace if-else statements, which have the following form − if(condition) { var = X; } else { var = Y; } For example, consider the following code − if(y < 10) { var = 30; } else { var = 40; } Above code can be rewritten like this − var = (y < 10) ? 30 : 40; Here, x is assigned the value of 30 if y is less than 10 and 40 if it is not. You can the try following example − #include <iostream> using namespace std; int main () { // Local variable declaration: int x, y = 10; x = (y < 10) ? 30 : 40; cout << "value of x: " << x << endl; return 0; } When the above code is compiled and executed, it produces the following result − value of x: 40 154 Lectures 11.5 hours Arnab Chakraborty 14 Lectures 57 mins Kaushik Roy Chowdhury 30 Lectures 12.5 hours Frahaan Hussain 54 Lectures 3.5 hours Frahaan Hussain 77 Lectures 5.5 hours Frahaan Hussain 12 Lectures 3.5 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2339, "s": 2318, "text": "Exp1 ? Exp2 : Exp3;\n" }, { "code": null, "e": 2678, "s": 2339, "text": "where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon. The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression." }, { "code": null, "e": 2827, "s": 2678, "text": "The ? is called a ternary operator because it requires three operands and can be used to replace if-else statements, which have the following form −" }, { "code": null, "e": 2879, "s": 2827, "text": "if(condition) {\n var = X;\n} else {\n var = Y;\n}\n" }, { "code": null, "e": 2922, "s": 2879, "text": "For example, consider the following code −" }, { "code": null, "e": 2974, "s": 2922, "text": "if(y < 10) { \n var = 30;\n} else {\n var = 40;\n}\n" }, { "code": null, "e": 3014, "s": 2974, "text": "Above code can be rewritten like this −" }, { "code": null, "e": 3041, "s": 3014, "text": "var = (y < 10) ? 30 : 40;\n" }, { "code": null, "e": 3155, "s": 3041, "text": "Here, x is assigned the value of 30 if y is less than 10 and 40 if it is not. You can the try following example −" }, { "code": null, "e": 3349, "s": 3155, "text": "#include <iostream>\nusing namespace std;\n \nint main () {\n // Local variable declaration:\n int x, y = 10;\n\n x = (y < 10) ? 30 : 40;\n cout << \"value of x: \" << x << endl;\n \n return 0;\n}" }, { "code": null, "e": 3430, "s": 3349, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3446, "s": 3430, "text": "value of x: 40\n" }, { "code": null, "e": 3483, "s": 3446, "text": "\n 154 Lectures \n 11.5 hours \n" }, { "code": null, "e": 3502, "s": 3483, "text": " Arnab Chakraborty" }, { "code": null, "e": 3534, "s": 3502, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 3557, "s": 3534, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 3593, "s": 3557, "text": "\n 30 Lectures \n 12.5 hours \n" }, { "code": null, "e": 3610, "s": 3593, "text": " Frahaan Hussain" }, { "code": null, "e": 3645, "s": 3610, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3662, "s": 3645, "text": " Frahaan Hussain" }, { "code": null, "e": 3697, "s": 3662, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3714, "s": 3697, "text": " Frahaan Hussain" }, { "code": null, "e": 3749, "s": 3714, "text": "\n 12 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3766, "s": 3749, "text": " Frahaan Hussain" }, { "code": null, "e": 3773, "s": 3766, "text": " Print" }, { "code": null, "e": 3784, "s": 3773, "text": " Add Notes" } ]
Python program to count total set bits in all number from 1 to n.
Given a positive integer n, then we change to its binary representation and count the total number of set bits. Input : n=3 Output : 4 Step 1: Input a positive integer data. Step 2: then convert it to binary form. Step 3: initialize the variable s = 0. Step 4: traverse every element and add. Step 5: display sum. # Python program to count set bits # in all numbers from 1 to n. def countbits(n): # initialize the counter c = 0 for i in range(1, n + 1): c += bitsetcount(i) return c def bitsetcount(x): if (x <= 0): return 0 return (0 if int(x % 2) == 0 else 1) + bitsetcount(int(x / 2)) # Driver program n = int(input("Enter the value of n")) print("Total set bit count is", countbits(n)) Enter the value of n10 Total set bit count is 17
[ { "code": null, "e": 1174, "s": 1062, "text": "Given a positive integer n, then we change to its binary representation and count the total number of set bits." }, { "code": null, "e": 1197, "s": 1174, "text": "Input : n=3\nOutput : 4" }, { "code": null, "e": 1376, "s": 1197, "text": "Step 1: Input a positive integer data.\nStep 2: then convert it to binary form.\nStep 3: initialize the variable s = 0.\nStep 4: traverse every element and add.\nStep 5: display sum." }, { "code": null, "e": 1800, "s": 1376, "text": "# Python program to count set bits\n# in all numbers from 1 to n.\ndef countbits(n):\n # initialize the counter\n c = 0\n for i in range(1, n + 1):\n c += bitsetcount(i)\n return c\n def bitsetcount(x):\n if (x <= 0):\n return 0\n return (0 if int(x % 2) == 0 else 1) + bitsetcount(int(x / 2))\n # Driver program\n n = int(input(\"Enter the value of n\"))\nprint(\"Total set bit count is\", countbits(n))" }, { "code": null, "e": 1849, "s": 1800, "text": "Enter the value of n10\nTotal set bit count is 17" } ]
Is Sudoku Valid | Practice | GeeksforGeeks
Given an incomplete Sudoku configuration in terms of a 9x9 2-D square matrix(mat[][]) the task to check if the current configuration is valid or not where a 0 represents an empty block. Note: Current valid configuration does not ensure validity of the final solved sudoku. Refer to this : https://en.wikipedia.org/wiki/Sudoku Example 1: Input: mat[][] = [ [3, 0, 6, 5, 0, 8, 4, 0, 0] [5, 2, 0, 0, 0, 0, 0, 0, 0] [0, 8, 7, 0, 0, 0, 0, 3, 1] [0, 0, 3, 0, 1, 0, 0, 8, 0] [9, 0, 0, 8, 6, 3, 0, 0, 5] [0, 5, 0, 0, 9, 0, 6, 0, 0] [1, 3, 0, 0, 0, 0, 2, 5, 0] [0, 0, 0, 0, 0, 0, 0, 7, 4] [0, 0, 5, 2, 0, 6, 3, 0, 0] ] Output: 1 Explaination: It is possible to have a proper sudoku. Your Task: You do not need to read input or print anything. Your task is to complete the function isValid() which takes mat[][] as input parameter and returns 1 if any solution is possible. Otherwise, returns 0. Expected Time Complexity: O(N2) Expected Auxiliary Space: O(1) Constraints: 0 ≤ mat[i][j] ≤ 9 0 patildhiren441 week ago JAVA - 3.08 static boolean isValidSudoku(int[][] board) { for(int i=0; i<board.length; i++){ HashSet<Integer> row = new HashSet<>(); HashSet<Integer> col = new HashSet<>(); HashSet<Integer> cube = new HashSet<>(); for(int j=0; j<board[0].length; j++){ if(board[i][j]!=0 && !row.add(board[i][j])){ return false; } if(board[j][i]!=0 && !col.add(board[j][i])){ return false; } int RowIndex = 3*(i/3); int ColIndex = 3*(i%3); if(board[RowIndex + j/3][ColIndex + j%3]!=0 && !cube.add(board[RowIndex + j/3][ColIndex + j%3])) return false; } } return true; } static int isValid(int mat[][]){ // code here if(isValidSudoku(mat)){ return 1; } return 0; } -1 patelneer4031 month ago int i,j; for(i=0;i<9;i++) { unordered_map<int,int>map; for(j=0;j<9;j++) { if(mat[i][j]==0) continue; map[mat[i][j]]++; if(map[mat[i][j]]>1 && mat[i][j]!=0) return 0; } } for(i=0;i<9;i++) { unordered_map<int,int>map; for(j=0;j<9;j++) { if(mat[j][i]==0) continue; map[mat[j][i]]++; if(map[mat[j][i]]>1 && mat[j][i]!=0) return 0; } } for(int k=0;k<9;k+=3) { for(int l=0;l<9;l+=3) { i=k; unordered_map<int,int>map; while(i!=k+3) { j=l; while(j!=l+3) { if(mat[i][j]==0){ j++; continue; } map[mat[i][j]]++; if(map[mat[i][j]] >1 && mat[i][j]!=0) return 0; j++; } i++; } } } return 1; 0 madhukartemba2 months ago INTUITIVE JAVA SOLUTION: class Solution{ static int isValid(int mat[][]) { HashSet<Integer> hs = new HashSet<>(); int n = 9; //Check for the rows for(int i=0; i<n; i++) { hs.clear(); for(int j=0; j<n; j++) { int x = mat[i][j]; if(x!=0) { if(hs.contains(x)) return 0; else hs.add(x); } } } //Check for the columns for(int i=0; i<n; i++) { hs.clear(); for(int j=0; j<n; j++) { int x = mat[j][i]; if(x!=0) { if(hs.contains(x)) return 0; else hs.add(x); } } } //Check for the sub-squares for(int i=0; i<n; i+=3) { for(int j=0; j<n; j+=3) { hs.clear(); for(int k=i; k<i+3; k++) { for(int l=j; l<j+3; l++) { int x = mat[k][l]; if(x!=0) { if(hs.contains(x)) return 0; else hs.add(x); } } } } } //All passed return 1; } } +2 palakkotwani28833 months ago Time Complexity:O(N^2) Space Complexity:O(1) //Checking if the same value exist in same row and same col bool isValid(vector<vector<int>>mat,int row,int col){ for(int i=0;i<9;i++){ if(i!=row && mat[i][col]==mat[row][col]) return false; if(i!=col && mat[row][i]==mat[row][col]) return false; if(((3*(row/3)+i/3)!=row ) &&((3*(col/3)+i%3)!=col) && mat[3*(row/3)+i/3][3*(col/3)+i%3]==mat[row][col]) return false; } return true; } int isValid(vector<vector<int>> mat){ // code here for(int i=0;i<9;i++){ for(int j=0;j<9;j++){ if(mat[i][j]==0) continue; if( isValid(mat,i,j)) continue; else{ return 0; } } } return 1; } }; +1 utsavbhatia3 months ago class Solution{ static int isValid(int mat[][]){ HashSet<String> set = new HashSet<>(); for(int i=0;i<9;++i) { for(int j=0;j<9;++j) { if(mat[i][j]!=0) { if(!set.add(mat[i][j]+"r"+i) || !set.add(mat[i][j]+"c"+j) || !set.add(mat[i][j]+"b"+(i/3)+"_"+(j/3))) return 0; } } } return 1; } } 0 abdulkhn83 months ago Soultion in Java - ----------------- class Solution{ static int isValid(int mat[][]){ // code here for(int row=0;row<9;row++) { for(int col=0;col<9;col++) { if(mat[row][col] != 0 && !isSafe(mat,row,col)) { return 0; } } } return 1; } static boolean isSafe(int mat[][],int rowIndex,int colIndex) { //row and col check for(int i=0;i<9;i++) { //row check if(mat[rowIndex][colIndex]==mat[rowIndex][i] && colIndex!=i) { return false; } //col check if(mat[rowIndex][colIndex]==mat[i][colIndex] && rowIndex!=i) { return false; } } //current board check int r = rowIndex-rowIndex%3; int c = colIndex-colIndex%3; for( int i=0;i< 3;i++) { for(int j=0;j<3;j++) { if(mat[rowIndex][colIndex]==mat[r+i][c+j] && rowIndex!=r+i && colIndex!=c+j) { return false; } } } return true; }} 0 amanpandey30073 months ago int isValid(vector<vector<int>> mat) { for(int i=0;i<9;i++) { vector<int>arr(10,-1); for(int j=0;j<9;j++) { if(mat[i][j]==0) continue; else if(arr[mat[i][j]]==-1) arr[mat[i][j]]=mat[i][j]; else return 0; } } for(int j=0;j<9;j++) { vector<int>arr(10,-1); for(int i=0;i<9;i++) { if(mat[i][j]==0) continue; else if(arr[mat[i][j]]==-1) arr[mat[i][j]]=mat[i][j]; else return 0; } } for(int i=0;i<9;i+=3) { for(int j=0;j<9;j+=3) { vector<int>arr(10,-1); for(int a=0;a<3;a++) { for(int b=0;b<3;b++) { if(mat[i+a][j+b]==0) continue; else if(arr[mat[i+a][j+b]]==-1) arr[mat[i+a][j+b]]=mat[i+a][j+b]; else return 0; } } } } return 1; } 0 krishna1saini13 months ago int isValid(vector<vector<int>> mat){ // code here int visit[10] = {0}; //row for(int i=0 ; i<9 ; i++) { for(int j=0 ; j<9 ; j++) { if(mat[i][j] == 0) continue; if(visit[mat[i][j]]) return 0; visit[mat[i][j]] = 1; } for(int i=0 ; i<10 ; i++) visit[i] = 0; } //column for(int i=0 ; i<9 ; i++) { for(int j=0 ; j<9 ; j++) { if(mat[j][i] == 0) continue; if(visit[mat[j][i]]) return 0; visit[mat[j][i]] = 1; } for(int i=0 ; i<10 ; i++) visit[i] = 0; } for(int i=0 ; i<10 ; i++) visit[i] = 0; //3*3 int rs=0 , re = 3 , cs = 0 , ce = 3; while( 1 ) { int i , j; for( i = rs ; i<re ; i++) { for( j=cs ; j<ce ; j++) { if(mat[i][j] == 0) continue; if(visit[mat[i][j]]) return 0; visit[mat[i][j]] = 1; } } for(int i=0 ; i<10 ; i++) visit[i] = 0; cs = ce; ce = cs+3; if(cs == 9 && re!=9) { rs = re; re = rs+3; cs = 0; ce = cs+3; } else if(cs==9 && re==9) { return 1; } } } 0 rounkagrwl3 months ago C++ , Time - O(N*N), Space - O(1) #include <bits/stdc++.h> using namespace std; // User function Template for C++ class Solution{ public: int isValid(vector<vector<int>> mat){ int maxi = 15; int n=9; //setting the matrix for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ int temp = mat[i][j]%maxi; if(temp){ mat[i][temp-1]+=maxi; if(mat[i][temp-1]/maxi>1) return false;} } } //resetting the matrix for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ mat[i][j] = mat[i][j]%maxi; } } //setting the matrix for(int j=0;j<n;j++){ for(int i=0;i<n;i++){ int temp = mat[i][j]%maxi; if(temp){ mat[temp-1][j]+=maxi; if(mat[temp-1][j]/maxi>1) return false;} } } //Resetting the matrix for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ mat[i][j] = mat[i][j]%maxi; } } //setting the matrix for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ int i1 = i/3; int j1= j/3; int in; if(i1==0) in = j1; if(i1==1) in = 3+j1; if(i1==2) in = 6+j1; int temp = mat[i][j]%maxi; if(temp){ mat[in][temp-1]+=maxi; if(mat[in][temp-1]/maxi>1) return false;} } } return true; } }; // { Driver Code Starts. int main(){ int t; cin>>t; while(t--){ vector<vector<int>> mat(9, vector<int>(9, 0)); for(int i = 0;i < 81;i++) cin>>mat[i/9][i%9]; Solution ob; cout<<ob.isValid(mat)<<"\n"; } return 0; } // } Driver Code Ends 0 choudharyaakash0663 months ago #Performing Simple Checks class Solution: def isValid(self, mat): # code here rowCheck = {0:[], 1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], 8:[]} colCheck = {0:[], 1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], 8:[]} gridCheck = {0:[], 1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], 8:[]} for i in range(len(mat)): for j in range(len(mat)): check = mat[i][j] if check != 0: if check in rowCheck[i] or check in colCheck[j]: return 0 rowCheck[i].append(check) colCheck[j].append(check) grid = (i//3)*3 + (j//3) if check in gridCheck[grid]: return 0 gridCheck[grid].append(check) return 1 We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 566, "s": 238, "text": "Given an incomplete Sudoku configuration in terms of a 9x9 2-D square matrix(mat[][]) the task to check if the current configuration is valid or not where a 0 represents an empty block.\nNote: Current valid configuration does not ensure validity of the final solved sudoku. \nRefer to this : https://en.wikipedia.org/wiki/Sudoku" }, { "code": null, "e": 577, "s": 566, "text": "Example 1:" }, { "code": null, "e": 914, "s": 577, "text": "Input: mat[][] = [\n[3, 0, 6, 5, 0, 8, 4, 0, 0]\n[5, 2, 0, 0, 0, 0, 0, 0, 0]\n[0, 8, 7, 0, 0, 0, 0, 3, 1]\n[0, 0, 3, 0, 1, 0, 0, 8, 0]\n[9, 0, 0, 8, 6, 3, 0, 0, 5]\n[0, 5, 0, 0, 9, 0, 6, 0, 0]\n[1, 3, 0, 0, 0, 0, 2, 5, 0]\n[0, 0, 0, 0, 0, 0, 0, 7, 4]\n[0, 0, 5, 2, 0, 6, 3, 0, 0]\n]\nOutput: 1\nExplaination: It is possible to have a\nproper sudoku." }, { "code": null, "e": 1126, "s": 914, "text": "Your Task:\nYou do not need to read input or print anything. Your task is to complete the function isValid() which takes mat[][] as input parameter and returns 1 if any solution is possible. Otherwise, returns 0." }, { "code": null, "e": 1189, "s": 1126, "text": "Expected Time Complexity: O(N2)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1220, "s": 1189, "text": "Constraints:\n0 ≤ mat[i][j] ≤ 9" }, { "code": null, "e": 1222, "s": 1220, "text": "0" }, { "code": null, "e": 1246, "s": 1222, "text": "patildhiren441 week ago" }, { "code": null, "e": 1260, "s": 1246, "text": "JAVA - 3.08 " }, { "code": null, "e": 2308, "s": 1260, "text": "static boolean isValidSudoku(int[][] board) {\n \n for(int i=0; i<board.length; i++){\n \n HashSet<Integer> row = new HashSet<>();\n HashSet<Integer> col = new HashSet<>();\n HashSet<Integer> cube = new HashSet<>();\n \n for(int j=0; j<board[0].length; j++){\n \n if(board[i][j]!=0 && !row.add(board[i][j])){\n return false;\n }\n \n if(board[j][i]!=0 && !col.add(board[j][i])){\n return false;\n }\n \n int RowIndex = 3*(i/3);\n int ColIndex = 3*(i%3);\n if(board[RowIndex + j/3][ColIndex + j%3]!=0 && !cube.add(board[RowIndex + j/3][ColIndex + j%3]))\n return false;\n\n }\n }\n return true;\n }\n \n static int isValid(int mat[][]){\n // code here\n \n if(isValidSudoku(mat)){\n return 1;\n }\n return 0;\n }" }, { "code": null, "e": 2311, "s": 2308, "text": "-1" }, { "code": null, "e": 2335, "s": 2311, "text": "patelneer4031 month ago" }, { "code": null, "e": 3830, "s": 2335, "text": "int i,j; for(i=0;i<9;i++) { unordered_map<int,int>map; for(j=0;j<9;j++) { if(mat[i][j]==0) continue; map[mat[i][j]]++; if(map[mat[i][j]]>1 && mat[i][j]!=0) return 0; } } for(i=0;i<9;i++) { unordered_map<int,int>map; for(j=0;j<9;j++) { if(mat[j][i]==0) continue; map[mat[j][i]]++; if(map[mat[j][i]]>1 && mat[j][i]!=0) return 0; } } for(int k=0;k<9;k+=3) { for(int l=0;l<9;l+=3) { i=k; unordered_map<int,int>map; while(i!=k+3) { j=l; while(j!=l+3) { if(mat[i][j]==0){ j++; continue; } map[mat[i][j]]++; if(map[mat[i][j]] >1 && mat[i][j]!=0) return 0; j++; } i++; } } } return 1; " }, { "code": null, "e": 3832, "s": 3830, "text": "0" }, { "code": null, "e": 3858, "s": 3832, "text": "madhukartemba2 months ago" }, { "code": null, "e": 3884, "s": 3858, "text": "INTUITIVE JAVA SOLUTION: " }, { "code": null, "e": 5465, "s": 3884, "text": "class Solution{\n static int isValid(int mat[][])\n {\n \n HashSet<Integer> hs = new HashSet<>();\n \n int n = 9;\n \n //Check for the rows\n for(int i=0; i<n; i++)\n {\n hs.clear();\n for(int j=0; j<n; j++)\n {\n int x = mat[i][j];\n \n if(x!=0)\n {\n if(hs.contains(x)) return 0;\n else hs.add(x);\n }\n }\n }\n \n //Check for the columns\n for(int i=0; i<n; i++)\n {\n hs.clear();\n for(int j=0; j<n; j++)\n {\n int x = mat[j][i];\n \n if(x!=0)\n {\n if(hs.contains(x)) return 0;\n else hs.add(x);\n }\n }\n }\n \n //Check for the sub-squares\n for(int i=0; i<n; i+=3)\n {\n for(int j=0; j<n; j+=3)\n {\n hs.clear();\n for(int k=i; k<i+3; k++)\n {\n for(int l=j; l<j+3; l++)\n {\n int x = mat[k][l];\n \n if(x!=0)\n {\n if(hs.contains(x)) return 0;\n else hs.add(x);\n }\n }\n }\n }\n }\n \n \n //All passed\n return 1;\n \n \n }\n}" }, { "code": null, "e": 5468, "s": 5465, "text": "+2" }, { "code": null, "e": 5497, "s": 5468, "text": "palakkotwani28833 months ago" }, { "code": null, "e": 5520, "s": 5497, "text": "Time Complexity:O(N^2)" }, { "code": null, "e": 5542, "s": 5520, "text": "Space Complexity:O(1)" }, { "code": null, "e": 6329, "s": 5544, "text": "//Checking if the same value exist in same row and same col\nbool isValid(vector<vector<int>>mat,int row,int col){\n for(int i=0;i<9;i++){\n if(i!=row && mat[i][col]==mat[row][col])\n return false;\n if(i!=col && mat[row][i]==mat[row][col])\n return false;\n if(((3*(row/3)+i/3)!=row ) &&((3*(col/3)+i%3)!=col) && mat[3*(row/3)+i/3][3*(col/3)+i%3]==mat[row][col])\n return false;\n }\n return true;\n}\n\n int isValid(vector<vector<int>> mat){\n // code here\n for(int i=0;i<9;i++){\n for(int j=0;j<9;j++){\nif(mat[i][j]==0)\ncontinue;\n if( isValid(mat,i,j))\n continue;\n else{\n \n \n return 0;\n }\n }\n }\n \n return 1;\n }\n};" }, { "code": null, "e": 6332, "s": 6329, "text": "+1" }, { "code": null, "e": 6356, "s": 6332, "text": "utsavbhatia3 months ago" }, { "code": null, "e": 6821, "s": 6356, "text": "class Solution{\n static int isValid(int mat[][]){\n HashSet<String> set = new HashSet<>();\n for(int i=0;i<9;++i) {\n for(int j=0;j<9;++j) {\n if(mat[i][j]!=0) {\n if(!set.add(mat[i][j]+\"r\"+i) ||\n !set.add(mat[i][j]+\"c\"+j) ||\n !set.add(mat[i][j]+\"b\"+(i/3)+\"_\"+(j/3)))\n return 0;\n }\n }\n }\n return 1;\n }\n}" }, { "code": null, "e": 6823, "s": 6821, "text": "0" }, { "code": null, "e": 6845, "s": 6823, "text": "abdulkhn83 months ago" }, { "code": null, "e": 6864, "s": 6845, "text": "Soultion in Java -" }, { "code": null, "e": 6882, "s": 6864, "text": "-----------------" }, { "code": null, "e": 8087, "s": 6884, "text": "class Solution{ static int isValid(int mat[][]){ // code here for(int row=0;row<9;row++) { for(int col=0;col<9;col++) { if(mat[row][col] != 0 && !isSafe(mat,row,col)) { return 0; } } } return 1; } static boolean isSafe(int mat[][],int rowIndex,int colIndex) { //row and col check for(int i=0;i<9;i++) { //row check if(mat[rowIndex][colIndex]==mat[rowIndex][i] && colIndex!=i) { return false; } //col check if(mat[rowIndex][colIndex]==mat[i][colIndex] && rowIndex!=i) { return false; } } //current board check int r = rowIndex-rowIndex%3; int c = colIndex-colIndex%3; for( int i=0;i< 3;i++) { for(int j=0;j<3;j++) { if(mat[rowIndex][colIndex]==mat[r+i][c+j] && rowIndex!=r+i && colIndex!=c+j) { return false; } } } return true; }}" }, { "code": null, "e": 8089, "s": 8087, "text": "0" }, { "code": null, "e": 8116, "s": 8089, "text": "amanpandey30073 months ago" }, { "code": null, "e": 9403, "s": 8116, "text": "int isValid(vector<vector<int>> mat) { for(int i=0;i<9;i++) { vector<int>arr(10,-1); for(int j=0;j<9;j++) { if(mat[i][j]==0) continue; else if(arr[mat[i][j]]==-1) arr[mat[i][j]]=mat[i][j]; else return 0; } } for(int j=0;j<9;j++) { vector<int>arr(10,-1); for(int i=0;i<9;i++) { if(mat[i][j]==0) continue; else if(arr[mat[i][j]]==-1) arr[mat[i][j]]=mat[i][j]; else return 0; } } for(int i=0;i<9;i+=3) { for(int j=0;j<9;j+=3) { vector<int>arr(10,-1); for(int a=0;a<3;a++) { for(int b=0;b<3;b++) { if(mat[i+a][j+b]==0) continue; else if(arr[mat[i+a][j+b]]==-1) arr[mat[i+a][j+b]]=mat[i+a][j+b]; else return 0; } } } } return 1; }" }, { "code": null, "e": 9405, "s": 9403, "text": "0" }, { "code": null, "e": 9432, "s": 9405, "text": "krishna1saini13 months ago" }, { "code": null, "e": 11157, "s": 9432, "text": " int isValid(vector<vector<int>> mat){ // code here int visit[10] = {0}; //row for(int i=0 ; i<9 ; i++) { for(int j=0 ; j<9 ; j++) { if(mat[i][j] == 0) continue; if(visit[mat[i][j]]) return 0; visit[mat[i][j]] = 1; } for(int i=0 ; i<10 ; i++) visit[i] = 0; } //column for(int i=0 ; i<9 ; i++) { for(int j=0 ; j<9 ; j++) { if(mat[j][i] == 0) continue; if(visit[mat[j][i]]) return 0; visit[mat[j][i]] = 1; } for(int i=0 ; i<10 ; i++) visit[i] = 0; } for(int i=0 ; i<10 ; i++) visit[i] = 0; //3*3 int rs=0 , re = 3 , cs = 0 , ce = 3; while( 1 ) { int i , j; for( i = rs ; i<re ; i++) { for( j=cs ; j<ce ; j++) { if(mat[i][j] == 0) continue; if(visit[mat[i][j]]) return 0; visit[mat[i][j]] = 1; } } for(int i=0 ; i<10 ; i++) visit[i] = 0; cs = ce; ce = cs+3; if(cs == 9 && re!=9) { rs = re; re = rs+3; cs = 0; ce = cs+3; } else if(cs==9 && re==9) { return 1; } } }" }, { "code": null, "e": 11159, "s": 11157, "text": "0" }, { "code": null, "e": 11182, "s": 11159, "text": "rounkagrwl3 months ago" }, { "code": null, "e": 11219, "s": 11184, "text": "\nC++ , Time - O(N*N), Space - O(1)" }, { "code": null, "e": 13235, "s": 11219, "text": "#include <bits/stdc++.h>\nusing namespace std;\n\n\n// User function Template for C++\n\nclass Solution{\npublic:\n int isValid(vector<vector<int>> mat){\n int maxi = 15;\n int n=9;\n \n //setting the matrix\n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n \n int temp = mat[i][j]%maxi;\n if(temp){\n mat[i][temp-1]+=maxi;\n if(mat[i][temp-1]/maxi>1) \n return false;}\n }\n }\n \n //resetting the matrix\n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n mat[i][j] = mat[i][j]%maxi;\n }\n }\n \n //setting the matrix\n for(int j=0;j<n;j++){\n for(int i=0;i<n;i++){\n \n int temp = mat[i][j]%maxi;\n if(temp){\n mat[temp-1][j]+=maxi;\n if(mat[temp-1][j]/maxi>1)\n return false;}\n }\n }\n //Resetting the matrix\n \n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n mat[i][j] = mat[i][j]%maxi;\n }\n }\n \n \n //setting the matrix\n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n int i1 = i/3;\n int j1= j/3;\n int in;\n if(i1==0) in = j1;\n if(i1==1) in = 3+j1;\n if(i1==2) in = 6+j1;\n int temp = mat[i][j]%maxi;\n if(temp){\n mat[in][temp-1]+=maxi;\n if(mat[in][temp-1]/maxi>1) \n return false;}\n }\n }\n \n return true;\n }\n};\n\n// { Driver Code Starts.\n\nint main(){\n int t;\n cin>>t;\n while(t--){\n vector<vector<int>> mat(9, vector<int>(9, 0));\n for(int i = 0;i < 81;i++)\n cin>>mat[i/9][i%9];\n \n Solution ob;\n cout<<ob.isValid(mat)<<\"\\n\";\n }\n return 0;\n" }, { "code": null, "e": 13260, "s": 13235, "text": "} // } Driver Code Ends" }, { "code": null, "e": 13262, "s": 13260, "text": "0" }, { "code": null, "e": 13293, "s": 13262, "text": "choudharyaakash0663 months ago" }, { "code": null, "e": 14182, "s": 13293, "text": "#Performing Simple Checks\nclass Solution:\n def isValid(self, mat):\n # code here\n rowCheck = {0:[], 1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], 8:[]}\n colCheck = {0:[], 1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], 8:[]}\n gridCheck = {0:[], 1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], 8:[]}\n \n for i in range(len(mat)):\n for j in range(len(mat)):\n check = mat[i][j]\n if check != 0:\n if check in rowCheck[i] or check in colCheck[j]:\n return 0\n rowCheck[i].append(check)\n colCheck[j].append(check)\n \n grid = (i//3)*3 + (j//3)\n \n if check in gridCheck[grid]:\n return 0\n gridCheck[grid].append(check)\n return 1" }, { "code": null, "e": 14328, "s": 14182, "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": 14364, "s": 14328, "text": " Login to access your submissions. " }, { "code": null, "e": 14374, "s": 14364, "text": "\nProblem\n" }, { "code": null, "e": 14384, "s": 14374, "text": "\nContest\n" }, { "code": null, "e": 14447, "s": 14384, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 14595, "s": 14447, "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": 14803, "s": 14595, "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": 14909, "s": 14803, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Dangling, Void, Null and Wild Pointers in C/C++
Dangling pointer is a pointer pointing to a memory location that has been freed (or deleted). There are different ways where Pointer acts as dangling pointer The pointer pointing to local variable becomes dangling when local variable is not static. int *show(void) { int n = 76; /* ... */ return &n; } Output of this program will be garbage address. #include <stdlib.h> #include <stdio.h> int main() { float *p = (float *)malloc(sizeof(float)); //dynamic memory allocation. free(p); //after calling free() p becomes a dangling pointer p = NULL; //now p no more a dangling pointer. } int main() { int *p //some code// { int c; p=&c; } //some code// //p is dangling pointer here. } Void pointer in C is a pointer which is not associate with any data types. It points to some data location in storage means points to the address of variables. It is also called general purpose pointer. It has some limitations Pointer arithmetic is not possible of void pointer due to its concrete size. It can’t be used as dereferenced. Here is a simple example #include<stdlib.h> int main() { int a = 7; float b = 7.6; void *p; p = &a; printf("Integer variable is = %d", *( (int*) p) ); p = &b; printf("\nFloat variable is = %f", *( (float*) p) ); return 0; } Integer variable is = 7 Float variable is = 7.600000 Begin Initialize a variable a with integer value and variable b with float value. Declare a void pointer p. (int*)p = type casting of void. p = &b mean void pointer p is now float. (float*)p = type casting of void. Print the value. End. Null pointer is a pointer which points nothing. Some uses of null pointer are: To initialize a pointer variable when that pointer variable isn’t assigned any valid memory address yet. To pass a null pointer to a function argument if we don’t want to pass any valid memory address. To check for null pointer before accessing any pointer variable. So that, we can perform error handling in pointer related code e.g. dereference pointer variable only if it’s not NULL. Live Demo #include<iostream> #include <stdio.h> int main() { int *p= NULL;//initialize the pointer as null. printf("The value of pointer is %u",p); return 0; } The value of pointer is 0. Wild pointers are pointers those are point to some arbitrary memory location. (not even NULL) int main() { int *ptr; //wild pointer *ptr = 5; }
[ { "code": null, "e": 1220, "s": 1062, "text": "Dangling pointer is a pointer pointing to a memory location that has been freed (or deleted). There are different ways where Pointer acts as dangling pointer" }, { "code": null, "e": 1311, "s": 1220, "text": "The pointer pointing to local variable becomes dangling when local variable is not static." }, { "code": null, "e": 1367, "s": 1311, "text": "int *show(void) {\n int n = 76; /* ... */ return &n;\n}" }, { "code": null, "e": 1415, "s": 1367, "text": "Output of this program will be garbage address." }, { "code": null, "e": 1660, "s": 1415, "text": "#include <stdlib.h> #include <stdio.h> int main() {\n float *p = (float *)malloc(sizeof(float));\n //dynamic memory allocation. free(p);\n //after calling free() p becomes a dangling pointer p = NULL;\n //now p no more a dangling pointer.\n}" }, { "code": null, "e": 1775, "s": 1660, "text": "int main() {\n int *p //some code// {\n int c; p=&c;\n }\n //some code//\n //p is dangling pointer here.\n}" }, { "code": null, "e": 1978, "s": 1775, "text": "Void pointer in C is a pointer which is not associate with any data types. It points to some data location in storage means points to the address of variables. It is also called general purpose pointer." }, { "code": null, "e": 2002, "s": 1978, "text": "It has some limitations" }, { "code": null, "e": 2079, "s": 2002, "text": "Pointer arithmetic is not possible of void pointer due to its concrete size." }, { "code": null, "e": 2113, "s": 2079, "text": "It can’t be used as dereferenced." }, { "code": null, "e": 2138, "s": 2113, "text": "Here is a simple example" }, { "code": null, "e": 2364, "s": 2138, "text": "#include<stdlib.h>\nint main() {\n int a = 7;\n float b = 7.6;\n void *p;\n p = &a;\n printf(\"Integer variable is = %d\", *( (int*) p) );\n p = &b;\n printf(\"\\nFloat variable is = %f\", *( (float*) p) );\n return 0;\n}" }, { "code": null, "e": 2417, "s": 2364, "text": "Integer variable is = 7\nFloat variable is = 7.600000" }, { "code": null, "e": 2672, "s": 2417, "text": "Begin\n Initialize a variable a with integer value and variable b with float value.\n Declare a void pointer p.\n (int*)p = type casting of void.\n p = &b mean void pointer p is now float.\n (float*)p = type casting of void.\n Print the value.\nEnd." }, { "code": null, "e": 2751, "s": 2672, "text": "Null pointer is a pointer which points nothing.\nSome uses of null pointer are:" }, { "code": null, "e": 2856, "s": 2751, "text": "To initialize a pointer variable when that pointer variable isn’t assigned any valid memory address yet." }, { "code": null, "e": 2953, "s": 2856, "text": "To pass a null pointer to a function argument if we don’t want to pass any valid memory address." }, { "code": null, "e": 3138, "s": 2953, "text": "To check for null pointer before accessing any pointer variable. So that, we can perform error handling in pointer related code e.g. dereference pointer variable only if it’s not NULL." }, { "code": null, "e": 3149, "s": 3138, "text": " Live Demo" }, { "code": null, "e": 3308, "s": 3149, "text": "#include<iostream>\n#include <stdio.h>\nint main() {\n int *p= NULL;//initialize the pointer as null.\n printf(\"The value of pointer is %u\",p);\n return 0;\n}" }, { "code": null, "e": 3335, "s": 3308, "text": "The value of pointer is 0." }, { "code": null, "e": 3429, "s": 3335, "text": "Wild pointers are pointers those are point to some arbitrary memory location. (not even NULL)" }, { "code": null, "e": 3485, "s": 3429, "text": "int main() {\n int *ptr; //wild pointer\n *ptr = 5;\n}" } ]
Maximum difference between two elements such that larger element appears after the smaller number in C
We are given with an array of integers of size N. The array consists of integers in random order. The task is to find the maximum difference between two elements such that the larger element appears after the smaller number. That is Arr[j]-Arr[i] is maximum such that j>i. Input Arr[] = { 2,1,3,8,3,19,21}. Output −The maximum difference between two elements such that the larger element appears after the smaller number − 20 Explanation − The maximum difference is between 21 and 1 and 21 appears after 1 in the array. Input Arr[] = {18, 2,8,1,2,3,2,6 }. Output −The maximum difference between two elements such that the larger element appears after the smaller number − 6 Explanation − The maximum difference is between 8 and 2 and 8 appears after 2 in the array. Declare an array of integers which contains pairs of sides of rectangle.( Arr[] ) Declare an array of integers which contains pairs of sides of rectangle.( Arr[] ) Create a variable to store the size of the array. (n) Create a variable to store the size of the array. (n) The function maxArea(int arr[],int n) is used to calculate the maximum area for rectangle. It takes an input array and its size as arguments. The function maxArea(int arr[],int n) is used to calculate the maximum area for rectangle. It takes an input array and its size as arguments. Inside maxArea() we declared an array Dim[2] two store highest two sides found after traversing the sorted array (in descending order) arr[]. Inside maxArea() we declared an array Dim[2] two store highest two sides found after traversing the sorted array (in descending order) arr[]. As arr[] is sorted in descending order the highest 4 sides must be in the beginning. We will iterate arr[] such that a pair of sides is found. As arr[] is sorted in descending order the highest 4 sides must be in the beginning. We will iterate arr[] such that a pair of sides is found. Initialize Dim[] with 0 at first. Initialize Dim[] with 0 at first. Inside the while loop we put the condition that it continues till j<2 that there are no values found for dim[0] and dim[1] or the end of arr[] is reached. (i<n). Inside the while loop we put the condition that it continues till j<2 that there are no values found for dim[0] and dim[1] or the end of arr[] is reached. (i<n). If a pair of such sides is found, ( if(arr[i]==arr[i+1]) ), then store it in dim[j] and increment j for next side. If a pair of such sides is found, ( if(arr[i]==arr[i+1]) ), then store it in dim[j] and increment j for next side. Return the result as a product of dim[0] and dim[1]. Return the result as a product of dim[0] and dim[1]. Note − sort(arr,n) is supposed to sort arr in descending order. Note − sort(arr,n) is supposed to sort arr in descending order. Live Demo #include <stdio.h> int maxDiff(int arr[], int n){ // Maximum difference found so far int MD = arr[1] - arr[0]; // Minimum number visited so far int min = arr[0]; for(int i = 1; i < n; i++){ if (arr[i] - min > MD) MD = arr[i] - min; if (arr[i] < min) min = arr[i]; } return MD; } /* Driver program to test above function */ int main(){ int arr[] = {2,5,7,3,4,12}; int n=6; // Function calling printf("Maximum difference is : %d ",maxDiff(arr, n)); return 0; } If we run the above code it will generate the following output − The maximum difference between two elements such that the larger element appears after the smaller number : 10
[ { "code": null, "e": 1335, "s": 1062, "text": "We are given with an array of integers of size N. The array consists of integers in random order. The task is to find the maximum difference between two elements such that the larger element appears after the smaller number. That is Arr[j]-Arr[i] is maximum such that j>i." }, { "code": null, "e": 1342, "s": 1335, "text": "Input " }, { "code": null, "e": 1370, "s": 1342, "text": "Arr[] = { 2,1,3,8,3,19,21}." }, { "code": null, "e": 1489, "s": 1370, "text": "Output −The maximum difference between two elements such that the larger element appears after the smaller number − 20" }, { "code": null, "e": 1583, "s": 1489, "text": "Explanation − The maximum difference is between 21 and 1 and 21 appears after 1 in the array." }, { "code": null, "e": 1590, "s": 1583, "text": "Input " }, { "code": null, "e": 1620, "s": 1590, "text": "Arr[] = {18, 2,8,1,2,3,2,6 }." }, { "code": null, "e": 1738, "s": 1620, "text": "Output −The maximum difference between two elements such that the larger element appears after the smaller number − 6" }, { "code": null, "e": 1830, "s": 1738, "text": "Explanation − The maximum difference is between 8 and 2 and 8 appears after 2 in the array." }, { "code": null, "e": 1912, "s": 1830, "text": "Declare an array of integers which contains pairs of sides of rectangle.( Arr[] )" }, { "code": null, "e": 1994, "s": 1912, "text": "Declare an array of integers which contains pairs of sides of rectangle.( Arr[] )" }, { "code": null, "e": 2048, "s": 1994, "text": "Create a variable to store the size of the array. (n)" }, { "code": null, "e": 2102, "s": 2048, "text": "Create a variable to store the size of the array. (n)" }, { "code": null, "e": 2244, "s": 2102, "text": "The function maxArea(int arr[],int n) is used to calculate the maximum area for rectangle. It takes an input array and its size as arguments." }, { "code": null, "e": 2386, "s": 2244, "text": "The function maxArea(int arr[],int n) is used to calculate the maximum area for rectangle. It takes an input array and its size as arguments." }, { "code": null, "e": 2528, "s": 2386, "text": "Inside maxArea() we declared an array Dim[2] two store highest two sides found after traversing the sorted array (in descending order) arr[]." }, { "code": null, "e": 2670, "s": 2528, "text": "Inside maxArea() we declared an array Dim[2] two store highest two sides found after traversing the sorted array (in descending order) arr[]." }, { "code": null, "e": 2813, "s": 2670, "text": "As arr[] is sorted in descending order the highest 4 sides must be in the beginning. We will iterate arr[] such that a pair of sides is found." }, { "code": null, "e": 2956, "s": 2813, "text": "As arr[] is sorted in descending order the highest 4 sides must be in the beginning. We will iterate arr[] such that a pair of sides is found." }, { "code": null, "e": 2990, "s": 2956, "text": "Initialize Dim[] with 0 at first." }, { "code": null, "e": 3024, "s": 2990, "text": "Initialize Dim[] with 0 at first." }, { "code": null, "e": 3186, "s": 3024, "text": "Inside the while loop we put the condition that it continues till j<2 that there are no values found for dim[0] and dim[1] or the end of arr[] is reached. (i<n)." }, { "code": null, "e": 3348, "s": 3186, "text": "Inside the while loop we put the condition that it continues till j<2 that there are no values found for dim[0] and dim[1] or the end of arr[] is reached. (i<n)." }, { "code": null, "e": 3463, "s": 3348, "text": "If a pair of such sides is found, ( if(arr[i]==arr[i+1]) ), then store it in dim[j] and increment j for next side." }, { "code": null, "e": 3578, "s": 3463, "text": "If a pair of such sides is found, ( if(arr[i]==arr[i+1]) ), then store it in dim[j] and increment j for next side." }, { "code": null, "e": 3631, "s": 3578, "text": "Return the result as a product of dim[0] and dim[1]." }, { "code": null, "e": 3684, "s": 3631, "text": "Return the result as a product of dim[0] and dim[1]." }, { "code": null, "e": 3748, "s": 3684, "text": "Note − sort(arr,n) is supposed to sort arr in descending order." }, { "code": null, "e": 3812, "s": 3748, "text": "Note − sort(arr,n) is supposed to sort arr in descending order." }, { "code": null, "e": 3823, "s": 3812, "text": " Live Demo" }, { "code": null, "e": 4348, "s": 3823, "text": "#include <stdio.h>\nint maxDiff(int arr[], int n){\n // Maximum difference found so far\n int MD = arr[1] - arr[0];\n // Minimum number visited so far\n int min = arr[0];\n for(int i = 1; i < n; i++){\n if (arr[i] - min > MD)\n MD = arr[i] - min;\n if (arr[i] < min)\n min = arr[i];\n }\n return MD;\n}\n/* Driver program to test above function */\nint main(){\n int arr[] = {2,5,7,3,4,12};\n int n=6;\n // Function calling\n printf(\"Maximum difference is : %d \",maxDiff(arr, n));\n return 0;\n}" }, { "code": null, "e": 4413, "s": 4348, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 4524, "s": 4413, "text": "The maximum difference between two elements such that the larger element appears after the smaller number : 10" } ]
How to Generate MS Word Tables With Python | by Dardan Xhymshiti | Towards Data Science
Whenever automation is discussed, Python is often mentioned. The easy to use syntax, huge number of libraries and the script oriented language construction make Python excel on automation compared to other programming languages. Small and big companies generate reports daily with Microsoft Office tools such as Word and Excel. In this article, I’ll provide an end-to-end explanation on generating tables of data in MS Word through Python. I will consider a scenario where we have a number of news articles and we need to generate a Word document with tables containing stats extracted from these articles. Some of these stats are: number of words, number of sentences and average word length. For this example, I’ve used Python 3.7. The only dependency you need to install is python-docx. You can install this dependency by submitting the following command in your machine’s terminal. pip install python-docx For this example, I’ve randomly picked up two sport articles from CNN. For extracting stats, I’ve written the below describe_text(text) function. This function takes a string parameter (article, review, ...) and returns a dictionary of stats such as Number of characters, Number of words, Number of sentences and others. First of you need to instantiate a document object through Document class. For every article, extract stats by invoking describe_text(text) function and create a table through add_table(row, columns) function. For every stat in a dictionary, create a row through add_row() function and add the corresponding stats. Finally add a page break at the end by calling add_page_break()function in order to present each table in a new page. For more text stats with pure Python functions check my other article below. towardsdatascience.com Generating word documents with Python is easy. All that you need is the python-docx library. This library offers possibilities to accomplish most of the things (but not all) that you can accomplish in MS Word. In my experience, I have generated thousands of Word documents with double-digits number of pages in a matter of seconds. I’ve done this to organise logs data in a more readable format or present written findings in after analysing product review text data.
[ { "code": null, "e": 400, "s": 171, "text": "Whenever automation is discussed, Python is often mentioned. The easy to use syntax, huge number of libraries and the script oriented language construction make Python excel on automation compared to other programming languages." }, { "code": null, "e": 611, "s": 400, "text": "Small and big companies generate reports daily with Microsoft Office tools such as Word and Excel. In this article, I’ll provide an end-to-end explanation on generating tables of data in MS Word through Python." }, { "code": null, "e": 865, "s": 611, "text": "I will consider a scenario where we have a number of news articles and we need to generate a Word document with tables containing stats extracted from these articles. Some of these stats are: number of words, number of sentences and average word length." }, { "code": null, "e": 1057, "s": 865, "text": "For this example, I’ve used Python 3.7. The only dependency you need to install is python-docx. You can install this dependency by submitting the following command in your machine’s terminal." }, { "code": null, "e": 1081, "s": 1057, "text": "pip install python-docx" }, { "code": null, "e": 1402, "s": 1081, "text": "For this example, I’ve randomly picked up two sport articles from CNN. For extracting stats, I’ve written the below describe_text(text) function. This function takes a string parameter (article, review, ...) and returns a dictionary of stats such as Number of characters, Number of words, Number of sentences and others." }, { "code": null, "e": 1835, "s": 1402, "text": "First of you need to instantiate a document object through Document class. For every article, extract stats by invoking describe_text(text) function and create a table through add_table(row, columns) function. For every stat in a dictionary, create a row through add_row() function and add the corresponding stats. Finally add a page break at the end by calling add_page_break()function in order to present each table in a new page." }, { "code": null, "e": 1912, "s": 1835, "text": "For more text stats with pure Python functions check my other article below." }, { "code": null, "e": 1935, "s": 1912, "text": "towardsdatascience.com" }, { "code": null, "e": 2145, "s": 1935, "text": "Generating word documents with Python is easy. All that you need is the python-docx library. This library offers possibilities to accomplish most of the things (but not all) that you can accomplish in MS Word." } ]
HTML | DOM Table Object - GeeksforGeeks
31 Jan, 2019 The Table object is used for representing an HTML <table> element. It can be used to create and access a table. Syntax: To access table element.:document.getElementById("id"); document.getElementById("id"); To create a table object:document.createElement("TABLE"); document.createElement("TABLE"); Below program illustrates the Table Object : Example-1: Accessing a <table> element by using the getElementById() method. <!DOCTYPE html><html> <head> <title>Table Object in HTML</title> <style> table, td { border: 1px solid green; } h1 { color: green; } h2 { font-family: Impact; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>Table Object</h2> <br> <table id="table" align="center"> <tr> <td>Fork Python</td> <td>Fork Java</td> </tr> <tr> <td>Sudo Placement</td> <td>Fork CPP</td> </tr> </table> <p>Double click the "Delete Row" button to remove the second row from the table.</p> <button onclick="delete()">Delete Row</button> <script> function delete() { // Accessing table object. var x = document.getElementById("table"); x.deleteRow(0); } </script> </body> </html> Output:Before Clicking The Button: After Clicking The Button: Example-2: Creating a <table> element by using the document.createElement() method. <!DOCTYPE html><html> <head> <title>Table Object in HTML</title> <style> table { border: 1px solid green; } h1 { color: green; } h2 { font-family: Impact; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>Table Object</h2> <br> <p>Double click the "Create" button to create a TABLE, a Table row and a Table cell element.</p> <button ondblclick="create()">Create</button> <script> function create() { // Create table object. var a = document.createElement("TABLE"); a.setAttribute("id", "MyTable"); document.body.appendChild(a); var b = document.createElement("TR"); b.setAttribute("id", "MyTr"); document.getElementById("MyTable").appendChild(b); var c = document.createElement("TD"); var d = document.createTextNode("Table cell"); c.appendChild(d); document.getElementById("MyTr").appendChild(c); } </script> </body> </html> Output:Before Clicking The Button: After Clicking The Button: Supported Browsers: Opera Internet Explorer Google Chrome Firefox Apple Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-DOM Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 23635, "s": 23607, "text": "\n31 Jan, 2019" }, { "code": null, "e": 23747, "s": 23635, "text": "The Table object is used for representing an HTML <table> element. It can be used to create and access a table." }, { "code": null, "e": 23755, "s": 23747, "text": "Syntax:" }, { "code": null, "e": 23811, "s": 23755, "text": "To access table element.:document.getElementById(\"id\");" }, { "code": null, "e": 23842, "s": 23811, "text": "document.getElementById(\"id\");" }, { "code": null, "e": 23900, "s": 23842, "text": "To create a table object:document.createElement(\"TABLE\");" }, { "code": null, "e": 23933, "s": 23900, "text": "document.createElement(\"TABLE\");" }, { "code": null, "e": 23978, "s": 23933, "text": "Below program illustrates the Table Object :" }, { "code": null, "e": 24055, "s": 23978, "text": "Example-1: Accessing a <table> element by using the getElementById() method." }, { "code": "<!DOCTYPE html><html> <head> <title>Table Object in HTML</title> <style> table, td { border: 1px solid green; } h1 { color: green; } h2 { font-family: Impact; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>Table Object</h2> <br> <table id=\"table\" align=\"center\"> <tr> <td>Fork Python</td> <td>Fork Java</td> </tr> <tr> <td>Sudo Placement</td> <td>Fork CPP</td> </tr> </table> <p>Double click the \"Delete Row\" button to remove the second row from the table.</p> <button onclick=\"delete()\">Delete Row</button> <script> function delete() { // Accessing table object. var x = document.getElementById(\"table\"); x.deleteRow(0); } </script> </body> </html>", "e": 25063, "s": 24055, "text": null }, { "code": null, "e": 25098, "s": 25063, "text": "Output:Before Clicking The Button:" }, { "code": null, "e": 25125, "s": 25098, "text": "After Clicking The Button:" }, { "code": null, "e": 25209, "s": 25125, "text": "Example-2: Creating a <table> element by using the document.createElement() method." }, { "code": "<!DOCTYPE html><html> <head> <title>Table Object in HTML</title> <style> table { border: 1px solid green; } h1 { color: green; } h2 { font-family: Impact; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>Table Object</h2> <br> <p>Double click the \"Create\" button to create a TABLE, a Table row and a Table cell element.</p> <button ondblclick=\"create()\">Create</button> <script> function create() { // Create table object. var a = document.createElement(\"TABLE\"); a.setAttribute(\"id\", \"MyTable\"); document.body.appendChild(a); var b = document.createElement(\"TR\"); b.setAttribute(\"id\", \"MyTr\"); document.getElementById(\"MyTable\").appendChild(b); var c = document.createElement(\"TD\"); var d = document.createTextNode(\"Table cell\"); c.appendChild(d); document.getElementById(\"MyTr\").appendChild(c); } </script> </body> </html>", "e": 26395, "s": 25209, "text": null }, { "code": null, "e": 26430, "s": 26395, "text": "Output:Before Clicking The Button:" }, { "code": null, "e": 26457, "s": 26430, "text": "After Clicking The Button:" }, { "code": null, "e": 26477, "s": 26457, "text": "Supported Browsers:" }, { "code": null, "e": 26483, "s": 26477, "text": "Opera" }, { "code": null, "e": 26501, "s": 26483, "text": "Internet Explorer" }, { "code": null, "e": 26515, "s": 26501, "text": "Google Chrome" }, { "code": null, "e": 26523, "s": 26515, "text": "Firefox" }, { "code": null, "e": 26536, "s": 26523, "text": "Apple Safari" }, { "code": null, "e": 26673, "s": 26536, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 26682, "s": 26673, "text": "HTML-DOM" }, { "code": null, "e": 26689, "s": 26682, "text": "Picked" }, { "code": null, "e": 26694, "s": 26689, "text": "HTML" }, { "code": null, "e": 26711, "s": 26694, "text": "Web Technologies" }, { "code": null, "e": 26716, "s": 26711, "text": "HTML" }, { "code": null, "e": 26814, "s": 26716, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26823, "s": 26814, "text": "Comments" }, { "code": null, "e": 26836, "s": 26823, "text": "Old Comments" }, { "code": null, "e": 26898, "s": 26836, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26948, "s": 26898, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 27008, "s": 26948, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 27056, "s": 27008, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 27117, "s": 27056, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 27173, "s": 27117, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 27206, "s": 27173, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27268, "s": 27206, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27311, "s": 27268, "text": "How to fetch data from an API in ReactJS ?" } ]