title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to match a particular word in a string using Pattern class in Java?
The \b meta character in Java regular expressions matches the word boundaries Therefore to find a particular word from the given input text specify the required word within the word boundaries in the regular expressions as − "\\brequired word\\b"; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MachingWordExample1 { public static void main( String args[] ) { //Reading string value Scanner sc = new Scanner(System.in); System.out.println("Enter input string"); String input = sc.next(); //Regular expression to find digits String regex = "\\bhello\\b"; //Compiling the regular expression Pattern pattern = Pattern.compile(regex); //Retrieving the matcher object Matcher matcher = pattern.matcher(input); if(matcher.find()) { System.out.println("Match found"); } else { System.out.println("Match not found"); } } } Enter input string hello welcome to Tutorialspoint Match found import java.util.regex.Matcher; import java.util.regex.Pattern; public class MatcherExample2 { public static void main( String args[] ) { String input = "This is sample text \n " + "This is second line " + "This is third line"; String regex = "\\bsecond\\b"; //Compiling the regular expression Pattern pattern = Pattern.compile(regex); //Retrieving the matcher object Matcher matcher = pattern.matcher(input); if(matcher.find()) { System.out.println("Match found"); } else { System.out.println("Match not found"); } } } Match found
[ { "code": null, "e": 1287, "s": 1062, "text": "The \\b meta character in Java regular expressions matches the word boundaries Therefore to find a particular word from the given input text specify the required word within the word boundaries in the regular expressions as −" }, { "code": null,...
C - Variable Types
C - Programming HOME C - Basic Introduction C - Program Structure C - Reserved Keywords C - Basic Datatypes C - Variable Types C - Storage Classes C - Using Constants C - Operator Types C - Control Statements C - Input and Output C - Pointing to Data C - Using Functions C - Play with Strings C - Structured Datatypes C - Working with Files C - Bits Manipulation C - Pre-Processors C - Useful Concepts C - Built-in Functions C - Useful Resources Computer Glossary Who is Who Copyright © 2014 by tutorialspoint A variable is just a named area of storage that can hold a single value (numeric or character). The C language demands that you declare the name of each variable that you are going to use and its type, or class, before you actually try to do anything with it. The Programming language C has two main variable types Local Variables Local Variables Global Variables Global Variables Local variables scope is confined within the block or function where it is defined. Local variables must always be defined at the top of a block. Local variables scope is confined within the block or function where it is defined. Local variables must always be defined at the top of a block. When a local variable is defined - it is not initalised by the system, you must initalise it yourself. When a local variable is defined - it is not initalised by the system, you must initalise it yourself. When execution of the block starts the variable is available, and when the block ends the variable 'dies'. When execution of the block starts the variable is available, and when the block ends the variable 'dies'. Check following example's output main() { int i=4; int j=10; i++; if (j > 0) { /* i defined in 'main' can be seen */ printf("i is %d\n",i); } if (j > 0) { /* 'i' is defined and so local to this block */ int i=100; printf("i is %d\n",i); }/* 'i' (value 100) dies here */ printf("i is %d\n",i); /* 'i' (value 5) is now visable.*/ } This will generate following output i is 5 i is 100 i is 5 Here ++ is called incremental operator and it increase the value of any integer variable by 1. Thus i++ is equivalent to i = i + 1; You will see -- operator also which is called decremental operator and it idecrease the value of any integer variable by 1. Thus i-- is equivalent to i = i - 1; Global variable is defined at the top of the program file and it can be visible and modified by any function that may reference it. Global variables are initalised automatically by the system when you define them! If same variable name is being used for global and local variable then local variable takes preference in its scope. But it is not a good practice to use global variables and local variables with the same name. int i=4; /* Global definition */ main() { i++; /* Global variable */ func(); printf( "Value of i = %d -- main function\n", i ); } func() { int i=10; /* Local definition */ i++; /* Local variable */ printf( "Value of i = %d -- func() function\n", i ); } This will produce following result Value of i = 11 -- func() function Value of i = 5 -- main function i in main function is global and will be incremented to 5. i in func is internal and will be incremented to 11. When control returns to main the internal variable will die and and any reference to i will be to the global. Advertisements 6 Lectures 1.5 hours Mr. Pradeep Kshetrapal 41 Lectures 5 hours AR Shankar 11 Lectures 58 mins Musab Zayadneh 59 Lectures 15.5 hours Narendra P 11 Lectures 1 hours Sagar Mehta 39 Lectures 4 hours Vikas Yadav Print Add Notes Bookmark this page
[ { "code": null, "e": 1475, "s": 1454, "text": "C - Programming HOME" }, { "code": null, "e": 1498, "s": 1475, "text": "C - Basic Introduction" }, { "code": null, "e": 1520, "s": 1498, "text": "C - Program Structure" }, { "code": null, "e": 1542, ...
2D Vector of Tuples in C++ with Examples - GeeksforGeeks
27 Dec, 2021 What is Vector? In C++, a vector is similar to dynamic arrays with the ability to resize itself automatically. Vector elements are stored in contiguous memory locations so that they can be accessed and traversed using iterators. Functions associated with a vector: begin(): Returns an iterator pointing to the first element in the vector. end(): Returns an iterator pointing to the theoretical element that follows the last element in the vector. rbegin(): Returns a reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to the first element. size(): Returns the number of elements in the vector. empty(): Returns whether the vector is empty. push_back(): It pushes the elements into a vector from the back. pop_back(): It is used to pop or remove elements from a vector from the back. insert(): It inserts new elements before the element at the specified position. What is a 2D vector? In C++, a 2D vector is a vector of vectors which means that each element of a 2D vector is a vector itself. It is the same as a matrix implemented with the help of vectors. Functions associated with a 2D vector: size(): Returns the number of elements in the 2D vector. empty(): Returns whether the 2D vector is empty. push_back(): It pushes a vector into a 2D vector from the back. pop_back(): It is used to pop or remove elements from a 2D vector from the back. What is a Tuple? A tuple in C++ is an object which is used to group elements together. In a tuple, elements can be of the same data type or different data types. The elements of tuples are initialized as in the order in which they will be accessed. Functions associated with a tuple: 1. make_tuple(): make_tuple() is used to assign tuple with values. The values passed should be in order with the values declared in the tuple.2. get(): get() is used to access the tuple values and modify them, it accepts the index and tuple name as arguments to access a particular tuple element. How to access a Tuple? To access elements of a tuple use the get<>() function. Syntax: auto fistElement = get<0>(myTuple);auto secondElement = get<1>(myTuple);auto thirdElement = get<2>(myTuple); This article focuses on how to create a 2D vector of tuples in C++. 2D Vector of Tuples A 2D vector of tuples or vector of vectors of tuples is a vector in which each element is a vector of tuples itself. Although a tuple may contain any number of elements for simplicity, a tuple of three elements is considered. Syntax: vector<vector<tuple<dataType1, dataType2, dataType3>> myContainer Here,dataType1, dataType2, dataType3 can be similar or dissimilar data types. Example 1: Below is the C++ program to implement 2D vector of tuples. C++ // C++ program to demonstrate the// working of vector of vectors// of tuples#include <bits/stdc++.h>using namespace std; // Function to print 2D vector elementsvoid print(vector<vector<tuple<int, int, int> > >& myContainer){ // Iterating over 2D vector elements for (auto currentVector : myContainer) { // Each element of the 2D vector // is a vector itself vector<tuple<int, int, int> > myVector = currentVector; // Iterating over the the vector elements cout << "[ "; for (auto currentTuple : myVector) { // Print the element cout << "{"; cout << get<0>(currentTuple) << ", " << get<1>(currentTuple) << ", " << get<2>(currentTuple); cout << "} "; } cout << "]\n"; }} // Driver codeint main(){ // Declaring a 2D vector of tuples vector<vector<tuple<int, int, int> > > myContainer; // Initializing vectors of tuples // tuples are of type {int, int, int} vector<tuple<int, int, int> > vect1 = { { 1, 1, 2 }, { 2, 2, 4 }, { 3, 3, 6 }, { 4, 4, 8 } }; vector<tuple<int, int, int> > vect2 = { { 1, 2, 3 }, { 1, 3, 4 }, { 1, 4, 5 }, { 1, 5, 6 } }; vector<tuple<int, int, int> > vect3 = { { 4, 5, 2 }, { 8, 1, 9 }, { 9, 3, 1 }, { 2, 4, 8 } }; vector<tuple<int, int, int> > vect4 = { { 7, 2, 1 }, { 6, 5, 1 }, { 1, 2, 9 }, { 10, 4, 8 } }; // Inserting vector of tuples in the 2D vector myContainer.push_back(vect1); myContainer.push_back(vect2); myContainer.push_back(vect3); myContainer.push_back(vect4); // Calling print function print(myContainer); return 0;} [ {1, 1, 2} {2, 2, 4} {3, 3, 6} {4, 4, 8} ][ {1, 2, 3} {1, 3, 4} {1, 4, 5} {1, 5, 6} ][ {4, 5, 2} {8, 1, 9} {9, 3, 1} {2, 4, 8} ][ {7, 2, 1} {6, 5, 1} {1, 2, 9} {10, 4, 8} ] Example 2: Below is the C++ program to implement 2D vector of tuples. C++ // C++ program to demonstrate the// working of vector of vectors of tuples#include <bits/stdc++.h>using namespace std; // Function to print 2D vector elementsvoid print(vector<vector<tuple<string, string, string> > >& myContainer){ // Iterating over 2D vector elements for (auto currentVector : myContainer) { // Each element of the 2D vector // is a vector itself vector<tuple<string, string, string> > myVector = currentVector; // Iterating over the the vector // elements cout << "[ "; for (auto currentTuple : myVector) { // Prstring the element cout << "{"; cout << get<0>(currentTuple) << ", " << get<1>(currentTuple) << ", " << get<2>(currentTuple); cout << "} "; } cout << "]\n"; }} // Driver codeint main(){ // Declaring a 2D vector of tuples vector<vector<tuple<string, string, string> > > myContainer; // Initializing vectors of tuples // tuples are of type {string, string, string} vector<tuple<string, string, string> > vect1 = { { "Geeks", "for", "Geeks" }, { "Swift", "Python", "Java" }, { "Int", "Float", "Double" } }; vector<tuple<string, string, string> > vect2 = { { "C++", "C", "C#" }, { "R", "HTML", "CSS" }, { "Javascript", "PHP", "Django" } }; vector<tuple<string, string, string> > vect3 = { { "Bhuwanesh", "Harshit", "DS" }, { "Piyush", "Jai", "Naveen" }, { "Anil", "Rahul", "keshav" } }; vector<tuple<string, string, string> > vect4 = { { "Sweta", "Tanu", "Kavita" }, { "Nawal", "Bhargav", "Jitesh" }, { "Daya", "Mohan", "Bhuwanesh" } }; // Inserting vector of tuples in the // 2D vector myContainer.push_back(vect1); myContainer.push_back(vect2); myContainer.push_back(vect3); myContainer.push_back(vect4); // Calling print function print(myContainer); return 0;} [ {Geeks, for, Geeks} {Swift, Python, Java} {Int, Float, Double} ][ {C++, C, C#} {R, HTML, CSS} {Javascript, PHP, Django} ][ {Bhuwanesh, Harshit, DS} {Piyush, Jai, Naveen} {Anil, Rahul, keshav} ][ {Sweta, Tanu, Kavita} {Nawal, Bhargav, Jitesh} {Daya, Mohan, Bhuwanesh} ] cpp-tuple cpp-vector STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Operator Overloading in C++ Sorting a vector in C++ Polymorphism in C++ Friend class and function in C++ List in C++ Standard Template Library (STL) Pair in C++ Standard Template Library (STL) Convert string to char array in C++ new and delete operators in C++ for dynamic memory Destructors in C++ Queue in C++ Standard Template Library (STL)
[ { "code": null, "e": 23707, "s": 23679, "text": "\n27 Dec, 2021" }, { "code": null, "e": 23723, "s": 23707, "text": "What is Vector?" }, { "code": null, "e": 23936, "s": 23723, "text": "In C++, a vector is similar to dynamic arrays with the ability to resize i...
Decimal.Truncate() Method in C#
The Decimal.Truncate() method in C# is used to return the integral digits of the specified Decimal. Remember, any fractional digits are discarded. Following is the syntax − public static decimal Truncate (decimal val); Above, Val is the decimal number to truncate. Let us now see an example to implement the Decimal.Truncate() method − using System; public class Demo { public static void Main(){ Decimal val = 6576.876m; Console.WriteLine("Decimal value = "+val); ulong res = Decimal.ToUInt64(val); Console.WriteLine("64-bit unsigned integer = "+res); Decimal val2 = Decimal.Truncate(val); Console.WriteLine("Integral digits of the decimal = "+val2); } } This will produce the following output − Decimal value = 6576.876 64-bit unsigned integer = 6576 Integral digits of the decimal = 6576 Let us now see another example to implement the Decimal.Truncate() method − using System; public class Demo { public static void Main(){ Decimal val = 28676.935m; Console.WriteLine("Decimal value = "+val); Decimal val2 = Decimal.Truncate(val); Console.WriteLine("Integral digits of the decimal = "+val2); } } This will produce the following output − Decimal value = 28676.935 Integral digits of the decimal = 28676
[ { "code": null, "e": 1209, "s": 1062, "text": "The Decimal.Truncate() method in C# is used to return the integral digits of the specified Decimal. Remember, any fractional digits are discarded." }, { "code": null, "e": 1235, "s": 1209, "text": "Following is the syntax −" }, {...
HTML | body text Attribute - GeeksforGeeks
25 Mar, 2022 The HTML <body> text Attribute is used to define a color for the text in the Document. Note: The <body> text attribute is not supported by HTML5. Instead of using this attribute, we can use css color property. Syntax: <body text="color_name | hex_number | rgb_number"> Attribute Values color_name: It specify the name of the color for the text in the Document. hex_number: It specify the hex code of the color of the Text in the Document. rgb_number: It specify the rgb value of the Text in the Document Example: html <!DOCTYPE html><html> <head> <title>HTML body Text Attribute</title></head> <!-- body tag starts here --> <body text="green"> <center> <h1>GeeksforGeeks</h1> <h2>HTML <body> Text Attribute</h2> <p>It is a Computer Science portal For Geeks</p> </center></body><!-- body tag ends here --> </html> Output: Supported Browsers: The browser supported by <body> Text Attribute are listed below: Google Chrome Internet Explorer Firefox Safari Opera Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. ManasChhabra2 chhabradhanvi HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to update Node.js and NPM to next version ? How to Insert Form Data into Database using PHP ? REST API (Introduction) CSS to put icon inside an input element in a form Form validation using HTML and JavaScript Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript How to calculate the number of days between two dates in javascript?
[ { "code": null, "e": 24814, "s": 24786, "text": "\n25 Mar, 2022" }, { "code": null, "e": 25026, "s": 24814, "text": "The HTML <body> text Attribute is used to define a color for the text in the Document. Note: The <body> text attribute is not supported by HTML5. Instead of using...
A definitive guide for Setting up a Deep Learning Workstation with Ubuntu 18.04 | by Rahul Agarwal | Towards Data Science
Lambda and other vendors offer pre-built deep learning workstations with the new Ampere RTX 3090, 3080, and 3070 GPUs — but if you’re interested in building your own, read on. Creating my own workstation has been a dream for me if nothing else. I knew the process involved, yet I somehow never got to it. But this time I just had to do it. So, I found out some free time to create a Deep Learning Rig with a lot of assistance from NVIDIA folks who were pretty helpful. On that note special thanks to Josh Patterson and Michael Cooper. Now, every time I create the whole deep learning setup from an installation viewpoint, I end up facing similar challenges. It’s like running around in circles with all these various dependencies and errors. This time also I had to try many things before the whole configuration came to life without errors. So this time, I made it a point to document everything while installing all the requirements and their dependencies in my own system. This post is about setting up your own Linux Ubuntu 18.04 system for deep learning with everything you might need. If a pre-built deep learning system is preferred, I can recommend Exxact’s line of workstations and servers. I assume that you have a fresh Ubuntu 18.04 installation. I am taking inspiration from Slav Ivanov’s excellent post in 2017 on creating a Deep Learning box. You can call it the 2020 version for the same post from a setup perspective, but a lot of the things have changed from then, and there are a lot of caveats with specific CUDA versions not supported by Tensorflow and Pytorch. Before we do anything with our installation, we need to update our Linux system to the latest packages. We can do this simply by using: sudo apt-get updatesudo apt-get --assume-yes upgradesudo apt-get --assume-yes install tmux build-essential gcc g++ make binutilssudo apt-get --assume-yes install software-properties-commonsudo apt-get --assume-yes install git So now we have everything set up we want to install the following four things: GPU Drivers: Why is your PC not supporting high graphic resolutions? Or how would your graphics cards talk to your python interfaces?CUDA: A layer to provide access to the GPU’s instruction set and parallel computation units. In simple words, it allows us a way to write code for GPUsCuDNN: a library that provides Primitives for Deep Learning NetworkPytorch, Tensorflow, and Rapids: higher-level APIs to code Deep Neural Networks GPU Drivers: Why is your PC not supporting high graphic resolutions? Or how would your graphics cards talk to your python interfaces? CUDA: A layer to provide access to the GPU’s instruction set and parallel computation units. In simple words, it allows us a way to write code for GPUs CuDNN: a library that provides Primitives for Deep Learning Network Pytorch, Tensorflow, and Rapids: higher-level APIs to code Deep Neural Networks The first step is to add the latest NVIDIA drivers. You can choose the GPU product type, Linux 64 bit, and download Type as “Linux Long-Lived” for the 18.04 version. Clicking on search will take you to a downloads page: From where you can download the driver file NVIDIA-Linux-x86_64–440.44.run and run it using: chmod +x NVIDIA-Linux-x86_64–440.44.runsudo sh NVIDIA-Linux-x86_64–440.44.run For you, the file may be named differently, depending on the latest version. We will now need to install the CUDA toolkit. Somehow the CUDA toolkit 10.2 is still not supported by Pytorch and Tensorflow, so we will go with CUDA Toolkit 10.1, which is supported by both. Also, the commands on the product page for CUDA 10.1 didn’t work for me and the commands I ended up using are: sudo apt-key adv --fetch-keys http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/7fa2af80.pub && echo "deb https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64 /" | sudo tee /etc/apt/sources.list.d/cuda.listsudo apt-get update && sudo apt-get -o Dpkg::Options::="--force-overwrite" install cuda-10-1 cuda-drivers The next step is to create the LD_LIBRARY_PATH and append to the PATH variable the path where CUDA got installed. Just run this below command on your terminal. echo 'export PATH=/usr/local/cuda-10.1/bin${PATH:+:${PATH}}' >> ~/.bashrc && echo 'export LD_LIBRARY_PATH=/usr/local/cuda-10.1/lib64${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}' >> ~/.bashrc && source ~/.bashrc && sudo ldconfig After this, one can check if CUDA is installed correctly by using: nvcc --version As you can see, the CUDA Version is 10.1 as we wanted. Also, check if you can use the command: nvidia-smi For me, it showed an error when I used it the first time, but a simple reboot solved the issue. And both my NVIDIA graphic cards show up in all their awesome glory. Don’t worry that the display says the CUDA version supported is 10.2. I was also confused, but it is just the maximum CUDA version supported by the graphics driver that is shown in nvidia-smi. What is the use of all these libraries if we are not going to train neural nets? CuDNN provides various primitives for Deep Learning, which are later used by PyTorch/TensorFlow. But we first need to get a developer account first to install CuDNN. Once you fill-up the signup form, you will see the screen below. Select the cuDNN version that applies to your CUDA version. For me, the CUDA version is 10.1, so I select the second one. Once you select the appropriate CuDNN version the screen expands: For my use case, I needed to download three files for Ubuntu 18.04: cuDNN Runtime Library for Ubuntu18.04 (Deb)cuDNN Developer Library for Ubuntu18.04 (Deb)cuDNN Code Samples and User Guide for Ubuntu18.04 (Deb) After downloading these files, you can install using these commands. You can also see the exact commands if anything changes in the future: # Install the runtime library:sudo dpkg -i libcudnn7_7.6.5.32-1+cuda10.1_amd64.deb#Install the developer library:sudo dpkg -i libcudnn7-dev_7.6.5.32-1+cuda10.1_amd64.deb#Install the code samples and cuDNN User Guide(Optional):sudo dpkg -i libcudnn7-doc_7.6.5.32-1+cuda10.1_amd64.deb And finally, we reach the crux. We will install the software which we will interface with most of the times. We need to install Python with virtual environments. I have downloaded python3 as it is the most stable version as of now, and it is time to say goodbye to Python 2.7. It was great while it lasted. And we will also install Pytorch and Tensorflow. I prefer them both for specific tasks as applicable. You can go to the anaconda distribution page and download the package. Once downloaded you can simply run the shell script: sudo sh Anaconda3-2019.10-Linux-x86_64.sh You will also need to run these commands on your shell to add some commands to your ~/.bashrc file, and update the conda distribution with the latest libraries versions. cat >> ~/.bashrc << 'EOF'export PATH=$HOME/anaconda3/bin:${PATH}EOFsource .bashrcconda upgrade -y --all The next step is creating a new environment for your deep learning pursuits or using an existing one. I created a new Conda environment using: conda create --name py37 Here py37 is the name we provide to this new conda environment. You can activate this conda environment using: conda activate py37 You should now be able to see something like: We can now add all our required packages to this environment using pip or conda. The latest version 1.3, as seen from the pytorch site, is not yet available for CUDA 10.2, as I already mentioned, so we are in luck with CUDA 10.1. Also, we will need to specify the version of TensorFlow as 2.1.0, as this version was built using 10.1 CUDA. I also install RAPIDS, which is a library to get your various data science workloads to GPUs. Why use GPUs only for deep learning and not for Data processing? You can get the command to install rapids from the rapids release selector: sudo apt install python3-pipconda install -c rapidsai -c nvidia -c conda-forge -c defaults rapids=0.11 python=3.7 cudatoolkit=10.1pip install torchvision Since PyTorch installation interfered with TensorFlow, I installed TensorFlow in another environment. conda create --name tfconda activate tfpip install --upgrade tensorflow Now we can check if the TF and Pytorch installations are correctly done by using the below commands in their own environments: # Should print Truepython3 -c "import tensorflow as tf; print(tf.test.is_gpu_available())"# should print cudapython3 -c "import torch; print(torch.device('cuda' if torch.cuda.is_available() else 'cpu'))" If the install is showing some errors for TensorFlow or the GPU test is failing, you might want to add these two additional lines at the end of your bashrc file and restart the terminal: export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda/extras/CUPTI/lib64:/usr/local/cuda/lib64export CUDA_HOME=/usr/local/cuda You might also want to install jupyter lab or jupyter notebook. Thanks to the developers, the process is as easy as just running jupyter labor jupyter notebook in your terminal, whichever you do prefer. I personally like notebook better without all the unnecessary clutter. In this post, I talked about all the software you are going to need to install in your deep learning rig without hassle. You might still need some help and face some problems for which my best advice would be to check out the different NVIDIA and Stack Overflow forums. So we have got our deep learning rig setup, and its time for some tests now. In the next few posts, I am going to do some benchmarking on the GPUs and will try to write more on various deep Learning libraries one can include in their workflow. So stay tuned. If you want to learn more about Deep Learning, here is an excellent course. You can start for free with the 7-day Free Trial. 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": 348, "s": 172, "text": "Lambda and other vendors offer pre-built deep learning workstations with the new Ampere RTX 3090, 3080, and 3070 GPUs — but if you’re interested in building your own, read on." }, { "code": null, "e": 477, "s": 348, "text": "Creating m...
PHP - Complete Form
This page explains about time real-time form with actions. Below example will take input fields as text, radio button, drop down menu, and checked box. <html> <head> <style> .error {color: #FF0000;} </style> </head> <body> <?php // define variables and set to empty values $nameErr = $emailErr = $genderErr = $websiteErr = ""; $name = $email = $gender = $class = $course = $subject = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr = "Name is required"; }else { $name = test_input($_POST["name"]); } if (empty($_POST["email"])) { $emailErr = "Email is required"; }else { $email = test_input($_POST["email"]); // check if e-mail address is well-formed if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format"; } } if (empty($_POST["course"])) { $course = ""; }else { $course = test_input($_POST["course"]); } if (empty($_POST["class"])) { $class = ""; }else { $class = test_input($_POST["class"]); } if (empty($_POST["gender"])) { $genderErr = "Gender is required"; }else { $gender = test_input($_POST["gender"]); } if (empty($_POST["subject"])) { $subjectErr = "You must select 1 or more"; }else { $subject = $_POST["subject"]; } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <h2>Absolute classes registration</h2> <p><span class = "error">* required field.</span></p> <form method = "POST" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> <table> <tr> <td>Name:</td> <td><input type = "text" name = "name"> <span class = "error">* <?php echo $nameErr;?></span> </td> </tr> <tr> <td>E-mail: </td> <td><input type = "text" name = "email"> <span class = "error">* <?php echo $emailErr;?></span> </td> </tr> <tr> <td>Time:</td> <td> <input type = "text" name = "course"> <span class = "error"><?php echo $websiteErr;?></span> </td> </tr> <tr> <td>Classes:</td> <td> <textarea name = "class" rows = "5" cols = "40"></textarea></td> </tr> <tr> <td>Gender:</td> <td> <input type = "radio" name = "gender" value = "female">Female <input type = "radio" name = "gender" value = "male">Male <span class = "error">* <?php echo $genderErr;?></span> </td> </tr> <tr> <td>Select:</td> <td> <select name = "subject[]" size = "4" multiple> <option value = "Android">Android</option> <option value = "Java">Java</option> <option value = "C#">C#</option> <option value = "Data Base">Data Base</option> <option value = "Hadoop">Hadoop</option> <option value = "VB script">VB script</option> </select> </td> </tr> <tr> <td>Agree</td> <td><input type = "checkbox" name = "checked" value = "1"></td> <?php if(!isset($_POST['checked'])){ ?> <span class = "error">* <?php echo "You must agree to terms";?></span> <?php } ?> </tr> <tr> <td> <input type = "submit" name = "submit" value = "Submit"> </td> </tr> </table> </form> <?php echo "<h2>Your given values are as :</h2>"; echo ("<p>Your name is $name</p>"); echo ("<p> your email address is $email</p>"); echo ("<p>Your class time at $course</p>"); echo ("<p>your class info $class </p>"); echo ("<p>your gender is $gender</p>"); for($i = 0; $i < count($subject); $i++) { echo($subject[$i] . " "); } ?> </body> </html> It will produce the following result − 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2909, "s": 2757, "text": "This page explains about time real-time form with actions. Below example will take input fields as text, radio button, drop down menu, and checked box." }, { "code": null, "e": 7827, "s": 2909, "text": "<html>\n \n <head>\n ...
GATE | GATE-CS-2000 | Question 17 - GeeksforGeeks
28 Jun, 2021 Consider the following C declaration struct { short s [5] union { float y; long z; }u;} t; Assume that objects of the type short, float and long occupy 2 bytes, 4 bytes and 8 bytes, respectively. The memory requirement for variable t, ignoring alignment considerations, is (A) 22 bytes(B) 14 bytes(C) 18 bytes(D) 10 bytesAnswer: (C)Explanation: See question 3 of https://www.geeksforgeeks.org/c-language-set-1/Quiz of this Question GATE-CS-2000 GATE-GATE-CS-2000 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-IT-2004 | Question 71 GATE | GATE CS 2011 | Question 7 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2016 (Set 2) | Question 61 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE CS 2010 | Question 24 GATE | GATE-CS-2016 (Set 1) | Question 65 GATE | GATE-CS-2014-(Set-3) | Question 38 GATE | GATE CS 2018 | Question 37 GATE | GATE-IT-2004 | Question 83
[ { "code": null, "e": 24182, "s": 24154, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24219, "s": 24182, "text": "Consider the following C declaration" }, { "code": "struct { short s [5] union { float y; long z; }u;} t;", "e": 24298, "s...
Minimum Size Subarray Sum in C++
Suppose we have an array of n elements, and a positive integer s. We have to find the minimal length of a contiguous subarray, of which the sum is greater or equal to s. If there isn’t one,then return 0 instead. So if the array is like [2,3,1,2,3,4] and sum is 7, then the output will be 2. This is the subarray [4,3] has the minimum length for this case. To solve this, we will follow these steps − ans := 0, n := size of array A, j := 0 and sum := 0 ans := 0, n := size of array A, j := 0 and sum := 0 for i in range 0 to n – 1sum := sum + A[i]while sum – A[i] >= K and j <= 1sum := sum – A[j]increase j by 1if sum >= k, thenif ans = 0 or ans > (i – j + 1), then ans := (i – j + 1) for i in range 0 to n – 1 sum := sum + A[i] sum := sum + A[i] while sum – A[i] >= K and j <= 1sum := sum – A[j]increase j by 1 while sum – A[i] >= K and j <= 1 sum := sum – A[j] sum := sum – A[j] increase j by 1 increase j by 1 if sum >= k, thenif ans = 0 or ans > (i – j + 1), then ans := (i – j + 1) if sum >= k, then if ans = 0 or ans > (i – j + 1), then ans := (i – j + 1) if ans = 0 or ans > (i – j + 1), then ans := (i – j + 1) return ans return ans Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: int minSubArrayLen(int K, vector<int>& A) { int ans = 0; int n = A.size(); int j = 0; int sum = 0; for(int i = 0; i < n; i++){ sum += A[i]; while(sum - A[j] >= K && j <= i){ sum -= A[j]; j++; } if(sum >= K){ if(ans == 0 || ans > (i - j + 1)) ans = (i - j + 1); } } return ans; } }; main(){ vector<int> v = {2,3,1,2,4,3}; Solution ob; cout << ((ob.minSubArrayLen(7,v))); } 7 [2,3,1,2,4,3] 2
[ { "code": null, "e": 1418, "s": 1062, "text": "Suppose we have an array of n elements, and a positive integer s. We have to find the minimal length of a contiguous subarray, of which the sum is greater or equal to s. If there isn’t one,then return 0 instead. So if the array is like [2,3,1,2,3,4] and...
Machine Learning With R: Logistic Regression | by Dario Radečić | Towards Data Science
Our little journey to machine learning with R continues! Today’s topic is logistic regression — as an introduction to machine learning classification tasks. We’ll cover data preparation, modeling, and evaluation of the well-known Titanic dataset. If you want to read the series from the beginning, here are the links to the previous articles: Machine Learning with R: Linear Regression This article is structured as follows: Intro to logistic regression Dataset introduction and loading Data preparation Model training and evaluation Conclusion You can download the source code here. That’s it for the introduction section — we have many things to cover, so let’s jump right to it. Logistic regression is a great introductory algorithm for binary classification (two class values) borrowed from the field of statistics. The algorithm got the name from its underlying mechanism — the logistic function (sometimes called the sigmoid function). The logistic function is an S-shaped function developed in statistics, and it takes any real-valued number and maps it to a value between 0 and 1. That’s just what we need for binary classification, as we can set the threshold at 0.5 and make predictions according to the output of the logistic function. Here’s how the logistic function looks like: In case you’re interested, below is the equation for the logistic function. Remember — it takes any real-valued number and transforms it to a value between 0 and 1. And that’s quite enough for the theory. I repeat — this article’s aim isn’t to cover the theory, as there’s a plethora of theoretical articles/books out there. It’s a pure hands-on piece. Okay, now we have a basic logistic regression understanding under our belt, and we can begin with the coding portion. We’ll use the Titanic dataset, as mentioned previously. You don’t have to download it, as R does that for us. Here’s the snippet for library imports and dataset loading: library(dplyr) library(stringr) library(caTools) library(caret) df <- read.csv('https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv') And here’s how the first couple of rows look like: Awesome! The dataset requires a bit of preparation to get it to a ml-ready format, so that’s what we’ll do next. There are a couple of essential things we have to do: Extract titles from the Name attribute Remap extracted titles as usual/unusual Convert Cabin attribute to binary — HasCabin Remove unnecessary attributes This snippet from Kaggle helped a lot with title extraction and remapping, with slight modifications. Other points are relatively straightforward, as the following snippet shows: maleNobleTitles <- c('Capt', 'Col', 'Don', 'Dr', 'Jonkheer', 'Major', 'Rev', 'Sir') femaleNobleTitles <- c('Lady', 'Mlle', 'Mme', 'Ms', 'the Countess') df$Title <- str_sub(df$Name, str_locate(df$Name, ',')[ , 1] + 2, str_locate(df$Name, '\\.')[ , 1] - 1) df$Title[df$Title %in% maleNobleTitles] <- 'MaleNoble' df$Title[df$Title %in% femaleNobleTitles] <- 'FemaleNoble' df$HasCabin <- ifelse(df$Cabin == '', 0, 1) df <- df %>% select(-PassengerId, -Name, -Ticket, -Cabin) We essentially created two arrays for noble titles, one for males and one for females, extracted the title to the Title column, and replaced noble titles with the expressions ‘MaleNoble’ and ‘FemaleNoble’. Further, the ifelse function helped make the HasCabin attribute, which has a value of 1 if the value for Cabin is not empty and 0 otherwise. Finally, we’ve kept only the features that are relevant for analysis. Here’s how the dataset looks now: Awesome! Let’s deal with missing values next. The following line of code prints out how many missing values there are per attribute: lapply(df, function(x) { length(which(is.na(x))) }) The attribute Age is the only one that contains missing values. As this article covers machine learning and not data preparation, we’ll perform the imputation with a simple mean. Here’s the snippet: df$Age <- ifelse(is.na(df$Age), mean(df$Age, na.rm=TRUE), df$Age) And that’s it for the imputation. There’s only one thing left to do, preparation-wise. We have a bunch of categorical attributes in our dataset. R provides a simple factor() function that converts categorical attributes to an algorithm-understandable format. Here’s the structure of our dataset before the transformation: And here’s the code snippet to perform the transformation: df$Survived <- factor(df$Survived) df$Pclass <- factor(df$Pclass) df$Sex <- factor(df$Sex) df$SibSp <- factor(df$SibSp) df$Parch <- factor(df$Parch) df$Embarked <- factor(df$Embarked) df$Title <- factor(df$Title) df$HasCabin <- factor(df$HasCabin) The data preparation part is finished, and we can now proceed with the modeling. Before the actual model training, we need to split our dataset on the training and testing subset. Doing so ensures we have a subset of data to evaluate on, and know how good the model is. Here’s the code: set.seed(42) sampleSplit <- sample.split(Y=df$Survived, SplitRatio=0.7) trainSet <- subset(x=df, sampleSplit==TRUE) testSet <- subset(x=df, sampleSplit==FALSE) The above code divides the original dataset into 70:30 subsets. We’ll train on the majority (70%), and evaluate on the rest. We can now train the model with the function. We’ll use all of the attributes, indicated by the dot, and the column is the target variable. model <- glm(Survived ~ ., family=binomial(link='logit'), data=trainSet) And that’s it — we have successfully trained the model. Let’s see how it performed by calling the summary() function on it: summary(model) The most exciting thing here is the P-values, displayed in the Pr(>|t|) column. Those values indicate the probability of a variable not being important for prediction. It’s common to use a 5% significance threshold, so if a P-value is 0.05 or below, we can say there’s a low chance for it not being significant for the analysis. As we can see, the most significant attributes/attribute subsets are Pclass3, Age, SibSp3, SibSp4 , and HasCabin1. We now have some more info on our model — we know the most important factors to decide if a passenger survived the Titanic accident. Now we can move on the evaluation of previously unseen data — test set. We’ve kept this subset untouched deliberately, just for model evaluation. To start, we’ll need to calculate the prediction probabilities and predicted classes on top of those probabilities. We’ll set 0.5 as a threshold — if the chance of surviving is less than 0.5, we’ll say the passenger didn’t survive the accident. Here’s the code: probabs <- predict(model, testSet, type='response') preds <- ifelse(probabs > 0.5, 1, 0) It’s now easy to build on top of that. The go-to approach for classification tasks is to make a confusion matrix — a 2×2 matrix showing correct classification on the first and fourth element, and incorrect classification on the second and third element (reading left to right, top to bottom). Here’s how to obtain it through code: confusionMatrix(factor(preds), factor(testSet$Survived)) So, overall, our model is correct in roughly 84% of the test cases — not too bad for a couple of minutes of work. Let’s wrap things up in the next section. We’ve covered the most basic regression and classification machine learning algorithms thus far. It was quite a tedious process, I know, but necessary to create foundations for what’s coming later — more complex algorithms and optimization. The next article in the series on KNN is coming in a couple of days, so stay tuned. Thanks for reading. Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you. medium.com Originally published at https://betterdatascience.com on October 4, 2020.
[ { "code": null, "e": 418, "s": 171, "text": "Our little journey to machine learning with R continues! Today’s topic is logistic regression — as an introduction to machine learning classification tasks. We’ll cover data preparation, modeling, and evaluation of the well-known Titanic dataset." }, ...
Unix / Linux Shell - The if...fi statement
The if...fi statement is the fundamental control statement that allows Shell to make decisions and execute statements conditionally. if [ expression ] then Statement(s) to be executed if expression is true fi The Shell expression is evaluated in the above syntax. If the resulting value is true, given statement(s) are executed. If the expression is false then no statement would be executed. Most of the times, comparison operators are used for making decisions. It is recommended to be careful with the spaces between braces and expression. No space produces a syntax error. If expression is a shell command, then it will be assumed true if it returns 0 after execution. If it is a Boolean expression, then it would be true if it returns true. #!/bin/sh a=10 b=20 if [ $a == $b ] then echo "a is equal to b" fi if [ $a != $b ] then echo "a is not equal to b" fi The above script will generate the following result − a is not equal to b 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2880, "s": 2747, "text": "The if...fi statement is the fundamental control statement that allows Shell to make decisions and execute statements conditionally." }, { "code": null, "e": 2963, "s": 2880, "text": "if [ expression ] \nthen \n Statement(s) to be ...
ioprio_set() - Unix, Linux System Call
Unix - Home Unix - Getting Started Unix - File Management Unix - Directories Unix - File Permission Unix - Environment Unix - Basic Utilities Unix - Pipes & Filters Unix - Processes Unix - Communication Unix - The vi Editor Unix - What is Shell? Unix - Using Variables Unix - Special Variables Unix - Using Arrays Unix - Basic Operators Unix - Decision Making Unix - Shell Loops Unix - Loop Control Unix - Shell Substitutions Unix - Quoting Mechanisms Unix - IO Redirections Unix - Shell Functions Unix - Manpage Help Unix - Regular Expressions Unix - File System Basics Unix - User Administration Unix - System Performance Unix - System Logging Unix - Signals and Traps Unix - Useful Commands Unix - Quick Guide Unix - Builtin Functions Unix - System Calls Unix - Commands List Unix Useful Resources Computer Glossary Who is Who Copyright © 2014 by tutorialspoint int ioprio_get(int which, int who); int ioprio_set(int which, int who, int ioprio); The which and who arguments identify the process(es) on which the system calls operate. The which argument determines how who is interpreted, and has one of the following values: The ioprio argument given to ioprio_set() is a bit mask that specifies both the scheduling class and the priority to be assigned to the target process(es). The following macros are used for assembling and dissecting ioprio values: I/O priorities are supported for reads and for synchronous (O_DIRECT, O_SYNC) writes. I/O priorities are not supported for asynchronous writes because they are issued outside the context of the program dirtying the memory, and thus program-specific priorities do not apply. On success, ioprio_set() returns 0. On error, -1 is returned, and errno is set to indicate the error. These system calls only have an effect when used in conjunction with an I/O scheduler that supports I/O priorities. As at kernel 2.6.17 the only such scheduler is the Completely Fair Queuing (CFQ) I/O scheduler. One can view the current I/O scheduler via the /sys file system. For example, the following command displays a list of all schedulers currently loaded in the kernel: $ cat /sys/block/hda/queue/scheduler noop anticipatory deadline [cfq] The scheduler surrounded by brackets is the one actually in use for the device (hda in the example). Setting another scheduler is done by writing the name of the new scheduler to this file. For example, the following command will set the scheduler for the hda device to cfq: $ su Password: # echo cfq > /sys/block/hda/queue/scheduler Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 1466, "s": 1454, "text": "Unix - Home" }, { "code": null, "e": 1489, "s": 1466, "text": "Unix - Getting Started" }, { "code": null, "e": 1512, "s": 1489, "text": "Unix - File Management" }, { "code": null, "e": 1531, "s": 1...
A Straightforward Guide to Cleaning and Preparing Data in Python | by Frank Andrade | Towards Data Science
Real-world data is dirty. In fact, around 80% of a data scientist's time is spent collecting, cleaning and preparing data. These tedious (but necessary) steps make the data suitable for any model we want to build and ensure the high quality of data. The cleaning and preparation of data might be tricky sometimes, so in this article, I would like to make these processes easier by showing some techniques, methods and functions used to clean and prepare data. To do so, we’ll use a Netflix dataset available on Kaggle that contains information about all the titles on Netflix. I’m using movie datasets because they’re frequently used in tutorials for many data science projects such as sentiment analysis and building a recommendation system. You can also follow this guide with a movie dataset from IMDb, MovieLens or any dataset that you need to clean. Although the Kaggle dataset might look well organized, it’s not ready to be used, so we’ll identify missing data, outliers, inconsistent data and do text normalization. This is shown in detail in the table below. Table of Contents1. Quick Dataset Overview2. Identify Missing Data - Create a percentage list with .isnull()3. Dealing with Missing Data - Remove a column or row with .drop, .dropna or .isnull - Replace it by the mean, median or mode - Replace it by an arbitrary number with .fillna()4. Identifying Outliers - Using histograms to identify outliers within numeric data - Using boxplots to identify outliers within numeric data - Using bars to identify outliers within categorical data5. Dealing with Outliers - Using operators & | to filter out outliers6. Dealing with Inconsistent Data Before Merging 2 Dataframes - Dealing with inconsistent column names - Dealing with inconsistent data type - Dealing with inconsistent names e.g. "New York" vs "NY"7. Text Normalization - Dealing with inconsistent capitalization - Remove blank spaces with .strip() - Remove or replace strings with .replace() or .sub()8. Merging Datasets - Remove duplicates with .drop_duplicates() The first thing to do once you downloaded a dataset is to check the data type of each column (the values of a column might contain digits, but they might not be datetime or int type) After reading the CSV file, type .dtypes to find the data type of each column. df_netflix_2019 = pd.read_csv('netflix_titles.csv')df_netflix_2019.dtypes Once you run that code, you’ll get the following output. show_id int64type objecttitle objectdirector objectcast objectcountry objectdate_added objectrelease_year int64rating objectduration objectlisted_in objectdescription objectdtype: object This will help you identify whether the columns are numeric or categorical variables, which is important to know before cleaning the data. Now to find the number of rows and columns, the dataset contains, use the .shape method. In [1]: df_netflix_2019.shapeOut[1]: (6234, 12) #This dataset contains 6234 rows and 12 columns. Missing data sometimes occurs when data collection was done improperly, mistakes were made in data entry, or data values were not stored. This happens often, and we should know how to identify it. A simple approach to identifying missing data is to use the .isnull() and .sum() methods df_netflix_2019.isnull().sum() This shows us a number of “NaN” values in each column. If the data contains many columns, you can use .sort_values(ascending=False) to place the columns with the highest number of missing values on top. show_id 0type 0title 0director 1969cast 570country 476date_added 11release_year 0rating 10duration 0listed_in 0description 0dtype: int64 That being said, I usually represent the missing values in percentages, so I have a clearer picture of the missing data. The following code shows the above output in % Now it’s more evident that a good number of directors were omitted in the dataset. show_id: 0.0%type: 0.0%title: 0.0%director: 31.58%cast: 9.14%country: 7.64%date_added: 0.18%release_year: 0.0%rating: 0.16%duration: 0.0%listed_in: 0.0%description: 0.0% Now that we identified the missing data, we have to manage it. There are different ways of dealing with missing data. The correct approach to handling missing data will be highly influenced by the data and goals your project has. That being said, the following cover 3 simple ways of dealing with missing data. If you consider it’s necessary to remove a column because it has too many empty rows, you can use .drop() and add axis=1 as a parameter to indicate that what you want to drop is a column. However, most of the time is just enough to remove the rows containing those empty values. There are different ways to do so. The first solution uses .drop with axis=0 to drop a row. The second identifies the empty values and takes the non-empty values by using the negation operator ~ while the third solution uses .dropna to drop empty rows within a column. If you want to save the output after dropping, use inplace=True as a parameter. In this simple example, we’ll not drop any column or row. Another common approach is to use the mean, median or mode to replace the empty values. The mean and median are used to replace numeric data, while the mode replaces categorical data. As we’ve seen before, the rating column contains 0.16% of missing data. We could easily complete that tiny portion of data with the mode since the rating is a categorical value. First, we calculated the mode (TV-MA), and then we filled all the empty values with .fillna. If the data is numeric, we can also set an arbitrary number to prevent removing any row without affecting our model's results. If the duration column was a numeric value (currently, the format is string e.g. 90 minutes), we could replace the empty values by 0 with the following code. df_netflix_2019['duration'].fillna(0, inplace=True) Also, you can use the ffill , bfill to propagate the last valid observation forward and backward, respectively. This is extremely useful for some datasets but it’s not useful in the df_netflix_2019 dataset. An outlier is that data that that differs significantly from other observations. A dataset might contain real outliers or outliers obtained after poor data collection or caused by data entry errors. We’re going to use the duration as a reference that will help us identify outliers in the Netflix catalog. The duration column is not considered a numerical value (e.g., 90) in our dataset because it’s mixed with strings (e.g., 90 min). Also, the duration of TV shows is in seasons (e.g., 2 seasons) so we need to filter it out. With the following code, we’ll take only movies from the dataset and then extract the numeric values from the duration column. Now the data is ready to be displayed in a histogram. You can make plots with matplotlib, seaborn or pandas in Python. In this case, I’ll do it with matplotlib. import matplotlib.pyplot as pltfig, ax = plt.subplots(nrows=1, ncols=1)plt.hist(df_movie['minute'])fig.tight_layout() The plot below reveals how the duration of movies is distributed. By observing the plot, we can say that movies in the first bar (3'–34') and the last visible bar (>189') are probably outliers. They might be short films or long documentaries that don’t fit well in our movie category (again, it still depends on your project goals) Another option to identify outliers is boxplots. I prefer using boxplots because it leaves outliers out of the box’s whiskers. As a result, it’s easier to identify the minimum and maximum values without considering the outliers. We can easily make boxplots with the following code. import seaborn as snsfig, ax = plt.subplots(nrows=1, ncols=1)ax = sns.boxplot(x=df_movie['minute'])fig.tight_layout() The boxplot shows that values below 43' and above 158' are probably outliers. Also, we can identify some elements of the boxplot like the lower quartile (Q1) and upper quartile (Q3) with the.describe() method. In [1]: df_movie['minute'].describe()Out [1]: count 4265.000000 mean 99.100821 std 28.074857 min 3.000000 25% 86.000000 50% 98.000000 75% 115.000000 max 312.000000 In addition to that, you can easily display all elements of the boxplot and even make it interactive with Plotly. import plotly.graph_objects as gofrom plotly.offline import iplot, init_notebook_modefig = go.Figure()fig.add_box(x=df_movie['minute'], text=df_movie['minute'])iplot(fig) In case the data is categorical, you can identify categories with few observations by plotting bars. In this case, we’ll use the built-in Pandas visualization to make the bar plot. fig=df_netflix_2019['rating'].value_counts().plot.bar().get_figure()fig.tight_layout() In the plot above, we can see that the mode (the value that appears most often in the column) is ‘TV-MA’ while ‘NC-17’ and ‘UR’ are uncommon. Once we identified the outliers, we can easily filter them out by using Python’s operators. Python operators are simple to memorize. & is the equivalent of and, while| is the equivalent of or. In this case, we’re going to filter out outliers based on the values revealed by the boxplot. #outliersdf_movie[(df_movie['minute']<43) | (df_movie['minute']>158)]#filtering outliers outdf_movie = df_movie[(df_movie['minute']>43) & (df_movie['minute']<158)] The df_movie created now contains only movies that last between 43' and 158'. A common task we often come across is merging dataframes to increase the information of an observation. Unfortunately, most of the time, datasets have many inconsistencies because they come from different sources. From now on, we’ll use a second dataset df_netflix_originals that contains only Netflix originals (.csv available on my Github), and we’ll merge it with the original dataset df_netflix_2019 to determine original and non-original content. A common issue we have to deal with is different column names between tables. Column names can be easily changed with the .rename method. If you try to merge 2 datasets based on a column that has different data types, Python will throw an error. That’s why you have to make sure the type is the same. If the same column have different types, you can use the .astype method to normalize it. Usually, the column and data type normalization is enough to merge to datasets; however, sometimes, there are inconsistencies between the data within the same column caused by data entry errors (typos) or disagreements in the way a word is written. Movies titles don’t usually have these problems. They might have a disagreement in punctuation (we’ll take care of this later), but movies usually have a standard name, so to explain how to deal with this problem, I’ll create a dataset and a list containing states written in different ways. There are many libraries that can help us solve this issue. In this case, I’ll use the fuzzywuzzy library. This will give a score based on the distance between 2 strings. You can choose the scorer that fits your data better. I will set scorer=fuzz.token_sort_ratio in this example. As we can see in the output, the scorer does a good job matching strings. states match scoreCA California 33 Hawai Hawaii 91 NY New York 40 Washington DC Washington 87 However, keep in mind that it can still match wrong names. Text normalization is necessary for Natural Language Processing. This involves the following techniques to make text uniform. Removing whitespace, punctuation and non-alphanumeric characters Tokenization, Stemming, Lemmatization, removing stop words To make things simple, this article will only cover the first point. However, in the article below, I explain how to tokenize text in Python. towardsdatascience.com Before merging 2 frames, we have to make sure most rows will match, and normalizing capitalization helps with it. There are many ways to lower case text within a frame. Below you can see two options (.apply or .str.lower) Sometimes data has leading or trailing white spaces. We can get rid of them with the .strip method Texts between two datasets often have disagreements in punctuation. You can remove it with .apply and .sub or by using .replace It’s good to use any of them with regular expressions. For example, the regex[^\w\s] will help you remove characters other than words (a-z, A-Z, 0–9, _ ) or spaces. Regular expressions (regex) might look intimidating, but they’re simpler than you think and are vital when extracting information from text data. In the link below, you’ll find a simple guide I made to easily learn regular expressions. towardsdatascience.com Finally, we can merge the dataset df_netflix_originals and df_netflix_2019. With this, we can identify which movies are Netflix originals and which only belong to the catalog. In this case, we do an outer join to give ‘Catalog’ value to all the rows with empty values in the "Original" column. One of the pitfalls of outer join with 2 key columns is that we’ll obtain duplicated rows if we consider a column alone. In this case, we merged based on the title and release_year columns, so most likely there are titles duplicated that have different release_year. You can drop duplicates within a column with the .drop_duplicates method The data grouped by type and origin is distributed like this. In[1]: df_netflix[['original', 'type']].value_counts()Out[1]:original type Catalog Movie 3763 TV Show 1466Netflix TV Show 1009 Movie 504 That’s it! Now the data is clean and ready to be processed! The code behind this analysis is available on my Github If you want to learn Python in Spanish, subscribe to my YouTube channel. Every week I publish videos like the one below. You can still clean more (if necessary) or use this data in your data science project as I did to find the best Netflix and Disney movies to learn a foreign language (NLP projects) towardsdatascience.com Some projects where I wrangled real-world data are the following:
[ { "code": null, "e": 421, "s": 171, "text": "Real-world data is dirty. In fact, around 80% of a data scientist's time is spent collecting, cleaning and preparing data. These tedious (but necessary) steps make the data suitable for any model we want to build and ensure the high quality of data." },...
chfn command in Linux with examples - GeeksforGeeks
15 May, 2019 chfn command in Linux allows you to change a user’s name and other details easily. chfn stands for Change finger. Basically, it is used to modify your finger information on Linux system. This information is generally stored in the file /etc/passwd that includes user’s original name, work phone number etc. Syntax: chfn [option] [login] Example: In this example we used default “chfn” command without any option. In this system asks from the user itself to change the values of some basic attributes. Options: -f full_name : Let you change the full name on the account. -w work_ph : Let you change the work phone number on the account. -r room_no : Let you change the room number on the account. -h home_ph : Let you change the home phone number on the account. -o other : Let you change any other detail on the account. linux-command Linux-system-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Thread functions in C/C++ mv command in Linux with examples nohup Command in Linux with Examples scp command in Linux with Examples Docker - COPY Instruction chown command in Linux with Examples nslookup command in Linux with Examples SED command in Linux | Set 2 Named Pipe or FIFO with example C program uniq Command in LINUX with examples
[ { "code": null, "e": 24015, "s": 23987, "text": "\n15 May, 2019" }, { "code": null, "e": 24322, "s": 24015, "text": "chfn command in Linux allows you to change a user’s name and other details easily. chfn stands for Change finger. Basically, it is used to modify your finger infor...
Symfony - Doctrine ORM
In Symfony web framework, model plays an important role. They are the business entities. They are either provided by customers or fetched from back-end database, manipulated according to business rules and persisted back into the database. They are the data presented by Views. Let us learn about models and how they interact with back-end system in this chapter. We need to map our models to the back-end relational database items to safely and efficiently fetch and persist the models. This mapping can be done with an Object Relational Mapping (ORM) tool. Symfony provides a separate bundle, DoctrineBundle, which integrates Symfony with third party PHP database ORM tool, Doctrine. By default, Symfony framework doesn't provide any component to work with databases. But, it integrates tightly with Doctrine ORM. Doctrine contains several PHP libraries used for database storage and object mapping. Following example will help you understand how Doctrine works, how to configure a database and how to save and retrieve the data. In this example, we will first configure the database and create a Student object, then perform some operations in it. To do this we need to adhere to the following steps. Create a Symfony application, dbsample using the following command. symfony new dbsample Generally, the database information is configured in “app/config/parameters.yml” file. Open the file and add the following changes. parameter.yml parameters: database_host: 127.0.0.1 database_port: null database_name: studentsdb database_user: <user_name> database_password: <password> mailer_transport: smtp mailer_host: 127.0.0.1 mailer_user: null mailer_password: null secret: 037ab82c601c10402408b2b190d5530d602b5809 doctrine: dbal: driver: pdo_mysql host: '%database_host%' dbname: '%database_name%' user: '%database_user%' password: '%database_password%' charset: utf8mb4 Now, Doctrine ORM can connect to the database. Issue the following command to generate “studentsdb” database. This step is used to bind the database in Doctrine ORM. php bin/console doctrine:database:create After executing the command, it automatically generates an empty “studentsdb” database. You can see the following response on your screen. Created database `studentsdb` for connection named default Mapping information is nothing but "metadata”. It is a collection of rules that informs Doctrine ORM exactly how the Student class and its properties are mapped to a specific database table. Well, this metadata can be specified in a number of different formats, including YAML, XML or you can directly pass Student class using annotations. It is defined as follows. Add the following changes in the file. <?php namespace AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table(name = "students") */ class Student { /** * @ORM\Column(type = "integer") * @ORM\Id * @ORM\GeneratedValue(strategy = "AUTO") */ private $id; /** * @ORM\Column(type = "string", length = 50) */ private $name; /** * @ORM\Column(type = "text") */ private $address; } Here, the table name is optional. If the table name is not specified, then it will be determined automatically based on the name of the entity class. Doctrine creates simple entity classes for you. It helps you build any entity. Issue the following command to generate an entity. php bin/console doctrine:generate:entities AppBundle/Entity/Student Then you will see the following result and the entity will be updated. Generating entity "AppBundle\Entity\Student" > backing up Student.php to Student.php~ > generating AppBundle\Entity\Student <?php namespace AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table(name="students") */ class Student { /** * @ORM\Column(type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\Column(type = "string", length = 50) */ private $name; /** * @ORM\Column(type = "text") */ private $address; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set name * * @param string $name * * @return Student */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Set address * * @param string $address * * @return Student */ public function setAddress($address) { $this->address = $address; return $this; } /** * Get address * * @return string */ public function getAddress() { return $this->address; } } After creating entities, you should validate the mappings using the following command. php bin/console doctrine:schema:validate It will produce the following result − [Mapping] OK - The mapping files are correct. [Database] FAIL - The database schema is not in sync with the current mapping file Since we have not created the students table, the entity is out of sync. Let us create the students table using the Symfony command in the next step. Doctrine can automatically create all the database tables needed for Student entity. This can be done using the following command. php bin/console doctrine:schema:update --force After executing the command, you can see the following response. Updating database schema... Database schema updated successfully! "1" query was executed This command compares what your database should look like with how it actually looks, and executes the SQL statements needed to update the database schema to where it should be. Now, again validate the schema using the following command. php bin/console doctrine:schema:validate It will produce the following result − [Mapping] OK - The mapping files are correct. [Database] OK - The database schema is in sync with the mapping files As seen in the Bind an Entity section, the following command generates all the getters and setters for the Student class. $ php bin/console doctrine:generate:entities AppBundle/Entity/Student Now, we have mapped the Student entity to its corresponding Student table. We should now be able to persist Student objects to the database. Add the following method to the StudentController of the bundle. <?php namespace AppBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; use AppBundle\Entity\Student; class StudentController extends Controller { /** * @Route("/student/add") */ public function addAction() { $stud = new Student(); $stud->setName('Adam'); $stud->setAddress('12 north street'); $doct = $this->getDoctrine()->getManager(); // tells Doctrine you want to save the Product $doct->persist($stud); //executes the queries (i.e. the INSERT query) $doct->flush(); return new Response('Saved new student with id ' . $stud->getId()); } } Here, we accessed the doctrine manager using getManager() method through getDoctrine() of base controller and then persist the current object using persist() method of doctrine manager. persist() method adds the command to the queue, but the flush() method does the actual work (persisting the student object). Create a function in StudentController that will display the student details. StudentController.php /** * @Route("/student/display") */ public function displayAction() { $stud = $this->getDoctrine() ->getRepository('AppBundle:Student') ->findAll(); return $this->render('student/display.html.twig', array('data' => $stud)); } Let’s create a view that points to display action. Move to the views directory and create a file “display.html.twig”. Add the following changes in the file. display.html.twig <style> .table { border-collapse: collapse; } .table th, td { border-bottom: 1px solid #ddd; width: 250px; text-align: left; align: left; } </style> <h2>Students database application!</h2> <table class = "table"> <tr> <th>Name</th> <th>Address</th> </tr> {% for x in data %} <tr> <td>{{ x.Name }}</td> <td>{{ x.Address }}</td> </tr> {% endfor %} </table> You can obtain the result by requesting the URL “http://localhost:8000/student/display” in a browser. It will produce the following output on screen − To update an object in StudentController, create an action and add the following changes. /** * @Route("/student/update/{id}") */ public function updateAction($id) { $doct = $this->getDoctrine()->getManager(); $stud = $doct->getRepository('AppBundle:Student')->find($id); if (!$stud) { throw $this->createNotFoundException( 'No student found for id '.$id ); } $stud->setAddress('7 south street'); $doct->flush(); return new Response('Changes updated!'); } Now, request the URL “http://localhost:8000/Student/update/1” and it will produce the following result. It will produce the following output on screen − Deleting an object is similar and it requires a call to the remove() method of the entity (doctrine) manager. This can be done using the following command. /** * @Route("/student/delete/{id}") */ public function deleteAction($id) { $doct = $this->getDoctrine()->getManager(); $stud = $doct->getRepository('AppBundle:Student')->find($id); if (!$stud) { throw $this->createNotFoundException('No student found for id '.$id); } $doct->remove($stud); $doct->flush(); return new Response('Record deleted!'); } Print Add Notes Bookmark this page
[ { "code": null, "e": 2567, "s": 2203, "text": "In Symfony web framework, model plays an important role. They are the business entities. They are either provided by customers or fetched from back-end database, manipulated according to business rules and persisted back into the database. They are the ...
Loading a csv file into Azure SQL Database from Azure Storage | by Mayank Srivastava | Towards Data Science
Over the weekend, I wanted to do a quick proof of concept on certain capabilities of Databricks and I wanted to use Azure SQL as a source. I faced quite bit of challenges and google was not kind enough to provide me a solution. I tried everything from bcp to bulk insert the file on my local computer and somehow it came out with errors which failed to fix. Finally I managed to load the csv file into database and thought of sharing this with everyone, so that if you have to quickly load data into Azure SQL Database and you don’t want to write a script in Databricks or use Azure Data Factory for such a simple task. And before you move ahead, I am assuming that you have a fair understanding of the Azure ecosystem particularly the Storage Account. So first things first, upload the file, you want to load into Azure SQL database, to a container in Azure Storage Account. You can use the normal Blob container and don’t have to use Azure Data Lake Storage for this. Second, you need to create a Shared Access Signature for the storage account Now go to the Azure SQL Database, where you would like to load the csv file and execute the following lines. Please replace the secret with the secret you have generated in the previous step. Also, please make sure you replace the location of the blob storage with the one you CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'YourStrongPassword1';CREATE DATABASE SCOPED CREDENTIAL MyAzureBlobStorageCredentialWITH IDENTITY = 'SHARED ACCESS SIGNATURE',SECRET = '******srt=sco&sp=rwac&se=2017–02–01T00:55:34Z&st=2016–12–29T16:55:34Z***************';NOTE: Make sure that you don't have a leading ? in SAS token, and that you have at least read permission on the object that should be loaded srt=o&sp=r, and expiration period is valid (all dates are in UTC time)CREATE EXTERNAL DATA SOURCE MyAzureBlobStorageWITH ( TYPE = BLOB_STORAGE,LOCATION = 'https://****************.blob.core.windows.net/adventureworks' , CREDENTIAL= MyAzureBlobStorageCredential Once you have done the above steps, you are left with only one last step and that is to insert the file into the table. Please remember to create the table in the database before you load the file and also remember to keep the schema of table exactly as the file structure, else you might run into errors. And the last step is BULK INSERT [dbo].[lnd_lending_club_acc_loans] FROM 'accepted_2007_to_2018Q4.csv'WITH ( CHECK_CONSTRAINTS, DATA_SOURCE = 'MyAzureBlobStorage', DATAFILETYPE='char', FIELDTERMINATOR=',', ROWTERMINATOR='0x0a', FIRSTROW=3, KEEPIDENTITY, TABLOCK); And if you have done everything correct, you can expect the table to be loaded with the data in the csv file. There are many other ways of doing this, but this one worked for me and was quite quick.
[ { "code": null, "e": 530, "s": 172, "text": "Over the weekend, I wanted to do a quick proof of concept on certain capabilities of Databricks and I wanted to use Azure SQL as a source. I faced quite bit of challenges and google was not kind enough to provide me a solution. I tried everything from bcp...
A Python Module for Maze Search Algorithms | by Muhammad Ahsan Naeem | Towards Data Science
The module pyamaze is created for the easy generation of random maze and apply different search algorithm efficiently. The main idea of this module, pyamaze, is to assist in creating customizable random mazes and be able to work on that, like applying the search algorithm with much ease. By using this module, you don’t need to program the GUI and also you don’t need the Object-Oriented Programming since the module will provide you the support. This module uses the Tkinter GUI framework which is built-in in Python and you don’t need to install any framework to use this module. The detail about the module is presented below and is also explained in this video Install the Package: On command prompt run the following command: pip install pyamaze Or you can visit the GitHub link and copy the module code as Python file named as pyamaze.py Here is the detail on how to use the module Generate a Maze: To simply generate a maze, you need to create the maze object and then apply the CreateMaze function. The last statement will be applying the function run to run the simulation. from pyamaze import mazem=maze()m.CreateMaze()m.run() A random 10x10 maze will be generated like this: The top-left cell is the goal of the maze and there are ways we can change the goal to any cell. Moreover, by default, a Perfect Maze is generated, which means all cells of the maze are accessible and there is one and only one path from any cell to the goal cell. Therefore any cell can be treated as the start cell and hence is not highlighted. Internally the last cell i.e. the last row and last column cell is set as the start cell. So, the general task will be finding the way from the bottom-right cell to the top-left cell. We can change the size of the maze while creating that. For example, a 5x5 maze can be generated as: from pyamaze import mazem=maze(5,5)m.CreateMaze()m.run() The first argument of the CreateMaze function is the row number and the second is the column number. To generate a maze of size 15x20, you should use the function as m.CreateMaze(15,20). It is important to know the maze parameters in order to use those in the program. Firstly the cells of the maze have two indices, one for row and the other for the column. The indices of the 5x5 maze generated previously are shown here: Optional Arguments of CreateMaze: To customize the generated maze, we can use different Optional Input arguments. Goal (x and y): To change the goal cell from (1,1) to some other cell we can provide the optional arguments x and y as the goal. For example, to make the cell (2,4) as goal we will use the function as CreateMaze(2,4) Pattern: We can generate a Horizontal (or Vertical) pattern maze. A horizontal pattern maze means the maze will have longer horizontal lines compared to the vertical line and similarly for the vertical pattern, the vertical maze lines will be longer. We can set the optional argument pattern to h or H for the horizontal pattern and v or V for the vertical pattern. For example, to generate a vertical pattern 5x5 maze with goal as cell (5,5), we will use the function as: m.CreateMaze(5,5,pattern=’v’) Sample generated maze is: Multiple Paths Maze: By default, the generated maze is Perfect Maze meaning just the one path from any cell to the goal cell. However, we can generate a maze with multiple paths by setting the optional argument loopPercent to some positive number. loopPercent set to highest value 100 means the maze generation algorithm will maximize the number of multiple paths for example as: m.CreateMaze(loopPercent=100) The generated maze is shown here: Save the generated Maze: There is also the possibility to save any generated maze for future use. For that, we need to set the optional argument saveMaze to True. The randomly generated maze will be saved in the working folder as a CSV file. The CSV file will contain the information of all cells inside the Maze and the information of the opened and closed walls in East West North and South directions. 1 means the path is opened in that direction and 0 means it is closed. We can later use the CSV file to generate the same old maze by using the loadMaze option and providing the CSV file. With this feature, we can also manually customize the Maze by changing the CSV file. To add or remove one wall from the Maze, we should change two values of the CSV file. While loading a Maze from the CSV file, the size of the Maze while creating the maze does not matter since the information about the size is also loaded from the CSV file. Theme: The default theme of the Maze is the Dark theme and we can change that to the Light theme by using the argument theme and setting that to the Light theme. We have a COLOR class as well inside the pyamze module to manage different colors. To set the theme to light, we can set that as a COLOR class object as: m.CreateMaze(theme=COLOR.light) or we can also provide the value as string as: m.CreateMaze(theme=”light”) Placing Agents inside the Maze: We can place agent (one or more) inside the Maze. An agent can be thought of as a physical agent like a robot or it can simply be used to highlight or point a cell in the maze. For that, we have the agent class in the module pyamaze. After importing the agent class, we can create the agent object and we should provide the parent Maze as the first input argument. By default, the agent will be placed on the start cell (the last cell) of the Maze. Here is complete code to create an agent on the default sized maze with light theme: from pyamaze import maze,COLOR,agentm=maze(10,10)m.CreateMaze(theme=COLOR.light)a=agent(m)m.run() Now let’s see different Optional Arguments of the agent class. Location of the agent: The default location of the agent is the start cell of the Maze which is the bottom-right corner of the Maze. You can change the location by setting the values x and y for the cell. The agent object has the two attributes x and y that you can access and set those later after an agent has been created. Moreover, the agent has an attribute position set to the tuple (x,y) that provides the complete x and y information as one parameter. You can also set it to some other value to change the position of the agent. Goal of the agent: The default goal for the agent is the goal of the Maze meaning the target for the agent is to reach the goal of the Maze. However, if you want to change the goal of the agent, you can do it by setting the argument goal while creating the agent. A two-valued tuple should be assigned as the goal of the agent. Size of the Agent: By default, the size of the agent is smaller than the cell dimensions. You can set the argument filled to True and the agent will fill the whole cell. Shape of the agent: By default, the agent is of square shape and there is a second option of shape arrow that you can set to the shape argument and the agent will be arrow-head shaped. This will differentiate the front and other sides of the agent. The argument filled has no effect if the shape is set to an arrow. See the footprints: When you will implement some search algorithm and the agent will move in the maze, it can be the requirement to visualize the complete path trace. For that, we can change the optional argument footprints equal to True and whenever the agent changes its position, an impression of footprints will be imposed on the previous location. Footprints is just the shape of the agent but with a different color shade. See the output yourself for this code: from pyamaze import maze,COLOR,agentm=maze(5,5)m.CreateMaze()a=agent(m,shape=’arrow’,footprints=True)a.position=(5,4)a.position=(5,3)a.position=(5,2)m.run() Other attributes of the Maze class: A few attributes of the Maze class that you should know to implement some search algorithm are: Rows: m.rows gives the number of rows of the maze m.Columns: m.cols gives the number of columns of the maze m.Grid: m.grid is a list with all cells from (1,1) to last.Map of the Maze: A Maze is generated randomly. It is important to know the information of different opened and closed walls of the Maze. That information is available in the attribute maze_map. It is a dictionary with the keys as the cells of the Maze and value as another dictionary with the information of the four walls of that cell in four directions; East, West, North and South. You can see the value of this attribute and confirm the values with the maze generated as: print(m.maze_map) The example maze generated and the value of the maze_map is shown here: maze_map = {(1, 1): {‘E’: 1, ‘W’: 0, ’N’: 0, ‘S’: 0}, (2, 1): {‘E’: 0, ‘W’: 0, ’N’: 0, ‘S’: 1}, (3, 1): {‘E’: 0, ‘W’: 0, ’N’: 1, ‘S’: 1}, (4, 1): {‘E’: 0, ‘W’: 0, ’N’: 1, ‘S’: 1}, (5, 1): {‘E’: 1, ‘W’: 0, ’N’: 1, ‘S’: 0}, (1, 2): {‘E’: 0, ‘W’: 1, ’N’: 0, ‘S’: 1}, (2, 2): {‘E’: 0, ‘W’: 0, ’N’: 1, ‘S’: 1}, (3, 2): {‘E’: 1, ‘W’: 0, ’N’: 1, ‘S’: 0}, (4, 2): {‘E’: 1, ‘W’: 0, ’N’: 0, ‘S’: 1}, (5, 2): {‘E’: 0, ‘W’: 1, ’N’: 1, ‘S’: 0}, (1, 3): {‘E’: 1, ‘W’: 0, ’N’: 0, ‘S’: 1}, (2, 3): {‘E’: 0, ‘W’: 0, ’N’: 1, ‘S’: 1}, (3, 3): {‘E’: 0, ‘W’: 1, ’N’: 1, ‘S’: 0}, (4, 3): {‘E’: 1, ‘W’: 1, ’N’: 0, ‘S’: 1}, (5, 3): {‘E’: 1, ‘W’: 0, ’N’: 1, ‘S’: 0}, (1, 4): {‘E’: 1, ‘W’: 1, ’N’: 0, ‘S’: 0}, (2, 4): {‘E’: 0, ‘W’: 0, ’N’: 0, ‘S’: 1}, (3, 4): {‘E’: 0, ‘W’: 0, ’N’: 1, ‘S’: 1}, (4, 4): {‘E’: 0, ‘W’: 1, ’N’: 1, ‘S’: 0}, (5, 4): {‘E’: 1, ‘W’: 1, ’N’: 0, ‘S’: 0}, (1, 5): {‘E’: 0, ‘W’: 1, ’N’: 0, ‘S’: 1}, (2, 5): {‘E’: 0, ‘W’: 0, ’N’: 1, ‘S’: 1}, (3, 5): {‘E’: 0, ‘W’: 0, ’N’: 1, ‘S’: 1}, (4, 5): {‘E’: 0, ‘W’: 0, ’N’: 1, ‘S’: 1}, (5, 5): {‘E’: 0, ‘W’: 1, ’N’: 1, ‘S’: 0}} Path from start to goal: The maze generation algorithm used in the pyamaze module (Recursive Backtracker) not just generates a random maze, but also has the information of the path from start to goal. This information is available in the attribute path of the Maze as a dictionary. The key of the path is a cell and value is also a cell representing the movement from key cell to value cell in order to reach the goal. Move the agent on a path: After creating a Maze and agent (one or more) inside the Maze, we can make the agent move on a specific path. The best will be moving the agent on the ***path*** attribute of the maze. For that, we have a method in the maze class named as tracePath that takes one dictionary as the input argument. The key of the dictionary is the agent and the value is the path we want that agent to follow. The tracePath method will simulate the agent moving on the path. Run this code and see the simulation yourself. from pyamaze import maze,agentm=maze(20,20)m.CreateMaze(loopPercent=50)a=agent(m,filled=True,footprints=True)m.tracePath({a:m.path})m.run() There are three ways we can specify a path for the agent to follow. Path as a Dictionary: As shown above the path can be a dictionary with key-value pairs representing the movement from key-cell to value-cell. Path as List: There is also a possibility to provide the path as a List of cells. Then the agent will follow the path starting from the first cell inside the list to the last cell. Path as String: We can also provide the path as a string of movement directions (EWNS), e.g. ‘EENWWSES’ is a string of 8 steps for the agent to follow. Optional Arguments in tracePath method: There are a couple of Optional arguments as well available with tracePath method. Kill the agent: It is possible to kill the agent after it completes the path. By setting the argument kill to True and the agent will be killed after 300 milliseconds after completing the path. Movement Speed: We can control the movement speed of the agent using the argument delay having the default value of 300 milliseconds. It is a time delay between the movement steps of the agent. Mark some cells: For different demonstrations, it might be needed to mark a few cells. For that, there is an option of showMarked that can be set to True and any cell present inside the list of maze markCell will be marked if the agent passes through that cell. Multiple Agents on different Paths: There is also the possibility to move multiple agents on their own paths. For that, we can provide more agent-path information inside the input dictionary to the tracePath method. There will be the movement against all agent-path pairs provided in the dictionary. Moreover, we can use the tracePath method multiple times. In that case, firstly all agents-paths provided the first time will complete their paths and then the other agent-path pairs provided second time in tracePath will start their movement and then so on. Controlling Agents with the keyboard Finally, there is also the possibility of controlling the agent with keyboard keys. For that, you can use the maze class method enableArrowKey and as the input argument, provide the agent to control with arrow keys. Likewise, an agent can be controlled using the keys WASD using the method enableWASD. Watch this video for more detail. Conclusion: The key idea behind creating this module is to facilitate generating maze of any size and different patterns. Moreover, we can place agents on the maze and control them. This will help implementing different maze search algorithms and your focus will be the search algorithm and not the effort to generate and display the maze. You can implement any maze search algorithm like Depth First Search, Breadth First Search, Best First Search, A-star Search, Dijakstra Algorithm, some Reinforcement Learning, Genetic Algorithm or any algorithm you can think of to solve a maze. This is the playlist on implementation of different Maze Search Algorithm using pyamaze module.
[ { "code": null, "e": 291, "s": 172, "text": "The module pyamaze is created for the easy generation of random maze and apply different search algorithm efficiently." }, { "code": null, "e": 755, "s": 291, "text": "The main idea of this module, pyamaze, is to assist in creating cus...
Reverse a string in Java - GeeksforGeeks
13 Oct, 2021 This article discusses different ways to reverse a string in Java with examples. Examples: Prerequisite: String vs StringBuilder vs StringBuffer in JavaFollowing are some interesting facts about String and StringBuilder classes : 1. Objects of String are immutable. 2. String class in Java does not have reverse() method, however StringBuilder class has built in reverse() method. 3. StringBuilder class do not have toCharArray() method, while String class does have toCharArray() method. 1. The idea is to traverse the length of the string 2. Extract each character while traversing 3. Add each character in front of the existing string Java // java program to reverse a word import java.io.*;import java.util.Scanner; class GFG { public static void main (String[] args) { String str= "Geeks", nstr=""; char ch; System.out.print("Original word: "); System.out.println("Geeks"); //Example word for (int i=0; i<str.length(); i++) { ch= str.charAt(i); //extracts each character nstr= ch+nstr; //adds each character in front of the existing string } System.out.println("Reversed word: "+ nstr); }} //Contributed by Tiyasa Converting String into Bytes: getBytes() method is used to convert the input string into bytes[]. Method: 1. Create a temporary byte[] of length equal to the length of the input string. 2. Store the bytes (which we get by using getBytes() method) in reverse order into the temporary byte[] . 3. Create a new String abject using byte[] to store result. Java // Java program to ReverseString using ByteArray.import java.lang.*;import java.io.*;import java.util.*; // Class of ReverseStringclass ReverseString { public static void main(String[] args) { String input = "GeeksforGeeks"; // getBytes() method to convert string // into bytes[]. byte[] strAsByteArray = input.getBytes(); byte[] result = new byte[strAsByteArray.length]; // Store result in reverse order into the // result byte[] for (int i = 0; i < strAsByteArray.length; i++) result[i] = strAsByteArray[strAsByteArray.length - i - 1]; System.out.println(new String(result)); }} Output: skeeGrofskeeG Using built in reverse() method of the StringBuilder class: String class does not have reverse() method, we need to convert the input string to StringBuilder, which is achieved by using the append method of StringBuilder. After that, print out the characters of the reversed string by scanning from the first till the last index. Java // Java program to ReverseString using StringBuilderimport java.lang.*;import java.io.*;import java.util.*; // Class of ReverseStringclass ReverseString { public static void main(String[] args) { String input = "Geeks for Geeks"; StringBuilder input1 = new StringBuilder(); // append a string into StringBuilder input1 input1.append(input); // reverse StringBuilder input1 input1.reverse(); // print reversed String System.out.println(input1); }} Output: skeeG rof skeeG Converting String to character array: The user input the string to be reversed. Method: 1. First, convert String to character array by using the built in Java String class method toCharArray(). 2. Then, scan the string from end to start, and print the character one by one. Java // Java program to Reverse a String by// converting string to characters one// by oneimport java.lang.*;import java.io.*;import java.util.*; // Class of ReverseStringclass ReverseString { public static void main(String[] args) { String input = "GeeksForGeeks"; // convert String to character array // by using toCharArray char[] try1 = input.toCharArray(); for (int i = try1.length - 1; i >= 0; i--) System.out.print(try1[i]); }} Output: skeeGrofskeeG Convert the input string into character array by using the toCharArray(): Convert the input string into character array by using the toCharArray() – built in method of the String Class. Then, scan the character array from both sides i.e from the start index (left) as well as from last index(right) simultaneously. 1. Set the left index equal to 0 and right index equal to the length of the string -1. 2. Swap the characters of the start index scanning with the last index scanning one by one. After that, increase the left index by 1 (left++) and decrease the right by 1 i.e., (right--) to move on to the next characters in the character array . 3. Continue till left is less than or equal to the right. Java // Java program to Reverse a String using swapping// of variablesimport java.lang.*;import java.io.*;import java.util.*; // Class of ReverseStringclass ReverseString { public static void main(String[] args) { String input = "Geeks For Geeks"; char[] temparray = input.toCharArray(); int left, right = 0; right = temparray.length - 1; for (left = 0; left < right; left++, right--) { // Swap values of left and right char temp = temparray[left]; temparray[left] = temparray[right]; temparray[right] = temp; } for (char c : temparray) System.out.print(c); System.out.println(); }} Output: skeeG roF skeeG Using ArrayList object: Convert the input string into the character array by using toCharArray() built in method. Then, add the characters of the array into the ArrayList object. Java also has built in reverse() method for the Collections class. Since Collections class reverse() method takes a list object, to reverse the list, we will pass the ArrayList object which is a type of list of characters. 1. We copy String contents to an object of ArrayList. 1. We create a ListIterator object by using the listIterator() method on the ArrayList object. 2. ListIterator object is used to iterate over the list. 3. ListIterator object helps us to iterate over the reversed list and print it one by one to the output screen. Java // Java program to Reverse a String using ListIteratorimport java.lang.*;import java.io.*;import java.util.*; // Class of ReverseStringclass ReverseString { public static void main(String[] args) { String input = "Geeks For Geeks"; char[] hello = input.toCharArray(); List<Character> trial1 = new ArrayList<>(); for (char c : hello) trial1.add(c); Collections.reverse(trial1); ListIterator li = trial1.listIterator(); while (li.hasNext()) System.out.print(li.next()); }} Output: skeeG roF skeeG Using StringBuffer: String class does not have reverse() method, we need to convert the input string to StringBuffer, which is achieved by using the reverse method of StringBuffer. Java // Java program to demonstrate conversion from// String to StringBuffer and reverse of stringimport java.lang.*;import java.io.*;import java.util.*; public class Test { public static void main(String[] args) { String str = "Geeks"; // conversion from String object to StringBuffer StringBuffer sbr = new StringBuffer(str); // To reverse the string sbr.reverse(); System.out.println(sbr); }} Output: skeeG Related Article: Different methods to reverse a string in C/C++This article is contributed by Mr. Somesh Awasthi. 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. vilaskolhe jigneshk5 abhishekbajhpa amulya k murthy shawosh casesensitiveunofficial Java-String-Programs Java-Strings Java School Programming Strings Java-Strings Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments HashMap in Java with Examples Interfaces in Java Object Oriented Programming (OOPs) Concept in Java ArrayList in Java How to iterate any Map in Java Python Dictionary Arrays in C/C++ Inheritance in C++ Interfaces in Java Operator Overloading in C++
[ { "code": null, "e": 24404, "s": 24376, "text": "\n13 Oct, 2021" }, { "code": null, "e": 24497, "s": 24404, "text": "This article discusses different ways to reverse a string in Java with examples. Examples: " }, { "code": null, "e": 24899, "s": 24499, "text"...
How to create a dynamic 2D array in Java?
If you wish to create a dynamic 2d array in Java without using List. And only create a dynamic 2d array in Java with normal array then click the below link You can achieve the same using List. See the below program. You can have any number of rows or columns. import java.util.ArrayList; import java.util.List; public class Tester { public static void main(String[] args) { List<int[]> rows = new ArrayList<>(); rows.add(new int[]{1,2,3}); rows.add(new int[]{1,2}); rows.add(new int[]{1}); //get element at row : 0, column : 0 System.out.println("[0][0] : " + rows.get(0)[0]); //get element at row : 1, column : 1 System.out.println("[1][1] : " + rows.get(1)[1]); } } [0][0] : 1 [1][1] : 2
[ { "code": null, "e": 1218, "s": 1062, "text": "If you wish to create a dynamic 2d array in Java without using List. And only create a dynamic 2d array in Java with normal array then click the below link" }, { "code": null, "e": 1322, "s": 1218, "text": "You can achieve the same u...
7 functions for your Exploratory Analysis in R | Towards Data Science
The EDA — Exploratory Data Analysis — phase of the Data Mining framework is one of the main activities when it comes to extracting information from a dataset. Whatever your ultimate goal is: Neural Networks, Statistical Analysis, or Machine Learning, everything should start with a good understanding and overview of the data you’re dealing with. One of the main characteristics of an EDA is that it is a somewhat open process that depends on the toolbox and the inventiveness of the Data Scientist. Unfortunately, this is both a blessing and a curse, as a poorly done EDA may hide relevant relationships in the data or even impair the study’s validity. Some of the activities that are usually carried out in an EDA (this is by no means an exhaustive list): Analysis of numerical variables: average, minimum and maximum values, data distribution. Analysis of categorical variables: list of categories, frequency of records in each category. Diagnosis of outliers and how they impact the distribution of data for each variable. Analysis of correlations between predictive variables. Relationship between predictive variables vs. the outcome variable. There is no magic formula when it comes to EDA, but there are certainly some packages and functions to keep in mind when analyzing your data to maintain the perfect balance of agility and flexibility in your analysis. The dataset used in this article is pretty well-known by everyone who has studied or practiced Data Science. It’s found here and it contains information on wines, made available in Portugal in 2008. It contains 1599 observations with 11 psychochemical attributes of Portuguese red wines and 1 target variable with a numerical discrete quality index from 0 to 10. The R programming language is one of the most widespread programming languages ​​among data enthusiasts. After extensive research, I have compiled a list with some of the best functions you should know to perform EDA on your data, focusing on functions that allow a more visual analysis, with tables and graphs. The visdat package has two interesting functions for a quick and practical overview of your dataset. The vis_dat function shows the variables, number of observations, and the type of each variable, in a way that’s very easy to interpret. visdat::vis_dat(wine,sort_type = FALSE) The vis_miss function, from the same package, allows you to view the number of missing values ​​per variable, thus giving an overview of the integrity of the dataset. Note: the dataset in question did not have any variable with Missing values, so some Missing Values were generated “artificially” for better visualization. The package called funModeling provides great functions to plot useful information about your dataset, from basic information about the variables to more specific information such as the gain of information that each variable provides, and the relationship between the predictive variables and the result variable. One of the functions to keep in mind is the plot_num function, which plots a histogram of each numeric variable. There are several similar functions in other packages and even ways to do the same directly through ggplot2, but the plot_num function greatly simplifies the task. With that, you have everything in one plot — of course, depending on the number of variables — an overview of your numerical varieties. As with numerical variables, it is important to have an overview of the categorical variables of your dataset. The inspect_cat function of the package inspectdf allows you to plot a summary of all categorical variables at once, showing the most common categories within each one. Note: the dataset used in the article did not have any categorical variables, so the image is illustrative and it was taken from here. The dlookr package is a package that has very interesting functions of analysis, data processing, and reporting and brings some of the best solutions when it comes to EDA for the R language. One of the aspects in which this package shines is in its information about outliers in numerical variables. Firstly, the diagnose_outlier function generates a data frame with information for each variable: count of outliers, the outliers x total observations-ratio, and the average with and without outliers. dlookr::diagnose_outlier(wine) The same package also offers the plot_outlier function, which shows plots for all variables in the value distribution with and without the aforementioned outliers. dlookr::plot_outlier(wine) As can be seen in the chlorides variable, several high values will certainly affect the results when applying statistical models, especially when some models have the assumption that the data is normally distributed. Note: it is important to remember that outliers should not always be removed, as in this case, they may indicate a specific subcategory of wines, especially due to the high concentration of outliers in this variable (7% of the values). There are many packages with functions to generate plots of correlations between variables in a dataset, but few provide a complete visualization of several factors like the chart.Correlation function of the PerformanceAnalytics package. chart.Correlation(wine[,2:7], histogram = TRUE, pch = 15) It presents: Numerical correlations (Pearson’s coefficient) between numerical variables in the dataset, with larger sources for larger correlations A mini-scatterplot between each of the pairs of variables A histogram and density plot of each variable Note: the function only accepts a data frame with only numeric variables as input, so you should perform this treatment beforehand if your dataset contains categorical predictive variables. A suggestion for this treatment is using the method keep (available in the dplyr package): wine %>% keep(is.numeric) That way, you keep only the numeric variables in the dataset. Some packages also have functions that automate the generation of EDA reports on their data set. The currently available report options vary in the extent and dimension of the analyzes presented, but all show some kind of summary of the dataset variables, information about missing values, histograms and bar graphs of each variable, etc. Possibly the best function I tested is the create_report function of the DataExplorer package. For a more standard analysis — which is already quite comprehensive — it allows you to generate a report with just one line of code: DataExplorer::create_report(wine) Luckily, this function goes far beyond that, since it is possible to customize various aspects of the report, from changing the layout and themes to adjusting specific parameters or choosing exactly which graphics should be included in the report. Note: It is always important to remember that there is no single solution that covers all the bases when it comes to data analysis and visualization and the automated report generation functions should also not be treated as such. Do you need a high-level overview of the dataset? visdat::vis_dat (overview) and visdat::vis_miss (missing values). Do you need information about the numeric variables? funModeling::plot_num. How about the categorical variables? inspectdf::inspect_cat. Correlations between variables? PerformanceAnalytics::chart.Correlation. How about an automated and configurable report?Package DataExplorer::create_report. And how about you? Is there a can’t-miss function to automate or aid in the visualization of your data in the Exploratory Analysis? Let me know in the comment section! 😁 We would first like to thank the developers responsible for creating and maintaining these incredible packages — which can all be found in R’s official repository, and also to the following sources consulted in my research:
[ { "code": null, "e": 518, "s": 171, "text": "The EDA — Exploratory Data Analysis — phase of the Data Mining framework is one of the main activities when it comes to extracting information from a dataset. Whatever your ultimate goal is: Neural Networks, Statistical Analysis, or Machine Learning, ever...
How to execute a particular test method multiple times (say 5 times) in TestNG?
We can execute a particular test method multiple times (say 5 times) with the help of the invocationCount helper attribute. @Test public void PaymentDetails(){ System.out.println("Payment details validation is successful”); } @Test(invocationCount=5) public void LoginAdmin(){ System.out.println("Login in admin is successful”); } @Test public void LeaseDetails(){ System.out.println("Lease details verification is successful”); } In the Java class file, the LoginAdmin() method with invocationCount set to 5 will result in Login in admin is a successful message to be printed five times on the console.
[ { "code": null, "e": 1186, "s": 1062, "text": "We can execute a particular test method multiple times (say 5 times) with the help of the invocationCount helper attribute." }, { "code": null, "e": 1502, "s": 1186, "text": "@Test\npublic void PaymentDetails(){\n System.out.printl...
OOAD Princhiples Q/A #4
Question:What do you mean by polymorphism? How Polymorphism is achieved at compile time and run time? Give an example of the polymorphism. Answer: Polymorphism refers to the ability to take more than one form. Polymorphism is the concept by which the same message or data can be sent to objects of several different classes. In the following example, same message is send to objects of different classes and the objects behave differently. Polymorphism is often considered the most powerful feature of an OOP language. In C++, polymorphism is implemented using the operator/function overloading. It is the ability of operator or a function to take more than one form. Polymorphism is classified in to two categories: Compile time polymorphism Compile time polymorphism Run time polymorphism Run time polymorphism In compile time polymorphism, the compiler is able to choose the appropriate function for a particular call at the compile time itself. It is also called static binding or early binding which means that the code associated with the function call is linked at compile time. In compile time polymorphism ,there are two types of overloading: operator overloading operator overloading function overloading function overloading The general syntax for defining operator overloading is: return_type classname :: operator op (argument list) { Body of function } Here return_type is the type of value returned by the operation. op is the operator being overloaded. operator is the function name. Body of the function contains set of instructions to be performed by operator function. // to overload unary minus'-' operator #include <iostream> using namespace std; class Counter { int a, b,c; public: void inputdata (int x, int y,int z); void display ( ); Counter operator–(const Counter& b ); }; void Counter::inputdata(int x, int y, int z) { a = x; b = y; c = z; } void Counter::display( ) { cout <<"x ="<<a<<endl; cout <<"y ="<<b<<endl; cout <<"z ="<<c<<endl; } Counter Counter::operator–(const Counter& b ) { Counter counter; counter.a = this->a - b.a; counter.b = this->b - b.b; counter.c = this->b - b.c; return counter; } int main() { Counter obj1; Counter obj2; Counter obj3; cout<<"obj1:"<<endl; obj1.inputdata (50,60, -70); cout<<"obj2:"<<endl; obj2.inputdata (40,50, -60); obj2.display( ): obj3 = obj1-obj2: cout<<"obj3:"<<endl; obj3.display( ); return 1; } Obj 1 : X =50 Y= 60 Z= -70 Obj 2: X =40 Y =50 Z =-60 Obj 3: X =10 Y =10 Z =-10 Function overloading is a concept where several function declarations are specified with a same name that perform similar tasks, but on different data types. Such functions are said to be overloaded. C++ allows functions to have the same name . These functions can only be distinguished by their number and type of arguments. int add (int a, int b); int add (int a, int b, int c); float add (float a, float b); The function add (int a, int b) which takes two integer inputs is different from the functions add (int a ,int b, int c) which takes three integer inputs and add (float a, float b ) which takes two float inputs. When an overloaded function is called, the C++ compiler selects the proper function by examining the number , types and order of the arguments in the call. Thus an overloaded function performs different activities depending on the kind of data sent to it. Function overloading not only implements polymorphism but also reduces number of comparisons in a program and thereby make the program to run faster. // program using concept of function overloading #include<iostream> #include<math> using namespace std; float area (float a, float b, float c) { float s, ar; s = (a+b+c)/2 ; ar = sqrt (s*(s-a)* (s-b)*(s-c)); return (ar); } float area (float a, float b) { return (a*b); } float area (float a ) { return (3.14*a*a); } int main ( ) { int choice ; float s1,s2,s3, ar; do { cout << Area/n"; cout <<"1.Rectangle\n"; cout <<"2.triangle\n"; cout <<"3.circle\n"; cout <<"4.exit\n"; cout <<enter your choice:"; cin>> choice ; switch (choice) { case 1: cout<<"enter length and breadth\n"; cin >>s1>>s2; ar =area (s1,s2); break; case 2: cout<<"enter three sides\n"; cin >>s1>>s2>>s3; ar =area (s1,s2,s3); break; case 3: cout<<"enter radius\n"; cin >>s1; ar =area (s1); break; case 4: break; default :cout <<"wrong choice"; } cout<<"the area is "<<ar <<endl; } while (choice!=4); return 1; } Area 1. Rectangle 2. triangle 3. circle 4. Exit Enter your choice :1 Enter length and breadth 10 20 The area is 200 Area 1. Rectangle 2. triangle 3. circle 4. Exit Enter your choice :2 Enter three sides 3 4 5 The area is 6 Area 1. Rectangle 2. triangle 3. circle 4. Exit Enter your choice :3 Enter radius 10 The area is 314 Area 1. Rectangle 2. triangle 3. circle 4. Exit Enter your choice : 4 If the appropriate member function is selected during the running program then it is called run time polymorphism . It is implemented using virtual function. Runtime polymorphism is also called as dynamic binding or late binding. Virtual functions: Virtual functions are special type of member functions which are defined in base class and are redefined in derived classes. The general syntax to declare a virtual function is class classname // base class of C++ virtual function { public : virtual void memberfunctionname ( ) // this denotes the c++virtual function { : } }; # include<iostream> using namespace std; class vehicle//base class of C++ virtual function { public: virtual void make ( ) // C++ virtual function { cout<<" member function of base class vehicle accessed" <<endl; } }; class fourwheeler : public vehicle { public: void make ( ) { cout <<" virtual member function of derived class fourwheeler accessed"<< endl; } }; int main ( ) { vehicle *a, *b; a = new vehicle ( ); a-> make ( ); b = new fourwheeler ( ); b-> make ( ); return 1; } Member function of base class vehicle accessed virtual member function of derived class fourwheeler accessed. In the above example , it is evidenced that after declaring the member functions make ( ) as virtual inside the base class vehicle, class fourwheeler is derived from the base class vechile. In the derived class , the new implementation for virtual function make ( ) is placed. Here, if the member function has not been declared as virtual, the base class member function is always called because linking takes place during compile time and is therefore static.In this example , the member function is declared virtual and the address is bounded only during run time, making it dynamic binding and thus the derived class member is called. To achieve the concept of dynamic binding in C++, the compiler creates a v-table each time a virtual function is declared. This V – table contains classes and pointers to the functions from each of the objects of the derived class. This is used by the compiler whenever a virtual function is needed. 14 Lectures 1.5 hours Harshit Srivastava 60 Lectures 8 hours DigiFisk (Programming Is Fun) 11 Lectures 35 mins Sandip Bhattacharya 21 Lectures 2 hours Pranjal Srivastava 6 Lectures 43 mins Frahaan Hussain 49 Lectures 4.5 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2126, "s": 1987, "text": "Question:What do you mean by polymorphism? How Polymorphism is achieved at compile time and run time? Give an example of the polymorphism." }, { "code": null, "e": 2134, "s": 2126, "text": "Answer:" }, { "code": null, "e"...
The Microsoft Data and Applied Scientist Interview | by Matt Przybyla | Towards Data Science
IntroductionProcessQuestionsConceptsSummaryReferences Introduction Process Questions Concepts Summary References The goal of this article is to give you more confidence and insight for your next interview at Microsoft. This guide can also apply to similar, big tech companies like Facebook and Apple. I will be discussing the role and interview process of the Senior Data and Applied Data Scientist at Microsoft. I have interviewed with numerous companies and after a while, I, as expected, started to see a trend in how they were arranged and executed. Recruiters, interviewers, and companies do not just want someone who can code well, but who can explain results to non-technical people as well. I also want to highlight that there are different roles like data scientist, applied scientist, and what I will be writing about: data and applied scientist. Along with the specific scientist role, there are levels that include the usual title, senior, and then principal. At other companies, you can expect to see roles like associate and staff. My experience in the Microsoft interview was great and I would recommend pursuing this role to anyone else who is interested. I especially loved hearing from the specific team. The focus on culture and diversity really stood out as an enticing factor in this position. In this article, I will detail the whole process as well as some questions that you can expect (or similar questions) during your interviews. Lastly, I want to stress that the point of this article is to ultimately help you interview at Microsoft or another, similar big tech company. I truly believe as a data science community, we should learn from one another and help everyone be the best they can be. Akin to how interviewers will eventually let you know (or so I hope), being open and adept to learning is more valuable than being quizzed. Below, find out more about the overall process from application to final interviews, questions, and concepts along with advice for your senior data and applied scientist interview journey. The overall interview process is surprisingly quite simple. After applying (hopefully), you can expect to get an email or phone call from the recruiter where you will have to submit an updated resume and information on why you are an appropriate fit for Microsoft. If you move forward after this point, you will have a 30 — 45 minute phone call with the manager going over why you think you are the right person for the role, as well as what interests you about it. You will want to focus on being yourself, knowing your past well, as well as the role, and Microsoft as a company even better. This phone call will include some technical conversation, but the next interview is when you will get to show off your skills in a round of four interviewers (in-person normally, but will probably be over a video conference at this time). This step is actually the final interview, but it will take around four hours, and is scheduled by a coordinator. The most important part of this day of interviews is to know key concepts and examples of machine learning algorithms. While coding is greatly used in these types of data science roles, it is arguably more important that you know the theory and point of an algorithm in data science over Python, R, or SQL code. The process will most likely be different with every interview, even at the same company, but the flow will be the same. It will entail the same manager you talked to over the phone previously that is mainly behavioral, a more in-depth data science algorithm question round from one person, a case study, and then an overall final summary of your data science knowledge. Here is an outline of the typical interview process: apply for the position hear back via phone call or email submit screening answers via email or phone initial manager interview over the phone four rounds of interview with the team in person (or most likely video conference) The following questions are not exact questions, but could very well be the exact questions you will encounter (as they are changed — but follow a similar format). The theme here is what is critical. If you can confidently answer these right now, then you can expect to do well overall. When answering questions, keep in mind it is okay to pause and think through your process, as it will show problem-solving and answers that do not sound memorized. Here are six questions you will need to know: 1. Explaining a machine learning algorithm to a non-technical user 2. Going over a time where you had a conflict at work 3. Giving an example of the machine learning pipeline 4. Explaining gradient descent 5. Describing dimensionality reduction 6. Providing an example of time series It is best to think of your answers in a business sense. While obtaining an accuracy of 95% for a machine learning model is impressive, it is even more impressive if you can explain to a business user or stakeholder how much money that will save the company, as well as how much you can automate an otherwise manual process. Knowing the common data science algorithms, like unsupervised versus supervised, along with time series and computer vision will be useful. Lastly, having a working knowledge of common Python libraries like sklearn and TensowFlow will also help to make you stand out. Aside from questions and skills, there are key concepts that will be discussed in your interview that are outlined below. While specific questions or key questions can be helpful to review, applying these concepts to your interview will be beneficial as well. All in all, you will want to know the role well by incorporating the department of the position or Microsoft product in your answers or discussions. You will also want to let them know when you do not know something; do not ramble about something you are unclear about and alternatively as a solution, possibly suggest a similar example and its respective explanation. Additionally, when you do use examples to explain an answer, try not to use the same one over and over again, as it will show that you do not have as much experience (even if you do). Lastly, even though the role’s description describes mainly data science and machine learning-centered skills, remember to know the key parts of deep learning and how it is different from conventional algorithms. Focus on these four concepts below: Incorporating Microsoft products Letting interviewers know when you do not know something Trying not to use the same example over and over again Deep learning Knowing the fundamental concepts of data science in addition to how they apply to Microsoft and its users, will be an impressive route to take in your interview process. Reviewing how businesses function in general will be beneficial — it will be better if you can provide how you would incorporate your model in a system that already exists — how the team would work, and what shortcomings could eventually happen. Testing your model is something data scientists may forget to practice. Not referring to testing your model on the dataset, but testing your model in production to see how it works, how fast it is, how much storage it uses, and overall, its possible limitations. Knowing the whole process from end-to-end will make you stand out as a candidate. Retrieving your data, cleaning and transforming it, building base models, secondary and tertiary modes (and so on), and the end product for the end-user is an entire process you should be familiar with that you can confidently explain. It will be good to talk about your Jupyter Notebook, but expounding upon object-oriented programming will be another bonus to show off to the interviewers. Displaying to the team how you created .py files that can be easily compiled and shared with not just other data scientists, but other professionals who are also interacting with your models, like the software engineers, machine learning engineers, and data engineers as well, will be an excellent concept to employ and describe. While there could be hundreds of questions and articles you could go over before your interview, ultimately, you will want to display to the interviewers your confidence in explaining your answer. You will be more likely to be hired if you make the interviewers comfortable in your answers by providing clear, correct, and confident explanations. Keep in mind that this overview is for a senior position, and more specifically, for a data and applied scientist role. You could most likely expect something similar for a non-senior role and also a data scientist and applied scientist role — in addition to general and interviews for non-data science roles. The common roles are: data scientist, applied scientist, and data and applied scientist. Just like the specific role and department can vary, so can the team that will interview you. Similar to a data science model, you will want to win the majority vote of the team to ace this interview. Another important facet of the interview process is not only coding and technical assessments, but behavioral valuations as well. It is important to focus your discussion on culture and diversity; find the pillars of Microsoft or a similar company to learn about their statement, how it applies to you, and what it means to you. Finally, keep your resume simple with: what you did, how it helped the business, and what the result was. For example, on one project you could say: I worked on a decision tree model that helped to automate a manual process by 50%. I cannot guarantee that you will get the job if you follow all of these steps, but I believe you will be well on your way to getting there if you are already going out of the way to learn about data science at Microsoft. I hope you found this article interesting, and especially useful for your future interview endeavors. Thank you for reading! [1] Photo by Franck V. on Unsplash, (2020) [2] Photo by visuals on Unsplash, (2020) [3] Photo by Lara Far on Unsplash, (2019) [4] Photo by Hitesh Choudhary on Unsplash, (2018)
[ { "code": null, "e": 226, "s": 172, "text": "IntroductionProcessQuestionsConceptsSummaryReferences" }, { "code": null, "e": 239, "s": 226, "text": "Introduction" }, { "code": null, "e": 247, "s": 239, "text": "Process" }, { "code": null, "e": 257, ...
The (Unofficial) Yahoo Finance API | by Doug Guthrie | Towards Data Science
I work in the financial services industry as a data analytics manager. My role is to support my organization in any data-related need. One project we’re working on is an internal application that relies heavily on financial data; my job was to find a way to supply the relevant data. If you search around the internet long enough you’ll be able to find solutions that will get you there (or partially there). I played around with IEX Cloud, Quandl, and others, which are great services but just aren’t free. So, like any developer looking for a solution, I started searching StackOverflow. I frequently came across Yahoo Finance as a possible solution, even though the note below sits at the top of the search results page for yahoo-finance: PLEASE NOTE : THIS API HAS BEEN DISCONTINUED BY YAHOO. Yahoo! Finance is a service from Yahoo! that provides financial information. It is the top financial news and research website in the United States. It looked like people were still utilizing the service though, either by web scraping or through URLs you could only find by searching through XHR requests. I knew that I didn’t want a web scraping solution, so I began scouring the network tab in Chrome’s developer tools for anything resembling data. Luckily, I stumbled upon some. pip install yahooquery The package provides three different classes that enable efficient and fast retrieval of data you can view through the front-end. The main class, where most of the data can be retrieved, is the Ticker class. Pretty easy, right? Just pass a symbol or list of symbols and you’re ready to retrieve most of the data available through Yahoo Finance. Before we go forward though, it’s important to know there are additional keyword arguments you can supply to modify certain behaviour: asynchronous, default False, optional: When set to True, requests made to Yahoo Finance will be made asynchronously. Only necessary when using more than one symbol. backoff_factor, default 0.3, optional: A factor, in seconds, to apply between attempts after the second try. For example, if the backoff factor is 0.1, then sleep() will sleep for [0.0s, 0.2s, 0.4s, ...] between retries country, default United States, optional: Alter the language, region, and corsDomain that each request utilizes as a query parameter. This functionality hasn’t been thoroughly tested, but you’ll see differences when utilizing the news method. Data will be returned for that country’s specific language. formatted, default False, optional: When formatted=True, most numerical data from the API will be returned as a dictionary: "totalCash": { "raw": 94051000320, "fmt": "94.05B", "longFmt": "94,051,000,320"} max_workers, default 8, optional: Defines the number of workers used to make asynchronous requests. This is only relevant when asynchronous=True proxies, default None, optional: Make each request with a proxy. Simply pass a dictionary, mapping URL schemes to the URL to the proxy. You can also configure proxies by setting the environment variables HTTP_PROXY and HTTPS_PROXY. retry, default 5, optional: Number of times to retry a failed request. status_forcelist, default [429, 500, 502, 503, 504], optional: A set of integer HTTP status codes that we should force a retry on. timeout, default 5, optional: Stop waiting for a response after a given number of seconds. user_agent, random selection, optional: A browser’s user-agent string that is sent in the headers with each request. validate, default False, optional: Validate existence of symbols during instantiation. Invalid symbols will be dropped but you can view them through the invalid_symbols property. verify, default True, optional: Either a boolean, in which case it controls whether we verify the server’s TLS certificate, or a string, in which case it must be a path to a CA bundle to use. username and password: If you subscribe to Yahoo Finance Premium, pass your username and password. You will be logged in and will now be able to access premium properties/methods. All premium properties/methods begin with p_. Disable two-factor authentication for this to work. The Ticker class can be broken up into a few different categories: modules, options, historical pricing, and premium data. The modules correspond (usually) to a tab or data within individual tabs from the Yahoo Finance front-end. For instance, to retrieve data from the ‘Summary’ tab, you would use the summary_detail property on the Ticker class. Or to find data within the ‘Statistics’ tab, you would use the properties valuation_measures and key_stats. All option expiration dates can be retrieved with a simple one-liner: faang = Ticker('fb aapl amzn nflx goog', asynchronous=True)options = faang.option_chain The variable options will be a pandas DataFrame. The DataFrame will contain a MultiIndex composed of the symbol, expiration date, and the option type (put or call). This one is pretty straight-forward: retrieve historical OHLC data for a symbol or list of symbols: faang = Ticker('fb aapl amzn nflx goog', asynchronous=True)history = faang.history() The above code will return daily YTD data. However, additional arguments can be supplied to the method: yahooquery.ticker.history(self, period='ytd', interval='1d', start=None, end=None)Historical pricing dataPulls historical pricing data for a given symbol(s)Parameters ---------- period: str, default ytd, optional Length of timeinterval: str, default 1d, optional Time between data pointsstart: str or datetime.datetime, default None, optional Specify a starting point to pull data from. Can be expressed as a string with the format YYYY-MM-DD or as a datetime object end: str of datetime.datetime, default None, optional Specify a ending point to pull data from. Can be expressed as a string with the format YYYY-MM-DD or as a datetime object.adj_timezone: bool, default True, optional Specify whether or not to apply the GMT offset to the timestamp received from the API. If True, the datetimeindex will be adjusted to the specified ticker's timezone.adj_ohlc: bool, default False, optional Calculates an adjusted open, high, low and close prices according to split and dividend informationReturns -------pandas.DataFrame historical pricing data Functionality is also available to retrieve data for Yahoo Finance Premium subscribers. The package utilizes Selenium, and chromedriver specifically, to login to Yahoo Finance. Once logged in, the user will be able to utilize premium methods and properties to retrieve data. One alternative to yahooquery is yfinance. It’s a package that offers similar functionality to retrieve data from Yahoo Finance. Currently, it has nearly 2,500 stars on GitHub, the highest amount when searching for python packages that offer data retrieval from Yahoo Finance. So, why should you use yahooquery over yfinance? Maintenance: yfinance does not seem to be maintained outside of external developers creating forks. Opinionated: In yfinance, each property call, outside of a couple, will call the same private method, _get_fundamentals. This means that the user has to retrieve all the data possible even if they’re only interested in one thing. The flip side to this though, is that each subsequent call that utilizes that private method takes almost no time because that data is already been stored in the Ticker instance. Source of data: yfinance retrieves the majority of data (outside of historical pricing and options) from scraping a javascript variable in each Ticker’s page. Yahooquery uses API endpoints for each property/method available to the user. Accuracy: The income statement, balance sheet, and cash flow methods are utilizing different endpoints. The one that’s used in yahooquery retrieves more data and is accurate when looking at companies outside the U.S. Simple: The dataframe that’s returned from retrieving historical pricing for multiple symbols is in a long format in yahooquery as opposed to a wide format for yfinance. Configuration: Keyword arguments allow for a lot of different configurations. Also, asynchronous requests are available throughout the library, not just for historical pricing like yfinance. Faster: See the Jupyter notebook below for different examples. View the documentation for in-depth use of the package yahooquery.dpguthrie.com View the source code on GitHub github.com View an interactive demo hosted on Heroku Reach out if you have questions, comments, or ways to improve the package
[ { "code": null, "e": 456, "s": 172, "text": "I work in the financial services industry as a data analytics manager. My role is to support my organization in any data-related need. One project we’re working on is an internal application that relies heavily on financial data; my job was to find a way ...
Ternary Operators in C/C++
The operators, which require three operands to act upon, are known as ternary operators. It can be represented by “ ? : ”. It is also known as conditional operator. The operator improves the performance and reduces the line of code. Here is the syntax of ternary operator in C language, Expression1 ? Expression2 : Expression3 Here is an example of Ternary Operators in C language, Live Demo #include <stdio.h> int main() { int a = -1; double b = 26.4231; int c = a? printf("True value : %lf",b):printf("False value : 0"); return 0; } True value : 26.423100 Expression1 will evaluate always while expression2 & expression3 are dependent on the outcome of expression1. If the outcome of expression1 is non-zero or negative, expression2 will display, otherwise expression3 will display. The ternary operator has a return type. The return type depends on expression2 and also on the convertibility of expression3 to expression2. If they are not convertible, the compiler will throw an error. Here is another example of ternary operator in C language, Live Demo #include <stdio.h> int main() { int x = -1, y = 3; double b = x+y+0.5; int c = x<y? printf("True value : %lf",b):printf("False value : 0"); return 0; } True value : 2.500000
[ { "code": null, "e": 1295, "s": 1062, "text": "The operators, which require three operands to act upon, are known as ternary operators. It can be represented by “ ? : ”. It is also known as conditional operator. The operator improves the performance and reduces the line of code." }, { "code"...
Deep Neural net with forward and back propagation from scratch - Python - GeeksforGeeks
08 Jun, 2020 This article aims to implement a deep neural network from scratch. We will implement a deep neural network containing a hidden layer with four units and one output layer. The implementation will go from very scratch and the following steps will be implemented.Algorithm: 1. Visualizing the input data 2. Deciding the shapes of Weight and bias matrix 3. Initializing matrix, function to be used 4. Implementing the forward propagation method 5. Implementing the cost calculation 6. Backpropagation and optimizing 7. prediction and visualizing the output Architecture of the model:The architecture of the model has been defined by the following figure where the hidden layer uses the Hyperbolic Tangent as the activation function while the output layer, being the classification problem uses the sigmoid function. Model Architecture Weights and bias:The weights and the bias that is going to be used for both the layers have to be declared initially and also among them the weights will be declared randomly in order to avoid the same output of all units, while the bias will be initialized to zero. The calculation will be done from the scratch itself and according to the rules given below where W1, W2 and b1, b2 are the weights and bias of first and second layer respectively. Here A stands for the activation of a particular layer. # Package importsimport numpy as npimport matplotlib.pyplot as plt# here planar_utils.py can be found on its github repofrom planar_utils import plot_decision_boundary, sigmoid, load_planar_dataset# Loading the Sample dataX, Y = load_planar_dataset() # Visualize the data:plt.scatter(X[0, :], X[1, :], c = Y, s = 40, cmap = plt.cm.Spectral); Code: Initializing the Weight and bias matrixHere is the number of hidden units is four, so, the W1 weight matrix will be of shape (4, number of features) and bias matrix will be of shape (4, 1) which after broadcasting will add up to the weight matrix according to the above formula. Same can be applied to the W2. # X --> input dataset of shape (input size, number of examples)# Y --> labels of shape (output size, number of examples) W1 = np.random.randn(4, X.shape[0]) * 0.01b1 = np.zeros(shape =(4, 1)) W2 = np.random.randn(Y.shape[0], 4) * 0.01b2 = np.zeros(shape =(Y.shape[0], 1)) Code: Forward Propagation :Now we will perform the forward propagation using the W1, W2 and the bias b1, b2. In this step the corresponding outputs are calculated in the function defined as forward_prop. def forward_prop(X, W1, W2, b1, b2): Z1 = np.dot(W1, X) + b1 A1 = np.tanh(Z1) Z2 = np.dot(W2, A1) + b2 A2 = sigmoid(Z2) # here the cache is the data of previous iteration # This will be used for backpropagation cache = {"Z1": Z1, "A1": A1, "Z2": Z2, "A2": A2} return A2, cache Code: Defining the cost function : # Here Y is actual outputdef compute_cost(A2, Y): m = Y.shape[1] # implementing the above formula cost_sum = np.multiply(np.log(A2), Y) + np.multiply((1 - Y), np.log(1 - A2)) cost = - np.sum(logprobs) / m # Squeezing to avoid unnecessary dimensions cost = np.squeeze(cost) return cost Code: Finally back-propagating function:This is a very crucial step as it involves a lot of linear algebra for implementation of backpropagation of the deep neural nets. The Formulas for finding the derivatives can be derived with some mathematical concept of linear algebra, which we are not going to derive here. Just keep in mind that dZ, dW, db are the derivatives of the Cost function w.r.t Weighted sum, Weights, Bias of the layers. def back_propagate(W1, b1, W2, b2, cache): # Retrieve also A1 and A2 from dictionary "cache" A1 = cache['A1'] A2 = cache['A2'] # Backward propagation: calculate dW1, db1, dW2, db2. dZ2 = A2 - Y dW2 = (1 / m) * np.dot(dZ2, A1.T) db2 = (1 / m) * np.sum(dZ2, axis = 1, keepdims = True) dZ1 = np.multiply(np.dot(W2.T, dZ2), 1 - np.power(A1, 2)) dW1 = (1 / m) * np.dot(dZ1, X.T) db1 = (1 / m) * np.sum(dZ1, axis = 1, keepdims = True) # Updating the parameters according to algorithm W1 = W1 - learning_rate * dW1 b1 = b1 - learning_rate * db1 W2 = W2 - learning_rate * dW2 b2 = b2 - learning_rate * db2 return W1, W2, b1, b2 Code: Training the custom model Now we will train the model using the functions defined above, the epochs can be put as per the convenience and power of the processing unit. # Please note that the weights and bias are global # Here num_iteration is epochsfor i in range(0, num_iterations): # Forward propagation. Inputs: "X, parameters". return: "A2, cache". A2, cache = forward_propagation(X, W1, W2, b1, b2) # Cost function. Inputs: "A2, Y". Outputs: "cost". cost = compute_cost(A2, Y) # Backpropagation. Inputs: "parameters, cache, X, Y". Outputs: "grads". W1, W2, b1, b2 = backward_propagation(W1, b1, W2, b2, cache) # Print the cost every 1000 iterations if print_cost and i % 1000 == 0: print ("Cost after iteration % i: % f" % (i, cost)) Output with learnt paramsAfter training the model, take the weights and predict the outcomes using the forward_propagate function above then use the values to plot the figure of output. You will have similar output. Visualizing the boundaries of data Conclusion:Deep Learning is a world in which the thrones are captured by the ones who get to the basics, so, try to develop the basics so strong that afterwards, you may be the developer of a new architecture of models which may revolutionalize the community. Deep-Learning Neural Network Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression ML | Underfitting and Overfitting Elbow Method for optimal value of k in KMeans Support Vector Machine Algorithm Clustering in Machine Learning Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 24636, "s": 24608, "text": "\n08 Jun, 2020" }, { "code": null, "e": 24907, "s": 24636, "text": "This article aims to implement a deep neural network from scratch. We will implement a deep neural network containing a hidden layer with four units and one output...
Best Time to Buy and Sell Stock II in Python
Suppose we have an array A, here A[i] is indicating the price of a given stock on day i. We have to find the maximum profit. We can complete as many transactions as we like. (Transaction means to buy and sell stocks). But we have to keep in mind that we may not engage in multiple transactions at the same time. So we have to sell the stock before buying the new one. Suppose the array is like A = [7, 1, 5, 3, 6, 4], then the result will be 7. As we can see, if we buy on day 2 (index 1), then it will take 1 as a buying price. Then if we sell on day 3, the profit will be 5 – 1 = 4. Then buy on day 4, and sell on day 5, so profit will be 6 – 3 = 3 To solve this, follow these steps − let answer = 0 for i in range 0 to n – 1 (n is the number of elements in A) −if A[i] – A[i – 1] > 0, thenanswer := answer + A[i] – A[i – 1] if A[i] – A[i – 1] > 0, thenanswer := answer + A[i] – A[i – 1] answer := answer + A[i] – A[i – 1] return answer Let us see the implementation to get a better understanding Live Demo class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ ans = 0 for i in range(1,len(prices)): if prices[i] - prices[i-1] >0: ans+=(prices[i] - prices[i-1]) return ans ob1 = Solution() print(ob1.maxProfit([7,2,5,8,6,3,1,4,5,4,7])) print(ob1.maxProfit([7,2,5,8,6,3,1,4,5,4,7])) 13
[ { "code": null, "e": 1430, "s": 1062, "text": "Suppose we have an array A, here A[i] is indicating the price of a given stock on day i. We have to find the maximum profit. We can complete as many transactions as we like. (Transaction means to buy and sell stocks). But we have to keep in mind that we...
How can I find the index of a 2d array of objects in JavaScript?
To find the index of a two-dimensional array of objects, use two for loops, one for row and another for column. Following is the code − function matrixIndexed(details, name) { var r; var c; for (r = 0; r < details.length; ++r) { const nsDetails = details[r]; for (c = 0; c < nsDetails.length; ++c) { const tempObject = nsDetails[c]; if (tempObject.studentName === name) { return { r, c}; } } } return {}; } const details = [ [ {studentName: 'John'}, {studentName:'David'} ], [ {studentName:"Mike"},{studentName:'Bob'},{studentName:'Carol'} ] ]; var {r, c } = matrixIndexed(details, 'Bob'); console.log(r, c); To run the above program, you need to use the following command − node fileName.js. Here, my file name is demo160.js. This will produce the following output − PS C:\Users\Amit\JavaScript-code> node demo160.js 1 1
[ { "code": null, "e": 1198, "s": 1062, "text": "To find the index of a two-dimensional array of objects, use two for loops, one for row and another for column. Following is the code −" }, { "code": null, "e": 1767, "s": 1198, "text": "function matrixIndexed(details, name) {\n va...
MySQL - SET autocommit Statement
The COMMIT statement saves all the modifications made in the current. If you commit a database, it saves all the changes that have been done till that particular point. By default, the MySQL database commits/saves the changes done automatically. You can turn off/on the auto-commit using the SET autocommit statement. Following is the syntax of the SET autocommit statement − SET autocommit=0; MySQL saves the changes done after the execution of each statement. To save changes automatically, set the autocommit option as shown below − SET autocommit=0; Assume we have created a table in MySQL with name EMPLOYEES as shown below − mysql> CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT); Query OK, 0 rows affected (0.36 sec) Following query saves the changes − mysql> COMMIT; Query OK, 0 rows affected (0.35 sec) Let us insert 4 records in to it using INSERT statements as − mysql> INSERT INTO EMPLOYEE VALUES ('Krishna', 'Sharma', 19, 'M', 2000), ('Raj', 'Kandukuri', 20, 'M', 7000), ('Ramya', 'Ramapriya', 25, 'F', 5000), ('Mac', 'Mohan', 26, 'M', 2000); Query OK, 4 rows affected (0.17 sec) Records: 4 Duplicates: 0 Warnings: 0 Now, update the age of the employees by one year − mysql> UPDATE EMPLOYEE SET AGE = AGE + 1; Query OK, 3 rows affected (0.06 sec) Rows matched: 3 Changed: 3 Warnings: 0 If you retrieve the contents of the table, you can see the updated values as − mysql> select * from EMPLOYEE; +------------+-----------+------+------+--------+ | FIRST_NAME | LAST_NAME | AGE | SEX | INCOME | +------------+-----------+------+------+--------+ | Krishna | Sharma | 20 | M | 2000 | | Raj | Kandukuri | 21 | M | 7000 | | Ramya | Ramapriya | 26 | F | 5000 | | Mac | Mohan | 27 | M | 2000 | +------------+-----------+------+------+--------+ 4 rows in set (0.09 sec) Following statement reverts the changes after the last commit. mysql> ROLLBACK; Query OK, 0 rows affected (0.00 sec) Since we have executed the COMMIT statement before inserting records if you verify the contents of the EMPLOYEE table, you will get an empty set as follow − mysql> SELECT * FROM EMPLOYEE; Empty set (0.06 sec) 31 Lectures 6 hours Eduonix Learning Solutions 84 Lectures 5.5 hours Frahaan Hussain 6 Lectures 3.5 hours DATAhill Solutions Srinivas Reddy 60 Lectures 10 hours Vijay Kumar Parvatha Reddy 10 Lectures 1 hours Harshit Srivastava 25 Lectures 4 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 2579, "s": 2333, "text": "The COMMIT statement saves all the modifications made in the current. If you commit a database, it saves all the changes that have been done till that particular point. By default, the MySQL database commits/saves the changes done automatically." }, ...
C# | Keywords - GeeksforGeeks
21 Jan, 2019 Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as variable names or objects. Doing this will result in a compile-time error. Example: // C# Program to illustrate the keywordsusing System; class GFG { // Here static, public, void // are keywords static public void Main () { // here int is keyword // a is identifier int a = 10; Console.WriteLine("The value of a is: {0}",a); // this is not a valid identifier // removing comment will give compile time error // double int = 10; }} Output: The value of a is: 10 There are total 78 keywords in C# as follows: Keywords in C# is mainly divided into 10 categories as follows: Value Type Keywords: There are 15 keywords in value types which are used to define various data types.boolbytechardecimaldoubleenumfloatintlongsbyteshortstructunitulongushortExample:// C# Program to illustrate the// value type keywordsusing System; class GFG { // Here static, public, void // are keywords static public void Main () { // here byte is keyword // a is identifier byte a = 47; Console.WriteLine("The value of a is: {0}",a); // here bool is keyword // b is identifier // true is a keyword bool b = true; Console.WriteLine("The value of b is: {0}",b); }}Output:The value of a is: 47 The value of b is: True Reference Type Keywords: There are 6 keywords in reference types which are used to store references of the data or objects. The keywords in this category are: class, delegate, interface, object, string, void. Modifiers Keywords: There are 17 keywords in modifiers which are used to modify the declarations of type member.publicprivateinternalprotectedabstractconsteventexternnewoverridepartialreadonlysealedstaticunsafevirtualvolatileExample:// C# Program to illustrate the// modifiers keywordsusing System; class Geeks { class Mod { // using public modifier // keyword public int n1; } // Main Method static void Main(string[] args) { Mod obj1 = new Mod(); // access to public members obj1.n1 = 77; Console.WriteLine("Value of n1: {0}", obj1.n1); } }Output:Value of n1: 77Statements Keywords: There are total 18 keywords which are used in program instructions.ifelseswitchdoforforeachinwhilebreakcontinuegotoreturnthrowtrycatchfinallycheckeduncheckedExample:// C# program to illustrate the statement keywordsusing System; class demoContinue { public static void Main() { // using for as statement keyword // GeeksforGeeks is printed only 2 times // because of continue statement for(int i = 1; i < 3; i++) { // here if and continue are keywords if(i == 2) continue; Console.WriteLine("GeeksforGeeks"); } } } Output:GeeksforGeeksMethod Parameters Keywords: There are total 4 keywords which are used to change the behavior of the parameters that passed to a method. The keyword includes in this category are: params, in, ref, out. Namespace Keywords: There are total 3 keywords in this category which are used in namespaces. The keywords are: namespace, using, extern. Operator Keywords: There are total 8 keywords which are used for different purposes like creating objects, getting a size of object etc. The keywords are: as, is, new, sizeof, typeof, true, false, stackalloc. Conversion Keywords: There are 3 keywords which are used in type conversions. The keywords are: explicit, implicit, operator. Access Keywords: There are 2 keywords which are used in accessing and referencing the class or instance of the class. The keywords are base, this. Literal Keywords: There are 2 keywords which are used as literal or constant. The keywords are null, default. Value Type Keywords: There are 15 keywords in value types which are used to define various data types.boolbytechardecimaldoubleenumfloatintlongsbyteshortstructunitulongushortExample:// C# Program to illustrate the// value type keywordsusing System; class GFG { // Here static, public, void // are keywords static public void Main () { // here byte is keyword // a is identifier byte a = 47; Console.WriteLine("The value of a is: {0}",a); // here bool is keyword // b is identifier // true is a keyword bool b = true; Console.WriteLine("The value of b is: {0}",b); }}Output:The value of a is: 47 The value of b is: True Example: // C# Program to illustrate the// value type keywordsusing System; class GFG { // Here static, public, void // are keywords static public void Main () { // here byte is keyword // a is identifier byte a = 47; Console.WriteLine("The value of a is: {0}",a); // here bool is keyword // b is identifier // true is a keyword bool b = true; Console.WriteLine("The value of b is: {0}",b); }} Output: The value of a is: 47 The value of b is: True Reference Type Keywords: There are 6 keywords in reference types which are used to store references of the data or objects. The keywords in this category are: class, delegate, interface, object, string, void. Modifiers Keywords: There are 17 keywords in modifiers which are used to modify the declarations of type member.publicprivateinternalprotectedabstractconsteventexternnewoverridepartialreadonlysealedstaticunsafevirtualvolatileExample:// C# Program to illustrate the// modifiers keywordsusing System; class Geeks { class Mod { // using public modifier // keyword public int n1; } // Main Method static void Main(string[] args) { Mod obj1 = new Mod(); // access to public members obj1.n1 = 77; Console.WriteLine("Value of n1: {0}", obj1.n1); } }Output:Value of n1: 77 Example: // C# Program to illustrate the// modifiers keywordsusing System; class Geeks { class Mod { // using public modifier // keyword public int n1; } // Main Method static void Main(string[] args) { Mod obj1 = new Mod(); // access to public members obj1.n1 = 77; Console.WriteLine("Value of n1: {0}", obj1.n1); } } Output: Value of n1: 77 Statements Keywords: There are total 18 keywords which are used in program instructions.ifelseswitchdoforforeachinwhilebreakcontinuegotoreturnthrowtrycatchfinallycheckeduncheckedExample:// C# program to illustrate the statement keywordsusing System; class demoContinue { public static void Main() { // using for as statement keyword // GeeksforGeeks is printed only 2 times // because of continue statement for(int i = 1; i < 3; i++) { // here if and continue are keywords if(i == 2) continue; Console.WriteLine("GeeksforGeeks"); } } } Output:GeeksforGeeks Example: // C# program to illustrate the statement keywordsusing System; class demoContinue { public static void Main() { // using for as statement keyword // GeeksforGeeks is printed only 2 times // because of continue statement for(int i = 1; i < 3; i++) { // here if and continue are keywords if(i == 2) continue; Console.WriteLine("GeeksforGeeks"); } } } Output: GeeksforGeeks Method Parameters Keywords: There are total 4 keywords which are used to change the behavior of the parameters that passed to a method. The keyword includes in this category are: params, in, ref, out. Namespace Keywords: There are total 3 keywords in this category which are used in namespaces. The keywords are: namespace, using, extern. Operator Keywords: There are total 8 keywords which are used for different purposes like creating objects, getting a size of object etc. The keywords are: as, is, new, sizeof, typeof, true, false, stackalloc. Conversion Keywords: There are 3 keywords which are used in type conversions. The keywords are: explicit, implicit, operator. Access Keywords: There are 2 keywords which are used in accessing and referencing the class or instance of the class. The keywords are base, this. Literal Keywords: There are 2 keywords which are used as literal or constant. The keywords are null, default. Important Points: Keywords are not used as an identifier or name of a class, variable, etc. If you want to use a keyword as an identifier then you must use @ as a prefix. For example, @abstract is valid identifier but not abstract because it is a keyword. Example: int a = 10; // Here int is a valid keyword double int = 10.67; // invalid because int is a keyword double @int = 10.67; // valid identifier, prefixed with @ int @null = 0; // valid // C# Program to illustrate the use of // prefixing @ in keywordsusing System; class GFG { // Here static, public, void // are keywords static public void Main () { // here int is keyword // a is identifier int a = 10; Console.WriteLine("The value of a is: {0}",a); // prefix @ in keyword int which // makes it a valid identifier int @int = 11; Console.WriteLine("The value of a is: {0}",@int); }} Output: The value of a is: 10 The value of a is: 11 These are used to give a specific meaning in the program. Whenever a new keyword comes in C#, it is added to the contextual keywords, not in the keyword category. This helps to avoid the crashing of programs which are written in earlier versions. Important Points: These are not reserved words. It can be used as identifiers outside the context that’s why it named contextual keywords. These can have different meanings in two or more contexts. There are total 30 contextual keywords in C#. Example: // C# program to illustrate contextual keywordsusing System; public class Student { // Declare name field private string name = "GeeksforGeeks"; // Declare name property public string Name { // get is contextual keyword get { return name; } // set is a contextual // keyword set { name = value; } } } class TestStudent { // Main Method public static void Main(string[] args) { Student s = new Student(); // calls set accessor of the property Name, // and pass "GFG" as value of the // standard field 'value'. s.Name = "GFG"; // displays GFG, Calls the get accessor // of the property Name. Console.WriteLine("Name: " + s.Name); // using get and set as identifier int get = 50; int set = 70; Console.WriteLine("Value of get is: {0}",get); Console.WriteLine("Value of set is: {0}",set); } } Output: Name: GFG Value of get is: 50 Value of set is: 70 Reference: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ CSharp-Basics CSharp-keyword C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between Abstract Class and Interface in C# C# | How to check whether a List contains a specified element C# | IsNullOrEmpty() Method Difference between Ref and Out keywords in C# String.Split() Method in C# with Examples C# | Arrays of Strings C# | Delegates Top 50 C# Interview Questions & Answers Extension Method in C# C# | Abstract Classes
[ { "code": null, "e": 24889, "s": 24861, "text": "\n21 Jan, 2019" }, { "code": null, "e": 25145, "s": 24889, "text": "Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not ...
Downloading Data From Twitter Using the REST API | by z_ai | Towards Data Science
Hey there everyone! This is the second article of a list of publications about adquiring data from Twitter and using it to gain certain insights, like the most influential users on a certain trend, topic modelling and much more. If you have not read the first article, you can take a look at it here: medium.com While the previous article discussed how to gather data from Twitter that is being produced on real time, this new article will cover how to collect historical data, like the previous tweets of a certain user, his followers, or his friends. Lets get started! While using the Streaming Twitter API we collected data that was produced on real time, the REST API serves the opposite purpose: gathering data that was produced before the time of collection, ie. historical data. Using this API we can collect old tweets containing certain keywords, similarly to how it was done before, but we can also gather other information that is relevant to the platform, like the friends and followers of different user accounts, retweets from a certain account, or retweeters of a certain tweet. Users inside the Twitter APIs are identifided by two different variables: The user screen_name, which is the Twitter name with the @ that we are all used to. For example “@jaimezorno”. The user_id, which is an unique numerical identifier for each Twitter user, which is a very long numerical string, like 747807250819981312 for example. In the data collection process, when we want to specify the user that we want to collect data from, we can either do it using the screen_name or the user_id of such user, so before diving into the more complex functions that are provided by the REST API, we will look at the how to obtain the Twitter Id of a certain user for whom we have the username and vice versa. Going from the Twitter Id to the user Screen name is needed as some of the functions that we will describe later return the Twitter identifier instead of the user screen names, so we need this functionality if we want to see who are the actual users associated with the corresponding ids. As always the first step is to collect to the Twitter API. import tweepy import time access_token = "ENTER YOUR ACCESS TOKEN" access_token_secret = "ENTER YOUR ACCESS TOKEN SECRET" consumer_key = "ENTER YOUR CONSUMER KEY" consumer_secret = "ENTER YOUR CONSUMER SECRET" auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) In the code, replace “ENTER YOUR ....” with your credentials, and then run the three last lines to create a connection to the Twitter REST API. Notice how this time we do not create a stream object, like we did to use the streaming API, but an api object. Once we have done this, going from screen name to id and vice versa is very simple, and it is done by running the lines in the following block of code: user = api.get_user(screen_name = 'theresa_may') print(user.id) This block, which queries the REST API for the user_id of Theresa May’s official Twitter acount, returns: 747807250819981312, which is the id associated which such account. It is important here to see that the screen_name does not include the @. To do this in the opposite direction, and gather the screen name of an account for whom we know the id, it is as easy as: user = api.get_user(747807250819981312) print(user.screen_name) which would print: theresa_may. As we can see both, the Id and the screen name, are attributes of the user object returned by the API, which contains a lot of valuable information like the user follower count, number of publications, date of creation of the account and much more. These parameters will be explored on a different post. It is as easy as that to go from username to id and the other way around. Now lets explore more complex and useful functionalities of the REST API. The timeline of a certain user are the past tweets that he or she has published or retweeted. It is useful to collect this information to get an idea of the previous activity of a certain account within the social network. We have to know however, that the method that will be used can only return tweets from the last 3200 of a specific user, so if we are gathering posts of a very active account and want tweets from a very long time ago, we will not be able to obtain them. This is a known limitation of the Twitter API, with no fix in the horizon, as by doing this, Twitter does not have to store ALL of the the tweets that have ever been produced by every single Twitter account. After having created a connection to the Twitter REST API like described above, to collect the timeline of a user we have to use a code structure similar to what appears in the following block: try: for tweet in tweepy.Cursor(api.user_timeline, screen_name="theresa_may", exclude_replies=True).items(): print(tweet) except tweepy.TweepError: time.sleep(60) As we can see, this code introduces a new concept inherent to the Twitter API: the Cursor Object. As intimidating as it might seem, it is nothing more than the way that the API has to handle pagination and be able to deliver content in an efficient and ordered manner. In this case we would be collecting the historical tweets from the user @theresa_may excluding the replies to tweets from other users. A similar parameter include_rts can be added to eliminate the retweets from this users timeline. Also, try-except duo was added to handle any errors we could find, like request rate exceeded or protected users. This is very frequent when opperating with APIs of this sort. The output of this code is a very ugly looking object called a Status Object for every tweet, that looks like this: Status(_api=<tweepy.api.API object at 0x000001C52728A710>, _json={'created_at': 'Sun May 12 11:55:41 +0000 2019', 'id': 1127542860520329216, 'id_str': '1127542860520329216', 'text': 'Congratulations to @SPendarovski on your inauguration as President of North Macedonia. I witnessed the strong relat............ Another post, like with the user object case, will explain in detail the nature of these objects and their attributes, however for now we will only describe how to collect some of the most interesting fields from it. Let’s see how we can do this. We will keep the same code structure than in the previous block, but adding some extra lines, which we will use to grab the parts of the status object that we find most relevant. try: for tweet in tweepy.Cursor(api.user_timeline, screen_name="theresa_may", exclude_replies=True, count = 10).items(): tweet_text = tweet.text time = tweet.created_at tweeter = tweet.user.screen_name print("Text:" + tweet_text + ", Timestamp:" + str(time) + ", user:" + tweeter) except tweepy.TweepError: time.sleep(60) This time, executing this block of code should print something like: Text:We’re driving the biggest transformation in mental health services for more than a generation. https://t.co/qOss2jOh4c, Timestamp:2019-06-17 07:19:59, user:theresa_mayText:RT @10DowningStreet: PM @Theresa_May hosted a reception at Downing Street to celebrate:✅ 22 new free schools approved to open ✅ 19,000 ad..., Timestamp:2019-06-15 13:53:34, user:theresa_mayText:Two years on from the devastating fire at Grenfell Tower, my thoughts remain with the bereaved, the survivors and t... https://t.co/Pij3z3ZUJB, Timestamp:2019-06-14 10:31:59, user:theresa_may Take into account that the tweets that you will get depend on the tweets published by the user you are searching for before the time of executing the code, so you will most likely not get the same tweets as me if you run these blocks with theresa_may as the target user. As nicer as the return from the previous block of code might look, we might want the data in a format that makes it easy to store and process later, like JSON for example. We will make one last modification to our code in order to print out each tweet, along with the fields from that tweet that we want, as a JSON object. For this we will need to import the json library and make some further changes to our code, like shown below: import json try: for tweet in tweepy.Cursor(api.user_timeline, screen_name="theresa_may", exclude_replies=True, count = 10).items(): tweet_text = tweet.text time = tweet.created_at tweeter = tweet.user.screen_name tweet_dict = {"tweet_text" : tweet_text.strip(), "timestamp" : str(time), "user" :tweeter} tweet_json = json.dumps(tweet_dict) print(tweet_json) except tweepy.TweepError: time.sleep(60) This time we will be outputting the same fields as before but in a JSON format, that makes it easy for other people to process and understand. The output for the same tweet in this case would be: {"tweet_text": "We\u2019re driving the biggest transformation in mental health services for more than a generation. https://t.co/qOss2jOh4c", "timestamp": "2019-06-17 07:19:59", "user": "theresa_may"}{"tweet_text": "RT @10DowningStreet: PM @Theresa_May hosted a reception at Downing Street to celebrate:\n\u2705 22 new free schools approved to open \n\u2705 19,000 ad\u2026", "timestamp": "2019-06-15 13:53:34", "user": "theresa_may"}{"tweet_text": "Two years on from the devastating fire at Grenfell Tower, my thoughts remain with the bereaved, the survivors and t\u2026 https://t.co/Pij3z3ZUJB", "timestamp": "2019-06-14 10:31:59", "user": "theresa_may"} After having seen how to efficiently collect and process the timeline of a certain user, we will look at how we can collect their friends and followers. Fetching the followers of a group of users is one of the most looked for actions in Twitter research, as creating follower/followee networks can provide some very interesting insights into a certain group of users who tweet about a topic or hashtag. To get the followers of a certain user, it’s as easy as connecting to the API using our credentials like it was done before and then running the following code: try: followers = api.followers_ids(screen_name="theresa_may") except tweepy.TweepError: time.sleep(20) By setting the parameter wait_on_rate_limit to True in api = tweepy.API(auth, wait_on_rate_limit=True) when we make the connection to the API, the error of exceeding the rate limit when downloading any kind of data is avoided, so despite of not having used it in the previous parts of this post, I suggest using it whenever you are going to be downloading large amounts of data from the Twitter REST API. followers here would be a list with the Ids of all the followers of the account @theresa_may. These Ids could then be translated to usernames using the api.get_user method that we have previously described. If we want to collect the followers for a certain group of users, we only need to add a couple of lines of code to the previous block, like so: user_list = ["AaltoUniversity", "helsinkiuni","HAAGAHELIAamk", "AaltoENG"]follower_list = [] for user in user_list: try: followers = api.followers_ids(screen_name=user) except tweepy.TweepError: time.sleep(20) continue follower_list.append(followers) In this case we would be collecting the followers of user accounts related to universities in Finland. The output of this code would be a list (follower_list) which in each index has a list with the followers of the account from user_list with the same index. Relating these two lists (the user and the follower lists) is very easy using the enumerate function: for index, user in enumerate(user_list): print("User: " + user + "\t Number of followers: " + str(len(follower_list[index]))) The output of this block would be: User: AaltoUniversity Number of followers: 5000User: helsinkiuni Number of followers: 5000User: HAAGAHELIAamk Number of followers: 4927User: AaltoENG Number of followers: 144 which might leave you wondering: Do the accounts @AaltoUniversity and @helsinkiuni have exactly the same number of followers and that is exactly 5000? The most obvious answer here is no. If you check the Twitter accounts of both universities, they both have followers in the range of the tenths of thousands. So why do we only get 5000 then? Well, this is because for issues involving pagination, the Twitter API breaks up their responses in different pages that we could think of as “chunks” of the requested information of a certain maximum size, and to go from one page to the following we need to use a special kind of object called a Cursor object, which was mentioned above. The following code uses the same function but this time with a cursor object to be able to grab all the followers of each user: user_list = ["AaltoUniversity", "helsinkiuni","HAAGAHELIAamk", "AaltoENG"] follower_list = [] for user in user_list: followers = [] try: for page in tweepy.Cursor(api.followers_ids, screen_name=user).pages(): followers.extend(page) except tweepy.TweepError: time.sleep(20) continue follower_list.append(followers) This time, if we use the enumerate loop to print each user and their number of followers, the output would be: User: AaltoUniversity Number of followers: 35695User: helsinkiuni Number of followers: 31966User: HAAGAHELIAamk Number of followers: 4927User: AaltoENG Number of followers: 144 which is the real number of followers of each of the accounts. In a similar way to how we can collect the followers of a certain user, we can also collect his “friends”, which is the group of people a certain user follows. For this, as always, we will start by connecting to the API with our credentials, and then running the following code: friends = [] try: for page in tweepy.Cursor(api.friends_ids, screen_name="theresa_may").pages(): friends.extend(page) except tweepy.TweepError: time.sleep(20) The variable friends from this block of code would be a list with all the friends of the user whose screen_name we select (theresa_may in this case) If we are not interested in who the followers/friends of a certain account are, but only in how many they are, the Twitter API allows us to collect this information without having to collect all of the followers/friends of the desired account. To do this without actually having to collect all the followers (which can take a while if the user has many, taking into account the download rate limit) we can use the api.get_user method that we have used before for going from user.screen_name to user.id and vice-versa. The following block of code shows how: user = api.get_user(screen_name = 'theresa_may') print(user.followers_count) print(user.friends_count) which would output: 83939129 We can also do this using the Twitter user.id, if we know it, as seen before, like so: user = api.get_user(747807250819981312)print(user.followers_count) print(user.friends_count) which would output again : 83939129 That as we can see from Theresa’s May official account, is the correct number of followers and friends. We have described the main functionalities of the Twitter REST API, and tackled some of the possible issues we might find when collecting data from it. This data can then be used for a lot for purposes: from trend or fake news detection using complex Machine Learning algorithms, to Sentiment Analysis for inferring how positive the feeling of a certain brand is, graph building, information diffusion models and much more. For further research, or clarification of the information found here refer to the previous links left throughout this guide or to: · Twitter Developers page: https://developer.twitter.com/en/docs · Tweepy’s github page: https://github.com/tweepy/tweepy · Tweepy’s official page: https://www.tweepy.org/ Twitter’s advanced search: https://twitter.com/search-advanced Stay tuned for more post in Social Network Analysis!
[ { "code": null, "e": 401, "s": 172, "text": "Hey there everyone! This is the second article of a list of publications about adquiring data from Twitter and using it to gain certain insights, like the most influential users on a certain trend, topic modelling and much more." }, { "code": null...
Generating random hex color in JavaScript
We are required to write a JavaScript function randomColor that returns a randomly generated hex color every time it is called. Therefore, let’s write the code for this function − The code for this will be − const randomColor = () => { let color = '#'; for (let i = 0; i < 6; i++){ const random = Math.random(); const bit = (random * 16) | 0; color += (bit).toString(16); }; return color; }; console.log(randomColor()); console.log(randomColor()); console.log(randomColor()); console.log(randomColor()); console.log(randomColor()); console.log(randomColor()); console.log(randomColor()); The output in the console will be − #762b46 #cfa0bf #a20ee1 #c2f7e0 #5d5822 #380f30 #805408
[ { "code": null, "e": 1190, "s": 1062, "text": "We are required to write a JavaScript function randomColor that returns a randomly generated\nhex color every time it is called." }, { "code": null, "e": 1242, "s": 1190, "text": "Therefore, let’s write the code for this function −" ...
Rename multiple files using Python
rename() method is used to rename a file or directory in Python3. The rename() method is a part of the os module. os.rename(src, dst) The first argument is src which is source address of file to be renamed and second argument dstwhich is the destination with the new name. Let's take any directory which has one image folder. Here we have this image folder. import os # Function to rename multiple files def main(): i = 0 path="C:/Users/TP/Desktop/sample/Travel/west bengal/bishnupur/" for filename in os.listdir(path): my_dest ="soul" + str(i) + ".jpg" my_source =path + filename my_dest =path + my_dest # rename() function will # rename all the files os.rename(my_source, my_dest) i += 1 # Driver Code if __name__ == '__main__': # Calling main() function main()
[ { "code": null, "e": 1176, "s": 1062, "text": "rename() method is used to rename a file or directory in Python3. The rename() method is a part of the os module." }, { "code": null, "e": 1197, "s": 1176, "text": "os.rename(src, dst)\n" }, { "code": null, "e": 1336, ...
CSS Margin Collapse
Sometimes two margins collapse into a single margin. Top and bottom margins of elements are sometimes collapsed into a single margin that is equal to the largest of the two margins. This does not happen on left and right margins! Only top and bottom margins! Look at the following example: Demonstration of margin collapse: In the example above, the <h1> element has a bottom margin of 50px and the <h2> element has a top margin set to 20px. Common sense would seem to suggest that the vertical margin between the <h1> and the <h2> would be a total of 70px (50px + 20px). But due to margin collapse, the actual margin ends up being 50px. Add a 20 pixels left margin to the <h1> element. <style> h1 { : 20px; } </style> <body> <h1>This is a heading</h1> <p>This is a paragraph</p> <p>This is a paragraph</p> </body> Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 53, "s": 0, "text": "Sometimes two margins collapse into a single margin." }, { "code": null, "e": 183, "s": 53, "text": "Top and bottom margins of elements are sometimes collapsed into a single \nmargin that is equal to the largest of the two margins." }, ...
Deploying your first Deep Learning Model: MNIST in production environment | by Anish Shrestha | Towards Data Science
How you can deploy your MNIST model in production environment MNIST Dataset is a hello world dataset for most of the ML Enthusiast likes us. At some point everyone who has started their journey in this field or willing to start will come across this dataset and get their hands on for sure. It is a good dataset for people who want to try learning techniques and pattern recognition methods on real-world data while spending minimal efforts on preprocessing and formatting. — Yann LeCun In this post i am going to write about how everyone who have completed MNIST can deploy there trained model as a beautiful web application in production environment using Django and Heroku. You should have basic knowledge on: Python programming languageDjango — Web Application FrameworkHeroku — Platform As a Service (Optional: You will learn how to use it in this post) Python programming language Django — Web Application Framework Heroku — Platform As a Service (Optional: You will learn how to use it in this post) and you should have a Keras based model file of MNIST; or you can get started on MNIST right now with this Jupyter Notebook file. First thing first, lets install Django using CMD or bash terminal; if you have not done it already. If you do not have prior experience in Django, There are a lot of free resources available online. Please consider looking at it. It’s an awesome framework for building Web Apps using Python. There is nothing to lose. pip install django This will install Django for you and you will have access to Django CLI for creating your project folder. django-admin startproject digitrecognizer I am going to name my project digitrecognizer you can name it as you like. Once you have done that you will be presented with a folder with some files inside it. let's create our new app main inside that folder using mange.py cli. python manage.py startapp main This will create a new app named main for you. Now we can write our main codes inside the views.py file. Let's write some code in the views.py file: ## Views.pyfrom django.shortcuts import renderfrom scipy.misc.pilutil import imread, imresizeimport numpy as npimport reimport sysimport ossys.path.append(os.path.abspath("./model"))from .utils import *from django.http import JsonResponsefrom django.views.decorators.csrf import csrf_exemptglobal model, graphmodel, graph = init()import base64OUTPUT = os.path.join(os.path.dirname(__file__), 'output.png')from PIL import Imagefrom io import BytesIOdef getI420FromBase64(codec): base64_data = re.sub('^data:image/.+;base64,', '', codec) byte_data = base64.b64decode(base64_data) image_data = BytesIO(byte_data) img = Image.open(image_data) img.save(OUTPUT)def convertImage(imgData): getI420FromBase64(imgData)@csrf_exemptdef predict(request):imgData = request.POST.get('img')convertImage(imgData) x = imread(OUTPUT, mode='L') x = np.invert(x) x = imresize(x, (28, 28)) x = x.reshape(1, 28, 28, 1) with graph.as_default(): out = model.predict(x) print(out) print(np.argmax(out, axis=1)) response = np.array_str(np.argmax(out, axis=1)) return JsonResponse({"output": response}) It looks like a lot, but it is not! 😂 trust me. At the very beginning of the code, we are importing every required library and module. Every import is self-explanatory and also I have commented on the important sections, consider looking at it. from django.shortcuts import renderfrom scipy.misc.pilutil import imread, imresizeimport numpy as npimport reimport sys## Apending MNIST model pathimport ossys.path.append(os.path.abspath("./model"))## custom utils file create for writing some helper funcfrom .utils import *from django.http import JsonResponsefrom django.views.decorators.csrf import csrf_exempt## Declaring global variableglobal model, graph## initializing MNIST model file (It comes from utils.py file)model, graph = init()import base64from PIL import Imagefrom io import BytesIO## Declaring output path to save our imageOUTPUT = os.path.join(os.path.dirname(__file__), 'output.png') After importing the required libraries, let's write some helper functions to process our MNIST model in a utils.py file. ## utils.pyfrom keras.models import model_from_jsonfrom scipy.misc.pilutil import imread, imresize, imshowimport tensorflow as tfimport osJSONpath = os.path.join(os.path.dirname(__file__), 'models', 'model.json')MODELpath = os.path.join(os.path.dirname(__file__), 'models', 'mnist.h5')def init(): json_file = open(JSONpath, 'r') loaded_model_json = json_file.read() json_file.close() loaded_model = model_from_json(loaded_model_json) loaded_model.load_weights(MODELpath) print("Loaded Model from disk") loaded_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) graph = tf.get_default_graph() return loaded_model, graph This file contains the init function which basically initializes our MNIST model file saved using Keras. It grabs or model file loads them and compiles them using adam optimizer to make them ready for prediction. here we are using categorical_crossentropy as our loss function, adam as our optimizer, and accuracy as our performance measuring metric. You can learn how to save models using Keras from here. Here we have got another helper function to help us convert our BASE64 Image file: which is grabbed from the client-side to a PNG file and save as whatever is in the OUTPUT variable; which is to save as an output.png file in the current directory. def getI420FromBase64(codec): base64_data = re.sub('^data:image/.+;base64,', '', codec) byte_data = base64.b64decode(base64_data) image_data = BytesIO(byte_data) img = Image.open(image_data) img.save(OUTPUT)def convertImage(imgData): getI420FromBase64(imgData) Now let's write our main API to: Grab a base64 image file submitted by the clientConvert it into png fileProcess it to be able to fit in our trained model filePredict the image using our previous helper function and get the performance metric in returnReturn it as a JSON response Grab a base64 image file submitted by the client Convert it into png file Process it to be able to fit in our trained model file Predict the image using our previous helper function and get the performance metric in return Return it as a JSON response @csrf_exemptdef predict(request):imgData = request.POST.get('img')convertImage(imgData) x = imread(OUTPUT, mode='L') x = np.invert(x) x = imresize(x, (28, 28)) x = x.reshape(1, 28, 28, 1) with graph.as_default(): out = model.predict(x) print(out) print(np.argmax(out, axis=1)) response = np.array_str(np.argmax(out, axis=1)) return JsonResponse({"output": response}) It uses csrf_exempt decorator because Django is very strict about security. By using it we are just disabling the CSRF validation. Now we have finished writing our application backend code to classify the label of a given image. Now, let's provide a route for our main function. Go to your project folder where settings.py and urls.py files are located. in the settings.py file underneath the INSTALLED_APPS array install the main app which we’ve created earlier to write our functions. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ## our main application 'main'] After that head back to the urls.py file and write a route that reaches our predict function. from django.contrib import adminfrom django.urls import path, includefrom main.views import predicturlpatterns = [ path('', include('main.urls')), path('api/predict/', predict)] Save everything and now our backend API is ready. Now it’s time to write our frontend code which enables us to interact with our backend API. We are using Django's template for writing our front end. let's create a templates folder inside our main folder and inside that let's create an index.html file. Inside the HTML file let's write some code to create a canvas and submit the image drawn by the user in that canvas. <canvas id="canvas" width="280" height="280" style="border:2px solid; float: left; border-radius: 5px; cursor: crosshair;" ></canvas><p id="result" class="text-center text-success"></p><a href="#" class="btn btn-success btn-block p-2" id="predictButton"> Predict</a><input type="button" class="btn btn-block btn-secondary p-2" id="clearButton" value="Clear" /> You can design your Frontend however you like and create this canvas inside it. After displaying a canvas, let's make it intractable with some JS(Jquery). (function(){ var canvas = document.querySelector( "#canvas" ); canvas.width = 280; canvas.height = 280; var context = canvas.getContext( "2d" ); var canvastop = canvas.offsetTopvar lastx; var lasty;context.strokeStyle = "#000000"; context.lineCap = 'round'; context.lineJoin = 'round'; context.lineWidth = 5;function dot(x,y) { context.beginPath(); context.fillStyle = "#000000"; context.arc(x,y,1,0,Math.PI*2,true); context.fill(); context.stroke(); context.closePath(); }function line(fromx,fromy, tox,toy) { context.beginPath(); context.moveTo(fromx, fromy); context.lineTo(tox, toy); context.stroke(); context.closePath(); }canvas.ontouchstart = function(event){ event.preventDefault();lastx = event.touches[0].clientX; lasty = event.touches[0].clientY - canvastop;dot(lastx,lasty); }canvas.ontouchmove = function(event){ event.preventDefault();var newx = event.touches[0].clientX; var newy = event.touches[0].clientY - canvastop;line(lastx,lasty, newx,newy);lastx = newx; lasty = newy; }var Mouse = { x: 0, y: 0 }; var lastMouse = { x: 0, y: 0 }; context.fillStyle="white"; context.fillRect(0,0,canvas.width,canvas.height); context.color = "black"; context.lineWidth = 10; context.lineJoin = context.lineCap = 'round';debug();canvas.addEventListener( "mousemove", function( e ) { lastMouse.x = Mouse.x; lastMouse.y = Mouse.y;Mouse.x = e.pageX - this.offsetLeft; Mouse.y = e.pageY - this.offsetTop;}, false );canvas.addEventListener( "mousedown", function( e ) { canvas.addEventListener( "mousemove", onPaint, false );}, false );canvas.addEventListener( "mouseup", function() { canvas.removeEventListener( "mousemove", onPaint, false );}, false );var onPaint = function() { context.lineWidth = context.lineWidth; context.lineJoin = "round"; context.lineCap = "round"; context.strokeStyle = context.color;context.beginPath(); context.moveTo( lastMouse.x, lastMouse.y ); context.lineTo( Mouse.x, Mouse.y ); context.closePath(); context.stroke(); };function debug() { /* CLEAR BUTTON */ var clearButton = $( "#clearButton" );clearButton.on( "click", function() {context.clearRect( 0, 0, 280, 280 ); context.fillStyle="white"; context.fillRect(0,0,canvas.width,canvas.height);});/* COLOR SELECTOR */$( "#colors" ).change(function() { var color = $( "#colors" ).val(); context.color = color; });/* LINE WIDTH */$( "#lineWidth" ).change(function() { context.lineWidth = $( this ).val(); }); }}()); This is basically our JS function to allow users to draw inside our canvas. It grabs the mouse + touch strokes of the user and draws lines inside canvas according to their drawings. After that let's write a code to submit those drawn lines to the backend as a base64 image file. <script type="text/javascript"> $("#predictButton").click(function() { var $SCRIPT_ROOT = "/api/predict/"; var canvasObj = document.getElementById("canvas"); var context = canvas.getContext( "2d" ); var img = canvasObj.toDataURL(); $.ajax({ type: "POST", url: $SCRIPT_ROOT, data: { img: img }, success: function(data) { $("#result").text("Predicted Output is: " + data.output);context.clearRect( 0, 0, 280, 280 ); context.fillStyle="white"; context.fillRect(0,0,canvas.width,canvas.height);} }); }); </script> Here we are using jquery to: Listen to our button click eventDefining our API route pathGrabbing our canvas elementGetting the context of the canvas as base64 imageSubmitting it to our backend using an ajax requestGetting a response from our backend and displaying it on our output section. Listen to our button click event Defining our API route path Grabbing our canvas element Getting the context of the canvas as base64 image Submitting it to our backend using an ajax request Getting a response from our backend and displaying it on our output section. Now for last, let's add a route to our fronted and write a function to serve our HTML file in our main app. # views.pydef index(request): return render(request, 'index.html', {})# urls.pyfrom django.urls import pathfrom .views import indexurlpatterns = [ path('', index, name="index")] That's it! we have successfully completed our backend + front-end development to recognize handwritten digits. Now let's deploy it. We are going to use Heroku to deploy our Django project because it’s awesome and FREE! You can learn more about heroku from it’s official documentation page. It is beautiful and everything is well documented. Install Heroku CLI on your laptop and let's get started. To make our Django project Heroku ready, let's write a Procfile inside our root directory. # Procfileweb: gunicorn digitrecognizer.wsgi --log-file - --log-level debug now let's create a new app repository in Heroku and get the remote URL of that app. after that git inits in our project directory and add git remote URL to Heroku url and push our project folder to Heroku with requirements.txt files included. That’s it for deployment 😊. We have successfully deployed our application in the cloud and it is live now. You can access the application using the URL provided by Heroku in your app dashboard. It is very important to deploy your projects in live environment to showcase your projects. It will be great for your project portfolio. I hope you have learned something, try building your own handwritten digit classifier and deploy it in a production environment. You can check my demo app from here. [1] Vitor Freitas, How to Deploy Django Applications on Heroku, 2016 Aug 9 [ONLINE] [2] yann lecunn, MNIST Database, 1998 [ONLINE]
[ { "code": null, "e": 234, "s": 172, "text": "How you can deploy your MNIST model in production environment" }, { "code": null, "e": 463, "s": 234, "text": "MNIST Dataset is a hello world dataset for most of the ML Enthusiast likes us. At some point everyone who has started their ...
Node.js – util.inherits() Method
The util.inherits() method basically inherits the methods from one construct to another. This prototype will be set to a new object to that from the superConstructor. By doing this, we can mainly add some validations to the top of Object.setPrototypeOf(constructor.prototype, superConstructor.prototype). util.inherits(constructor, superConstructor) The parameters are described below - constructor − This is a function type input that holds the prototype for constructor the user wants to be inherited. superConstructor − This is the function that will be used for adding and validating the input validations. Create a file "inherits.js" and copy the following code snippet. After creating the file, use the command "node inherits.js" to run this code. Live Demo // util.inherit() example // Importing the util module const util = require('util'); const EventEmitter = require('events'); // Defining the constructor below function Stream() { EventEmitter.call(this); } // Inheriting the stream constructor util.inherits(Stream, EventEmitter); // Creating the prototype for the constructor with some data Stream.prototype.write = function(data) { this.emit('data', data); }; // Creating a new stream constructor const stream = new Stream(); // Checking if stream is instanceOf EventEmitter console.log(stream instanceof EventEmitter); // true console.log(Stream.super_ === EventEmitter); // true // Printing the data stream.on('data', (data) => { console.log(`Data Received: "${data}"`); }); // Passing the data in stream stream.write('Its working... Created the constructor prototype!'); C:\home\node>> node inherits.js true true Dta Received: "It's working... Created the constructor prototype!" Let’s have a look at one more example Live Demo // util.inherits() example // Importing the util & events module const util = require('util'); const { inspect } = require('util'); const emitEvent = require('events'); // Definging the class to emit stream data class streamData extends emitEvent { write(stream_data) { // This will emit the data stream this.emit('stream_data', stream_data); } } // Creating a new instance of the stream const manageStream = new streamData('default'); console.log("1.", inspect(manageStream, false, 0, true)) console.log("2.", streamData) manageStream.on('stream_data', (stream_data) => { // Prints the write statement after streaming console.log("3.", `Data Stream Received: "${stream_data}"`); }); // Write on console manageStream.write('Inheriting the constructor & checking from superConstructor'); C:\home\node>> node inherits.js 1. streamData { _events: [Object: null prototype] {}, _eventsCount: 0, _maxListeners: undefined, [Symbol(kCapture)]: false } 2. [class streamData extends EventEmitter] 3. Data Stream Received: "Inheriting the constructor & checking from superConstructor"
[ { "code": null, "e": 1229, "s": 1062, "text": "The util.inherits() method basically inherits the methods from one construct to another. This prototype will be set to a new object to that from the superConstructor." }, { "code": null, "e": 1367, "s": 1229, "text": "By doing this, ...
\acute - Tex Command
\acute - Command to show accent symbol over the parameter passed. { \acute #1 } \acute command draws an accent symbol over the center of the passed parameter(expression). \acute e e ́ \acute E E ́ \acute eu e ́u \acute {eu} eu ́ \acute e e ́ \acute e \acute E E ́ \acute E \acute eu e ́u \acute eu \acute {eu} eu ́ \acute {eu} 14 Lectures 52 mins Ashraf Said 11 Lectures 1 hours Ashraf Said 9 Lectures 1 hours Emenwa Global, Ejike IfeanyiChukwu 29 Lectures 2.5 hours Mohammad Nauman 14 Lectures 1 hours Daniel Stern 15 Lectures 47 mins Nishant Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 8052, "s": 7986, "text": "\\acute - Command to show accent symbol over the parameter passed." }, { "code": null, "e": 8066, "s": 8052, "text": "{ \\acute #1 }" }, { "code": null, "e": 8157, "s": 8066, "text": "\\acute command draws an acce...
Building Web Applications with Streamlit for NLP Projects | by Ram Vegiraju | Towards Data Science
One of the most common tasks Data Scientists struggle with is presenting their model/project in a format for users to interact with. The model is not of much use to any external users if it is not presentable in some type of application. This introduces the vast-field of web/app development which then leads to more languages and tools such as HTML, CSS, ReactJS, Dash, Flask, and more that can help you create a front-end interface for users to interact with and get results out of your model. This vast field can be intimidating at first and alien to the traditional Data Science skillset. Streamlit is a simple Python API that provides a way to lessen this learning curve and eliminates the need for Data Scientist’s to know many of these tools. The general full-stack arsenal should be the go-to for large scale projects, but if you ever need a quick front-end for your data science projects, Streamlit more than serves the purpose. For this article, I wanted to demonstrate the basics of Streamlit while building a web application that allows users to work with models solving common NLP tasks such as Sentiment Analysis, Named Entity Recognition, and Text Summarization. NOTE: While we could build custom models for each of these tasks, I went with pre-trained models in Python libraries as this article is more centered around building a web application to display your ML/NLP projects through Streamlit. Web App SetupDataSentiment AnalysisNamed Entity Recognition (NER)Text SummarizationEntire Code & Conclusion Web App Setup Data Sentiment Analysis Named Entity Recognition (NER) Text Summarization Entire Code & Conclusion Before building any of our models, we need a template for how our application is going to look. Let’s first import streamlit (To install use pip3 install streamlit for Python3). To explain what our application is, let’s add a title and smaller header asking which NLP service the user wants to work with from our three options. Streamlit.title(), Streamlit.header(), and Streamlit.subheader() are the different heading levels in descending order. For pure non-heading text data you can use Streamlit.text(). Now that we have the main question for the application, we can build a drop-down menu for the user to pick from the three tasks our models can complete. This can be done using the Streamlit.selectbox() call. The service chosen out of the three choices is stored as a string in the option variable. The next piece of information that needs to be entered is the text that the user wants to enter for our models to process/perform the chosen task on. For this we can use the Streamlit.text_input() call, which is similar to the textarea tag in HTML. The text input is then stored in the text variable. Now that we have the option and text variables containing all the information we need to work with, we need to make an area to display the results. With our template now set-up we have something that looks like what’s below. With just about 10 lines of Python code a very simple yet effective template has been created. Now that we have our front-end we can work with processing/feeding this information to our models and returning the results to the user. For the NLP tasks we will be using the following piece of text data from an article titled “Microsoft Launches Intelligent Cloud Hub To Upskill Students In AI & Cloud Technologies”. The article/text was found through the medium article linked. We will use the following text block as the input text for all three of the NLP tasks. In an attempt to build an AI-ready workforce, Microsoft announced Intelligent Cloud Hub which has been launched to empower the next generation of students with AI-ready skills. Envisioned as a three-year collaborative program, Intelligent Cloud Hub will support around 100 institutions with AI infrastructure, course content and curriculum, developer support, development tools and give students access to cloud and AI services. As part of the program, the Redmond giant which wants to expand its reach and is planning to build a strong developer ecosystem in India with the program will set up the core AI infrastructure and IoT Hub for the selected campuses. The company will provide AI development tools and Azure AI services such as Microsoft Cognitive Services, Bot Services and Azure Machine Learning.According to Manish Prakash, Country General Manager-PS, Health and Education, Microsoft India, said, "With AI being the defining technology of our time, it is transforming lives and industry and the jobs of tomorrow will require a different skillset. This will require more collaborations and training and working with AI. That’s why it has become more critical than ever for educational institutions to integrate new cloud and AI technologies. The program is an attempt to ramp up the institutional set-up and build capabilities among the educators to educate the workforce of tomorrow." The program aims to build up the cognitive skills and in-depth understanding of developing intelligent cloud connected solutions for applications across industry. Earlier in April this year, the company announced Microsoft Professional Program In AI as a learning track open to the public. The program was developed to provide job ready skills to programmers who wanted to hone their skills in AI and data science with a series of online courses which featured hands-on labs and expert instructors as well. This program also included developer-focused AI school that provided a bunch of assets to help build AI skills. For Sentiment Analysis, we’ll be working with the textblob library to generate polarity and subjectivity of text entered. (Use pip3 install textblob for Python3) For tokenizing the data we use the NLTK library to split the text into sentences so we can break larger text into smaller portions for visual analysis. Using the textblob library we get a sentiment per sentence to create a visual plot of the sentiment throughout the text. Note: Sentiment is represented between -1 to 1 for the library with 1 being most positive and -1 being most negative. Using another neat Streamlit feature in Streamlit.line_chart(), we can plot the sentiment of each sentence in a line graph for user to visually analyze the text data shown in the second section. If we want an overall sentiment off the text, we can use the TextBlob API call on the entire data string. Using the st.write() call we can display the sentiment returned from textblob. The two features returned are Polarity and Subjectivity. Polarity is between [-1,1] and Subjectivity is between [0,1] with 0.0 as objective and 1.0 as subjective. For NER we’ll be using another popular NLP library in Spacy. Spacy has a nice feature where it provides the type of entities along with the entities it recognizes. Examples of this includes: PERSON, ORG, DATE, MONEY, and more. To extract entities and their labels we can iterate through the entire list of entities found and join them into a dictionary. For our user to get an easy visual representation of entities of each type, we can make a helper function that lists all entities of each type. Using this function we can extract entities for each type and write the results out for the user to cleanly see. For text summarization, we’ll be using the gensim library which has a simple summarize call. Using the summarize call, we easily generate a summary of the inputted text. Note: Need to have more than one sentence for the summarize call to work with the gensim. github.com Streamlit allows you to seamlessly integrate popular Data Science/ML libraries to display your projects on simple yet concise web application/dashboards. While the more common full-stack skillset will serve better for projects at scale, the short time and simplicity needed to use Streamlit greatly aids Data Scientists & ML Engineers trying to showcase their projects. I hope that this article has been useful for anyone trying to work with Streamlit with their ML/NLP projects. Feel free to leave any feedback in the comments or connect with me on Linkedln if interested in chatting about ML & Data Science. Thank you for reading!
[ { "code": null, "e": 764, "s": 171, "text": "One of the most common tasks Data Scientists struggle with is presenting their model/project in a format for users to interact with. The model is not of much use to any external users if it is not presentable in some type of application. This introduces t...
The CSS3 matrix3d() Function
The matrix3d() function in CSS is used to define a 4x4 homogeneous 3D transformation matrix. Live Demo <!DOCTYPE html> <html> <head> <style> .demo_img { transform: matrix3d(1,1,0,0,0,1,0,0,0,0,1,0,1,100,0,1); } </style> </head> <body> <h1>Learn</h1> <p>Learn Apache Spark</p> <img class="demo_img" src= "https://www.tutorialspoint.com/machine_learning/images/machine-learning-mini-logo.jpg" alt="Apache Spark"> </body> </html> Let us see another example − Live Demo <!DOCTYPE html> <html> <head> <style> .demo_img { transform: matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,50,-100,0,1.1); </style> </head> <body> <h1>Learn</h1> <p>Learn Apache Spark</p> <img class="demo_img" src= "https://www.tutorialspoint.com/machine_learning/images/machine-learning-mini-logo.jpg" alt="Apache Spark"> </body> </html>
[ { "code": null, "e": 1155, "s": 1062, "text": "The matrix3d() function in CSS is used to define a 4x4 homogeneous 3D transformation matrix." }, { "code": null, "e": 1166, "s": 1155, "text": " Live Demo" }, { "code": null, "e": 1493, "s": 1166, "text": "<!DOCTY...
Synchronization and Pooling of processes in C#
Using Synchronization, you can synchronize access to resources in multithreaded applications. A mutex can be used to synchronize threads across processes. Use it to prevent the simultaneous execution of a block of code by more than one thread at a time. C# lock statement is used to ensure that a block of code runs without interruption by other threads. A Mutual-exclusion lock is obtained for a given object for the duration of the code block. Thread pool in C# is a collection of threads. It is used to perform tasks in the background. When a thread completes a task, it is sent to the queue wherein all the waiting threads are present. This is done so that it can be reused. Let us see how to create a thread pool. Firstly, use the following namespace − using System.Threading; Now, call the threadpool class, using the threadpool object. Call the method QueueUserWorkItem. ThreadPool.QueueUserWorkItem(new WaitCallback(Run));
[ { "code": null, "e": 1156, "s": 1062, "text": "Using Synchronization, you can synchronize access to resources in multithreaded applications." }, { "code": null, "e": 1316, "s": 1156, "text": "A mutex can be used to synchronize threads across processes. Use it to prevent the simul...
How to convert List<Integer> to int[] in Java?
You can simply iterate through list and fill the array as shown below − import java.util.ArrayList; import java.util.List; public class Tester { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(new Integer(1)); list.add(new Integer(2)); list.add(new Integer(3)); list.add(new Integer(4)); int[] array = new int[list.size()]; for(int i=0;i<array.length;i++) { array[i] = list.get(i); System.out.println(array[i]); } } } 1 2 3 4
[ { "code": null, "e": 1134, "s": 1062, "text": "You can simply iterate through list and fill the array as shown below −" }, { "code": null, "e": 1594, "s": 1134, "text": "import java.util.ArrayList;\nimport java.util.List;\npublic class Tester {\n public static void main(String[...
How to make the Parula colormap in Matplotlib?
To make the Parula colormap in matplotlib, we can take the following steps Set the figure size and adjust the padding between and around the subplots. Create colormap data using numpy. Create a 'LinearSegmentedColormap' from a list of colors. Viscum is a little tool for analyzing colormaps and creating new colormaps. Use imshow() method to display data as an image, i.e., on a 2D regular raster. To display the figure, use show() method. from matplotlib.colors import LinearSegmentedColormap import matplotlib.pyplot as plt import numpy as np from viscm import viscm plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True cm_data = np.random.rand(4, 4) parula_map = LinearSegmentedColormap.from_list('parula', cm_data) viscm(parula_map) plt.imshow(np.linspace(0, 100, 256)[None, :], aspect='auto', cmap=parula_map) plt.show()
[ { "code": null, "e": 1137, "s": 1062, "text": "To make the Parula colormap in matplotlib, we can take the following steps" }, { "code": null, "e": 1213, "s": 1137, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, ...
Kruskal-Wallis test in R Programming
16 May, 2022 The Kruskal–Wallis test in R Programming Language is a rank-based test that is similar to the Mann–Whitney U test but can be applied to one-way data with more than two groups. It is a non-parametric alternative to the one-way ANOVA test, which extends the two-samples Wilcoxon test. A group of data samples is independent if they come from unrelated populations and the samples do not affect each other. Using the Kruskal-Wallis Test, it can be decided whether the population distributions are similar without assuming them to follow the normal distribution. It is very much easy to perform Kruskal-Wallis test in the R language. Note: The outcome of the Kruskal–Wallis test tells that if there are differences among the groups, but doesn’t tell which groups are different from other groups. Examples: Let one wants to find out how socioeconomic status influences attitude towards sales tax hikes. Here the independent variable is “socioeconomic status” with three levels: working-class, middle-class, and wealthy. The dependent variable is measured on a 5-point Likert scale from strongly agree to strongly disagree.If one wants to find out how test anxiety influences actual test scores. The independent variable “test anxiety” has three levels: no anxiety, low-medium anxiety, and high anxiety. The dependent variable is the exam score and it is rated from 0 to 100%. Let one wants to find out how socioeconomic status influences attitude towards sales tax hikes. Here the independent variable is “socioeconomic status” with three levels: working-class, middle-class, and wealthy. The dependent variable is measured on a 5-point Likert scale from strongly agree to strongly disagree. If one wants to find out how test anxiety influences actual test scores. The independent variable “test anxiety” has three levels: no anxiety, low-medium anxiety, and high anxiety. The dependent variable is the exam score and it is rated from 0 to 100%. The variables should have: One independent variable with two or more levels. The test is more commonly used when there are three or more levels. For two levels instead of the Kruskal-Wallis test consider using the Mann Whitney U Test. The dependent variable should be the Ordinal scale, Ratio Scale, or Interval scale. The observations should be independent. In other words, there should be no correlation between the members in every group or within groups. All groups should have identical shape distributions. R provides a method kruskal.test() which is available in the stats package to perform a Kruskal-Wallis rank-sum test. Syntax: kruskal.test(x, g, formula, data, subset, na.action, ...) Parameters: x: a numeric vector of data values, or a list of numeric data vectors. g: a vector or factor object giving the group for the corresponding elements of x formula: a formula of the form response ~ group where response gives the data values and group a vector or factor of the corresponding groups. data: an optional matrix or data frame containing the variables in the formula . subset: an optional vector specifying a subset of observations to be used. na.action: a function which indicates what should happen when the data contain NA ...: further arguments to be passed to or from methods. Example: Let’s use the built-in R data set named PlantGrowth. It contains the weight of plants obtained under control and two different treatment conditions. R # Preparing the data set# to perform Kruskal-Wallis Test # Taking the PlantGrowth data setmyData = PlantGrowthprint(myData) # Show the group levelsprint(levels(myData$group)) Output: weight group 1 4.17 ctrl 2 5.58 ctrl 3 5.18 ctrl 4 6.11 ctrl 5 4.50 ctrl 6 4.61 ctrl 7 5.17 ctrl 8 4.53 ctrl 9 5.33 ctrl 10 5.14 ctrl 11 4.81 trt1 12 4.17 trt1 13 4.41 trt1 14 3.59 trt1 15 5.87 trt1 16 3.83 trt1 17 6.03 trt1 18 4.89 trt1 19 4.32 trt1 20 4.69 trt1 21 6.31 trt2 22 5.12 trt2 23 5.54 trt2 24 5.50 trt2 25 5.37 trt2 26 5.29 trt2 27 4.92 trt2 28 6.15 trt2 29 5.80 trt2 30 5.26 trt2 [1] "ctrl" "trt1" "trt2" Here the column “group” is called factor and the different categories (“ctr”, “trt1”, “trt2”) are named factor levels. The levels are ordered alphabetically. The problem statement is we want to know if there is any significant difference between the average weights of plants in the 3 experimental conditions. And the test can be performed using the function kruskal.test() as given below. R # R program to illustrate# Kruskal-Wallis Test # Taking the PlantGrowth data setmyData = PlantGrowth # Performing Kruskal-Wallis testresult = kruskal.test(weight ~ group, data = myData)print(result) Output: Kruskal-Wallis rank sum test data: weight by group Kruskal-Wallis chi-squared = 7.9882, df = 2, p-value = 0.01842 Explanation: As the p-value is less than the significance level 0.05, it can be concluded that there are significant differences between the treatment groups. kumar_satyam sweetyty R Data-science R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 May, 2022" }, { "code": null, "e": 658, "s": 28, "text": "The Kruskal–Wallis test in R Programming Language is a rank-based test that is similar to the Mann–Whitney U test but can be applied to one-way data with more than two groups....
Lambda Expression in Scala
28 Feb, 2019 Lambda Expression refers to an expression that uses an anonymous function instead of variable or value. Lambda expressions are more convenient when we have a simple function to be used in one place. These expressions are faster and more expressive than defining a whole function. We can make our lambda expressions reusable for any kind of transformations. It can iterate over a collection of objects and perform some kind of transformation to them.Syntax: val lambda_exp = (variable:Type) => Transformation_Expression Example: // lambda expression to find double of x val ex = (x:Int) => x + x We can pass values to a lambda just like a normal function call.Example :// Scala program to show// working of lambda expression // Creating objectobject GfG{ // Main methoddef main(args:Array[String]){ // lambda expression val ex1 = (x:Int) => x + 2 // with multiple parameters val ex2 = (x:Int, y:Int) => x * y println(ex1(7)) println(ex2(2, 3))}}Output:9 6 // Scala program to show// working of lambda expression // Creating objectobject GfG{ // Main methoddef main(args:Array[String]){ // lambda expression val ex1 = (x:Int) => x + 2 // with multiple parameters val ex2 = (x:Int, y:Int) => x * y println(ex1(7)) println(ex2(2, 3))}} Output: 9 6 To apply transformation to any collection, we generally use map() function. It is a higher-order function where we can pass our lambda as a parameter in order to transform every element of the collection according to the definition of our lambda expression.Example :// Scala program to apply// transformation on collection // Creating objectobject GfG{ // Main methoddef main(args:Array[String]){ // list of numbers val l = List(1, 1, 2, 3, 5, 8) // squaring each element of the list val res = l.map( (x:Int) => x * x ) /* ORval res = l.map( x=> x * x )*/ println(res)}}Output:List(1, 1, 4, 9, 25, 64)We can see that the defined anonymous function to perform the square operation is not reusable. // Scala program to apply// transformation on collection // Creating objectobject GfG{ // Main methoddef main(args:Array[String]){ // list of numbers val l = List(1, 1, 2, 3, 5, 8) // squaring each element of the list val res = l.map( (x:Int) => x * x ) /* ORval res = l.map( x=> x * x )*/ println(res)}} Output: List(1, 1, 4, 9, 25, 64) We can see that the defined anonymous function to perform the square operation is not reusable. We are passing it as an argument. However, we can make it reusable and may use it with different collections.Example :// Scala program to apply// transformation on collection // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // list of numbers val l1 = List(1, 1, 2, 3, 5, 8) val l2 = List(13, 21, 34) // reusable lambda val func = (x:Int) => x * x // squaring each element of the lists val res1 = l1.map( func ) val res2 = l2.map( func ) println(res1) println(res2) }}Output:List(1, 1, 4, 9, 25, 64) List(169, 441, 1156) // Scala program to apply// transformation on collection // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // list of numbers val l1 = List(1, 1, 2, 3, 5, 8) val l2 = List(13, 21, 34) // reusable lambda val func = (x:Int) => x * x // squaring each element of the lists val res1 = l1.map( func ) val res2 = l2.map( func ) println(res1) println(res2) }} Output: List(1, 1, 4, 9, 25, 64) List(169, 441, 1156) A lambda can also be used as a parameter to a function.Example :// Scala program to pass lambda// as parameter to a function // Creating objectobject GfG{ // transform function with integer x and // function f as parameter // f accepts Int and returns Double def transform( x:Int, f:Int => Double) = f(x) // Main method def main(args:Array[String]) { // lambda is passed to f:Int => Double val res = transform(2, r => 3.14 * r * r) println(res)}}Output:12.56In above example, transform function accepts integer x and function f, applies the transformation to x defined by f. Lambda passed as the parameter in function call returns Double type. Therefore, parameter f must obey the lambda definition. // Scala program to pass lambda// as parameter to a function // Creating objectobject GfG{ // transform function with integer x and // function f as parameter // f accepts Int and returns Double def transform( x:Int, f:Int => Double) = f(x) // Main method def main(args:Array[String]) { // lambda is passed to f:Int => Double val res = transform(2, r => 3.14 * r * r) println(res)}} Output: 12.56 In above example, transform function accepts integer x and function f, applies the transformation to x defined by f. Lambda passed as the parameter in function call returns Double type. Therefore, parameter f must obey the lambda definition. We can perform the same task on any collection as well. In case of collections, the only change we need to make in transform function is using map function to apply transformation defined by f to every element of the list l.Example :// Scala program to pass lambda// as parameter to a function // Creating objectobject GfG{ // transform function with integer list l and // function f as parameter // f accepts Int and returns Double def transform( l:List[Int], f:Int => Double) = l.map(f) // Main method def main(args:Array[String]) { // lambda is passed to f:Int => Double val res = transform(List(1, 2, 3), r => 3.14 * r * r) println(res) }}Output:List(3.14, 12.56, 28.259999999999998) // Scala program to pass lambda// as parameter to a function // Creating objectobject GfG{ // transform function with integer list l and // function f as parameter // f accepts Int and returns Double def transform( l:List[Int], f:Int => Double) = l.map(f) // Main method def main(args:Array[String]) { // lambda is passed to f:Int => Double val res = transform(List(1, 2, 3), r => 3.14 * r * r) println(res) }} Output: List(3.14, 12.56, 28.259999999999998) Picked Scala Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. For Loop in Scala Scala | map() method Scala | flatMap Method String concatenation in Scala Scala | reduce() Function Scala List filter() method with example Type Casting in Scala Scala Tutorial – Learn Scala with Step By Step Guide Scala String substring() method with example How to Install Scala with VSCode?
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Feb, 2019" }, { "code": null, "e": 485, "s": 28, "text": "Lambda Expression refers to an expression that uses an anonymous function instead of variable or value. Lambda expressions are more convenient when we have a simple function t...
How to remove all the elements of a dictionary in Python?
To remove all elements from a dictionary, the easiest way is to reassign the dictionary to an empty dictionary. my_dict = {'name': 'foo', 'age': 28} my_dict = {} print(my_dict) This will give the output − {} You can also use the del function to delete a specific key or loop through all keys and delete them. my_dict = {'name': 'foo', 'age': 28} keys = list(my_dict.keys()) for key in keys: del my_dict[key] print(my_dict) This will give the output − {}
[ { "code": null, "e": 1175, "s": 1062, "text": "To remove all elements from a dictionary, the easiest way is to reassign the dictionary to an empty dictionary. " }, { "code": null, "e": 1240, "s": 1175, "text": "my_dict = {'name': 'foo', 'age': 28}\nmy_dict = {}\nprint(my_dict)" ...
Break statement in java
The break statement in Java programming language has the following two usages − When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. It can be used to terminate a case in the switch statement (covered in the next chapter). It can be used to terminate a case in the switch statement (covered in the next chapter). The syntax of a break is a single statement inside any loop − break; public class Test { public static void main(String args[]) { int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ) { if( x == 30 ) { break; } System.out.print( x ); System.out.print("\n"); } } } This will produce the following result − 10 20 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": 2457, "s": 2377, "text": "The break statement in Java programming language has the following two usages −" }, { "code": null, "e": 2621, "s": 2457, "text": "When the break statement is encountered inside a loop, the loop is immediately terminated and the prog...
JavaScript | Object.getOwnPropertyDescriptor() Method - GeeksforGeeks
17 Sep, 2021 The Object.getOwnPropertyDescriptor() method in JavaScript is standard built-in objects that returns a property descriptor for an own property of a given object.Syntax: Object.getOwnPropertyDescriptor( obj, prop ) Parameters: This method accept two parameters as mentioned above and described below: obj: This parameter holds the object in which the property are to be look. prop: This parameter holds the name or Symbol of the property whose description is to be retrieved. Return value: This method returns a property descriptor of the given property or undefined depending upon the existence of the object.Below examples illustrate the Object.getOwnPropertyDescriptor() method in JavaScript:Example 1: javascript const geeks1 = { prop1: "GeeksforGeeks" } const geeks2 = { prop2: "Best Platform" } const geeks3 = { prop3: "And Computer science portal" }const descriptor1 = Object.getOwnPropertyDescriptor(geeks1, 'prop1'); const descriptor2 = Object.getOwnPropertyDescriptor(geeks2, 'prop2'); const descriptor3 = Object.getOwnPropertyDescriptor(geeks3, 'prop3'); console.log(descriptor1.enumerable); console.log(descriptor2.enumerable); console.log(descriptor1.value); console.log(descriptor2.value); console.log(descriptor3.enumerable); console.log(descriptor3.value); Output: true true "GeeksforGeeks" "Best Platform" true "And Computer science portal" Example 2: javascript var geek, result;geek = { get foo() { return 17; } };d = Object.getOwnPropertyDescriptor(geek, 'foo');console.log(d) geek = { bar: 42 };d = Object.getOwnPropertyDescriptor(geek, 'bar');console.log(d) geek = { [Symbol.for('baz')]: 73 }d = Object.getOwnPropertyDescriptor(geek, Symbol.for('baz'));console.log(d) geek = {};Object.defineProperty(geek, 'qux', { value: 8675309, writable: false, enumerable: false});d = Object.getOwnPropertyDescriptor(geek, 'qux');console.log(d) Output: Object { get: get foo() { return 17; }, set: undefined, enumerable: true, configurable: true } Object { value: 42, writable: true, enumerable: true, configurable: true } Object { value: 73, writable: true, enumerable: true, configurable: true } Object { value: 8675309, writable: false, enumerable: false, configurable: false } Supported Browsers: The browsers supported by Object.getOwnPropertyDescriptor() method are listed below: Google Chrome 5.0 and above Internet Explorer 9.0 and above Mozilla 4.0 and above Opera 12 and above Safari 5.0 and above ysachin2314 javascript-functions JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26511, "s": 26483, "text": "\n17 Sep, 2021" }, { "code": null, "e": 26682, "s": 26511, "text": "The Object.getOwnPropertyDescriptor() method in JavaScript is standard built-in objects that returns a property descriptor for an own property of a given object.Sy...
screen command in Linux with Examples - GeeksforGeeks
06 May, 2022 screen command in Linux provides the ability to launch and use multiple shell sessions from a single ssh session. When a process is started with ‘screen’, the process can be detached from session & then can reattach the session at a later time. When the session is detached, the process that was originally started from the screen is still running and managed by the screen itself. The process can then re-attach the session at a later time, and the terminals are still there, the way it was left. Syntax: screen [-opts] [cmd [args]] Options: -a: It force all capabilities into each window’s termcap. -A -[r|R]: It adapt all windows to the new display width & height. -c file: It read configuration file instead of ‘.screenrc’. -d (-r): It detach the elsewhere running screen (and reattach here). -dmS name: It start as daemon: Screen session in detached mode. -D (-r): It detach and logout remote (and reattach here). -D -RR: It do whatever is needed to get a screen session. -e xy: It change the command characters. -f: It make the flow control on, -fn = off, -fa = auto. -h lines: It set the size of the scrollback history buffer. -i: It interrupt output sooner when flow control is on. -l: It make the login mode on (update /var/run/utmp), -ln = off. -ls [match]: It display all the attached screens. -L: It turn on output logging. -m: It ignore $STY variable, do create a new screen session. -O: It choose optimal output rather than exact vt100 emulation. -p window: It preselect the named window if it exists. -q: It quiet startup. Exits with non-zero return code if unsuccessful. -Q: It commands will send the response to the stdout of the querying process. -r [session]: It reattach to a detached screen process. -R: It reattach if possible, otherwise start a new session. -S sockname: It name this session .sockname instead of ... -t title: It set title. (window’s name). -T term: It use term as $TERM for windows, rather than “screen”. -U: It tell screen to use UTF-8 encoding. -v: It print “Screen version 4.06.02 (GNU) 23-Oct-17”. -x: It attach to a not detached screen. (Multi display mode). -X: It execute as a screen command in the specified session. Shortcut keys Options: Ctrl-a + c: It create a new windows. Ctrl-a + w: It display the list of all the windows currently opened. Ctrl-a + A: It rename the current windows. The name will appear when you will list the list of windows opened with Ctrl-a + w. Ctrl-a + n: It go to the next windows. Ctrl-a + p: It go to the previous windows. Ctrl-a + Ctrl-a: It back to the last windows used. Ctrl-a + k: It close the current windows (kill). Ctrl-a + S: It split the current windows horizontally. To switch between the windows, do Ctrl-a + Tab. Ctrl-a + |: It split the current windows vertically. Ctrl-a + X: Close active Split window Ctrl-a + Q: Close all Split windows Ctrl-a + d: It detach a screen session without stopping it. Ctrl-a + r: It reattach a detached screen session. Ctrl-a + [: It start the copy mode. Ctrl-a + ]: It paste the copied text. Examples: Installation of screen command: To install the screen command simply go to the terminal and type the following command: sudo apt install screen screen: It will start a new window within the screen. screen -S: It will start a new window within the screen and also gives a name to the window. It creates a session which is identified by that name. The name can be used to reattach screen at a later stage. screen -S file -ls: It is used to display the currently opened screens including those running in the background. It will list all the attached as well as detached screen sessions. screen -ls -d: It is used to detach a screen session so that it can be reattached in future. It can also be done with the help of shortcut key Ctrl-a + d screen -d 1643 Here 1643 is the screen id we want to detach. -r: It is used to reattach a screen session which was detached in past. screen -r 1643 Note: To check for the manual page of screen command, use the following command: man screen To check the help page of screen command, use the following command: screen --help surinderdawra388 SSShingne linux-command Linux-misc-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples mv command in Linux with examples chown command in Linux with Examples Docker - COPY Instruction nohup Command in Linux with Examples SED command in Linux | Set 2 Named Pipe or FIFO with example C program Thread functions in C/C++ uniq Command in LINUX with examples Array Basics in Shell Scripting | Set 1
[ { "code": null, "e": 25761, "s": 25733, "text": "\n06 May, 2022" }, { "code": null, "e": 26267, "s": 25761, "text": "screen command in Linux provides the ability to launch and use multiple shell sessions from a single ssh session. When a process is started with ‘screen’, the proc...
Python For Sport Scientists: Descriptive Statistics | by John Cothran | Towards Data Science
Python has been gaining a tremendous amount of popularity over the past few years, and is the language of choice for many data scientists across the world. It is no accident that it is also gaining popularity for sport scientists, who have to work with a lot of data on a day-to-day basis. While this article may benefit sport scientists who are beginners in Python, it is not an introduction to the language itself. Rather it is an introduction to how to reason about solving problems and analyzing data in a more functional way. Furthermore, this article will use basic descriptive statistics to illustrate how to build composable functional Python code to solve problems. In the first section, I’ll introduce two basic calculations of central tendency: the mean and the median. The second part applies the same principles to calculating standard deviation and variance. The last part introduces bivariate analysis by calculating the relationship between two variables. Sport scientists are consistently working with datasets about athletes, and it is useful to be able to call mean on a list of data points to gain a general insight about it. In the case of datasets with outliers (we are working with athletes after all), we may need to use median to find out the 50th percentile. While there are statistical libraries for Python to import these functions, I believe it can be extremely helpful to work through them to build the foundation to solve more complex problems later. When we get to composable functions like Sum of Squares, or Mean Squared Error, this will make more sense. Let’s begin by creating a .py file and define the function mean. The following is a pure function that returns the mean: # Python 3def mean (x): return sum(x) / len(x) Notice that sum() and len() are functions native to Python that return the sum and the length of a python data structure. The mean function here is a simple pure function, meaning that it has no side-effects (it always returns the same result given the same input.) Calculating the median is slightly more complex than the mean, but simple enough to think through. Finding the median of a list of numbers hinges on finding half the length of a sorted list: half = lambda arr: len(arr) / 2. However, this function has two problems assuming we are going to use it to find the index (which starts at 0.) The first problem is that it returns a float, and we need an integer to find the value at an index. The second problem is that we want it to return the first of the middle two indexes if the length of numbers is even. We can solve this by using the int() function. Let’s add this to our file: The half() function now returns the middle index (or in the case of an even list, the first of two middle indexes): evenList = [11, 12, 13, 14]oddList = [21, 22, 23]half(evenList)# 1half(oddList)# 1 The next step in defining the median is to return the value at that index. If the length is even, we need to return the average of the arr[half(arr)] and arr[half(arr) + 1] values to get the median. So let’s finally write the median function and add it to our file: def median (arr): sortedList = sorted(arr) index = half(sortedList) if isEven(len(sortedList)): return mean([ sortedList[index], sortedList[index + 1] ]) else: return sortedList[index] Voila! Calling median(evenList) from above will return 12.5, and calling median(oddList) will return 22. This is pretty cool because we got to use that mean() function that we just defined! This is the most fun part about programming with functions — they serve as simple building blocks that can be build to tackle any problem. Furthermore, notice we had to use the native sorted() function to return a sorted copy of the dataset before operating on it, which is vital to getting the correct median value. Let’s use these two functions in a somewhat practical example. I’ll use a basic dataset that contains some GPS data from a training session: data = [ {"name": "John", "distance": 5602, "high-speed-running": 504}, {"name": "Mike", "distance": 5242, "high-speed-running": 622}, {"name": "Chad", "distance": 4825, "high-speed-running": 453}, {"name": "Phil", "distance": 611, "high-speed-running": 500}, {"name": "Tyler", "distance": 5436, "high-speed-running": 409}] This is a list of dictionaries, so we can’t just call mean(data[“distance”]) as it stands. Let’s import the handypandas library at the top of the file to transform the dataset into a Pandas DataFrame, so we can simply call mean on elements of the dataset: Now we can call mean(df['distance']) to return 4343.2. Calling median(df[‘distance’]) returns 5242. Something to think about: in this specific dataset, why might we want to use the median function rather than the mean in our analysis? Or vice-versa. Standard deviation and variance are closely related to each other. For example, variance is defined as the square of the standard deviation (or standard deviation is the square root of the variance). With composable functions, this is almost too easy! We can start with variance, since all we will have to do is to square it to get the standard deviation. The mean function we defined in Part 1 will also come in handy, as well as Python’s native len function. Looking at the equation for sample variance and considering that we will be squaring it to get the standard deviation, it seems like a good idea to go ahead and define a function that squares a value: def square(x): return x * x The next bit is slightly trickier, but we can evaluate the numerator with a function called, say sumOfSquaredDifferences: def sumOfSquaredDifferences (arr): xBar = mean(arr) differences = map(lambda x: x - xBar, arr) squaredDifferences = map(square, differences) return sum(squaredDifferences)sprintEfforts = [88, 56, 51, 34, 50, 22, 61, 79, 90, 49]sumOfSquaredDifferences(sprintEfforts)# 4444 This function essentially evaluates the differences of each of the values and the mean (using the higher-order map function), then squares the differences and finds the sum of the squared differences. Simple enough! Now finding the sample variance is easy: def variance (arr): n = len(arr) return sumOfSquaredDifferences(arr) / (n-1)variance(sprintEfforts)# 493.7 The variance is great an all, but we would like a measure that is a little more familiar to us. Luckily, calculating Standard Deviation from Variance is a breeze, since it is simply the square root of Variance: def sqrt (x): return x**(1/2)def stDev (arr): return sqrt(variance(arr))stDev(sprintEfforts)# 22.2 Other than Python’s wacky syntax for the power operator (**), this is super easy. Let’s apply it to the dataset of GPS scores from Part 1: stDev(df['high-speed-running'])# 79.62 The updated file from Part 1 should now look like this: Combining small, pure functions that have a single purpose is proving to be useful in bringing basic statistical concepts to life. These statistical calculations are perfect for practicing good programming principles. We’ve used map quite a bit, along with lambda functions. These are foundational for working with lists of data. It is a good idea to try to master and understand how to use higher-order-functions like map, filter, and reduce in any language in order to most effectively build composable, functional code. So far we have been defining functions of univariate analysis, which have been useful for demonstrating working with single arrays of data. Now we can apply the same logic to undertake bivariate analysis by exploring correlation. The number one rule of working with a dataset is to plot the data to see what we’re working with. For simplicity’s sake, let’s use import seaborn as sns for creating the plot: The dataset is based off of the fictitious dataset used in Parts 1 and 2. However, if those were representative of one training session, this dataset can be weekly totals of the same metrics. This code will produce the following plot: Cool! Right off the bat we can tell that there is a strong positive linear relationship between ‘distance’ and ‘high-speed-running.’ The next step is to put a number to it by finding the Pearson Correlation Coefficient, which can be represented by the following formula: Let’s break this up into its parts. We’re going to need count for n, sum for Σ, sqrt, and square. Furthermore, we will need to map through each x and y index and multiply them, as well as square them. Lets start with by adding n to our file using count: # Python3def n (arr): return arr.count() The next step is to map through each ‘x’ and ‘y’ pair and return a sum of their products: def product (x, y): return x * ydef sumXTimesY (x, y): return sum(map(product, x, y)) Now we can easily define the numerator: def numerator (x, y): return n(x) * sumXTimesY(x, y) - sum(x) * sum(y) The denominator looks a little trickier, and will need to be broken up into its smallest components. Let’s define sumOfSquares: def sumOfSquares (val): return sum(map(square, val)) Now we have all the tools to define the denominator with the help of our sqrt function from Part 2: def denominator (x, y): return sqrt((n(x) * sumOfSquares(x) - square(sum(x))) * (n(y) * sumOfSquares(y) - square(sum(y)))) We can now put it all together in our final version of the file: Not too shabby! Not only do we see a very strong relationship between ‘distance’ and ‘high-speed-running’ at an r of 0.88, but we have put it all together using functional and composable code that is easy to reason about. Furthermore, breaking apart this Pearson r formula in this way creates a deeper understanding of what exactly a relationship between two variables really looks like. It is worth reiterating that using libraries that do the statistical heavy lifting is the way to go, however the point of this article is to work on using simple functional concepts to solve complex problems. This article introduced two libraries that are very powerful for data visualization and analysis: Seaborn and Pandas. Seaborn is a statistical visualization library that is based on Matplotlib. It is my go-to library for high-level statistical plotting due to its simplicity and flexibility. Pandas is a wonderful data analysis toolkit that will be very attractive to Sport Scientists who come from a background of working with spreadsheets. My goal with this article was to provide Sport Scientists with the tools to build a functional code-base, and to understand how to approach analyzing datasets in a modular and functional way.
[ { "code": null, "e": 337, "s": 47, "text": "Python has been gaining a tremendous amount of popularity over the past few years, and is the language of choice for many data scientists across the world. It is no accident that it is also gaining popularity for sport scientists, who have to work with a l...
PHP | min( ) Function - GeeksforGeeks
08 Mar, 2018 The min() function of PHP is used to find the lowest value in an array, or the lowest value of several specified values. The min() function can take an array or several numbers as an argument and return the numerically minimum value among the passed parameters. The return type is not fixed, it can be an integer value or a float value based on input. Syntax: min(array_values) or min(value1, value2, ...) Parameters: This function accepts two different types of parameters which are explained below: array_values : It specifies an array containing the values.value1, value2, ... : It specifies two or more than two values to be compared. array_values : It specifies an array containing the values. value1, value2, ... : It specifies two or more than two values to be compared. Return Value: The min() function returns the numerically minimum value. Examples: Input : min(12, 4, 62, 97, 26) Output : 4 Input : min(array(28, 36, 87, 12)) Output : 12 Below programs illustrate the working of min() in PHP: Program 1: <?php echo (min(12, 4, 62, 97, 26)); ?> Output: 4 Program 2: <?php echo (min(array(28, 36, 87, 12))); ?> Output: 12 Important points to note : min() function is used to find the numerically minimum number. min() function can be used on two or more than two values or it can be used on an array. The value returned is of mixed data type. Reference:http://php.net/manual/en/function.min.php PHP-array PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? Comparing two dates in PHP 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": 24602, "s": 24574, "text": "\n08 Mar, 2018" }, { "code": null, "e": 24954, "s": 24602, "text": "The min() function of PHP is used to find the lowest value in an array, or the lowest value of several specified values. The min() function can take an array or se...
C++ Strings
Strings are used for storing text. A string variable contains a collection of characters surrounded by double quotes: Create a variable of type string and assign it a value: To use strings, you must include an additional header file in the source code, the <string> library: Fill in the missing part to create a greeting variable of type string and assign it the value Hello. = ; Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 35, "s": 0, "text": "Strings are used for storing text." }, { "code": null, "e": 118, "s": 35, "text": "A string variable contains a collection of characters surrounded by double quotes:" }, { "code": null, "e": 174, "s": 118, "text": "Cre...
How to Add Easy FlipView in Android? - GeeksforGeeks
05 May, 2021 EasyFlipView is an Android library that allows us to easily create a flip view in our android app. We can use this feature in many apps such as the app in which we store the credit or debit card details of the user (the user can easily flip the card to view the CVV of the card). A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Attribute Name Default Value Description app:flipFrom=”right” app:flipFrom=”back” left front 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: Before going to the coding section first do some pre-task Go to app -> res -> values -> colors.xml file and set the colors for the app. XML <?xml version="1.0" encoding="utf-8"?><resources> <color name="colorPrimary">#0F9D58</color> <color name="colorPrimaryDark">#0F9D58</color> <color name="colorAccent">#05af9b</color> <color name="white">#ffffff</color> </resources> Go to Gradle Scripts -> build.gradle (Module: app) section and import the following dependencies and click the “the” on the above pop up. implementation ‘com.wajahatkarim3.EasyFlipView:EasyFlipView:3.0.0’ Step 3: Designing the UI In the activity_main.xml remove the default Text View and change the layout to Relative layout and add the EasyFlipView and inside it, we include 2 layouts card_layout_back.xml and card_layout_front.xml (We create a 2 layout in the next step ), follow the same step and add one more card_layout_front of horizontal type. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- Vertical Flip View --> <com.wajahatkarim3.easyflipview.EasyFlipView android:id="@+id/easyFlipViewVertical" android:layout_width="match_parent" android:layout_height="wrap_content" app:autoFlipBack="true" app:autoFlipBackTime="2000" app:flipDuration="400" app:flipEnabled="true" app:flipFrom="front" app:flipOnTouch="true" app:flipType="vertical"> <!-- Back Layout --> <include layout="@layout/card_layout_back" /> <!-- Front Layout --> <include layout="@layout/card_layout_front" /> </com.wajahatkarim3.easyflipview.EasyFlipView> <!-- Horizontal Flip View --> <com.wajahatkarim3.easyflipview.EasyFlipView android:id="@+id/easyFlipViewHorizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" app:autoFlipBack="false" app:flipDuration="400" app:flipEnabled="true" app:flipFrom="right" app:flipOnTouch="true" app:flipType="horizontal"> <!-- Back Layout --> <include layout="@layout/card_layout_back" /> <!-- Front Layout --> <include layout="@layout/card_layout_front" /> </com.wajahatkarim3.easyflipview.EasyFlipView> </RelativeLayout> Now go to res -> layout and right-click on it then New -> Layout Resource File (name the file card_layout_back). Now open the card_layout_back.xml file, add a simple ImageView, and set the src as the image you want. Below is the code for the card_layout_back.xml file XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <!-- simple image view --> <ImageView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="8dp" android:src="@drawable/card_back" /> </androidx.constraintlayout.widget.ConstraintLayout> Repeat the above step and create the card_layout_front.xml file. Below is the code for the card_layout_front.xml file XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <!-- simple image view --> <ImageView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="8dp" android:src="@drawable/card_front" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 4: Coding Part We can add an OnFlipAnimationListener to both the horizontal and vertical flip view and when the user flips the card we simply show a toast message . Below is the complete code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.wajahatkarim3.easyflipview.EasyFlipView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // creating objects of EasyFlipView EasyFlipView easyFlipViewVertical = (EasyFlipView) findViewById(R.id.easyFlipViewVertical); EasyFlipView easyFlipViewHorizontal = (EasyFlipView) findViewById(R.id.easyFlipViewHorizontal); // creating OnFlipAnimationListener for easyFlipViewVertical easyFlipViewVertical.setOnFlipListener(new EasyFlipView.OnFlipAnimationListener() { @Override public void onViewFlipCompleted(EasyFlipView flipView, EasyFlipView.FlipState newCurrentSide) { // showing simple toast message to the user Toast.makeText(MainActivity.this, "Vertical Flip Completed :)", Toast.LENGTH_SHORT).show(); } }); // creating OnFlipAnimationListener for easyFlipViewHorizontal easyFlipViewHorizontal.setOnFlipListener(new EasyFlipView.OnFlipAnimationListener() { @Override public void onViewFlipCompleted(EasyFlipView flipView, EasyFlipView.FlipState newCurrentSide) { // showing simple toast message to the user Toast.makeText(MainActivity.this, "Horizontal Flip Completed :)", Toast.LENGTH_SHORT).show(); } }); }} Output: Android-View Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Retrofit with Kotlin Coroutine in Android Android Listview in Java with Example How to Read Data from SQLite Database in Android? How to Change the Background Color After Clicking the Button in Android? Flutter - Custom Bottom Navigation Bar Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Initialize an ArrayList in Java
[ { "code": null, "e": 25036, "s": 25008, "text": "\n05 May, 2021" }, { "code": null, "e": 25481, "s": 25036, "text": "EasyFlipView is an Android library that allows us to easily create a flip view in our android app. We can use this feature in many apps such as the app in which we...
numpy.swapaxes() function | Python - GeeksforGeeks
22 Apr, 2020 numpy.swapaxes() function interchange two axes of an array. Syntax : numpy.swapaxes(arr, axis1, axis2)Parameters :arr : [array_like] input array.axis1 : [int] First axis.axis2 : [int] Second axis.Return : [ndarray] In earlier NumPy versions, a view of arr is returned only if the order of the axes is changed, otherwise the input array is returned. For NumPy >= 1.10.0, if arr is an ndarray, then a view of arr is returned; otherwise a new array is created. Code #1 : # Python program explaining# numpy.swapaxes() function # importing numpy as geek import numpy as geek arr = geek.array([[2, 4, 6]]) gfg = geek.swapaxes(arr, 0, 1) print (gfg) Output : [[2] [4] [6]] Code #2 : # Python program explaining# numpy.swapaxes() function # importing numpy as geek import numpy as geek arr = geek.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]) gfg = geek.swapaxes(arr, 0, 2) print (gfg) Output : [[[0 4] [2 6]] [[1 5] [3 7]]] Python numpy-arrayManipulation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python Classes and Objects Create a directory in Python Python | os.path.join() method Python | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 24390, "s": 24362, "text": "\n22 Apr, 2020" }, { "code": null, "e": 24450, "s": 24390, "text": "numpy.swapaxes() function interchange two axes of an array." }, { "code": null, "e": 24848, "s": 24450, "text": "Syntax : numpy.swapaxes(arr, a...
Implement a Dictionary using Trie - GeeksforGeeks
16 Jul, 2019 Implement a dictionary using Trie such that if the input is a string representing a word, the program prints its meaning from the prebuilt dictionary. Examples: Input: str = “map”Output: a diagrammatic representation of an area Input: str = “language”Output: the method of human communication Approach: We can use a Trie to efficiently store strings and search them. Here, an implementation of a dictionary using Trie (memory optimization using hash-map) is discussed. We add another field to Trie node, a string which will hold the meaning of a word. While searching for the meaning of the required word, we search for the word in Trie and if the word is present (i.e isEndOfWord = true) then we return its meaning otherwise we return an empty string. Below is the implementation of the above approach: // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Structure for Triestruct Trie { bool isEndOfWord; unordered_map<char, Trie*> map; string meaning;}; // Function to create a new Trie nodeTrie* getNewTrieNode(){ Trie* node = new Trie; node->isEndOfWord = false; return node;} // Function to insert a word with its meaning// in the dictionary built using a Trievoid insert(Trie*& root, const string& str, const string& meaning){ // If root is null if (root == NULL) root = getNewTrieNode(); Trie* temp = root; for (int i = 0; i < str.length(); i++) { char x = str[i]; // Make a new node if there is no path if (temp->map.find(x) == temp->map.end()) temp->map[x] = getNewTrieNode(); temp = temp->map[x]; } // Mark end of word and store the meaning temp->isEndOfWord = true; temp->meaning = meaning;} // Function to search a word in the Trie// and return its meaning if the word existsstring getMeaning(Trie* root, const string& word){ // If root is null i.e. the dictionary is empty if (root == NULL) return ""; Trie* temp = root; // Search a word in the Trie for (int i = 0; i < word.length(); i++) { temp = temp->map[word[i]]; if (temp == NULL) return ""; } // If it is the end of a valid word stored // before then return its meaning if (temp->isEndOfWord) return temp->meaning; return "";} // Driver codeint main(){ Trie* root = NULL; // Build the dictionary insert(root, "language", "the method of human communication"); insert(root, "computer", "A computer is a machine that can be \ instructed to carry out sequences of arithmetic or \logical operations automatically via computer programming"); insert(root, "map", "a diagrammatic representation \of an area"); insert(root, "book", "a written or printed work \consisting of pages glued or sewn together along one \side and bound in covers."); insert(root, "science", "the intellectual and \practical activity encompassing the systematic study \of the structure and behaviour of the physical and \natural world through observation and experiment."); string str = "map"; cout << getMeaning(root, str); return 0;} a diagrammatic representation of an area Trie Advanced Data Structure Pattern Searching Searching Strings Searching Strings Pattern Searching Trie Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Ordered Set and GNU C++ PBDS 2-3 Trees | (Search, Insert and Deletion) Extendible Hashing (Dynamic approach to DBMS) Suffix Array | Set 1 (Introduction) Difference between Backtracking and Branch-N-Bound technique KMP Algorithm for Pattern Searching Rabin-Karp Algorithm for Pattern Searching Naive algorithm for Pattern Searching Boyer Moore Algorithm for Pattern Searching Check if a string is substring of another
[ { "code": null, "e": 25843, "s": 25815, "text": "\n16 Jul, 2019" }, { "code": null, "e": 25994, "s": 25843, "text": "Implement a dictionary using Trie such that if the input is a string representing a word, the program prints its meaning from the prebuilt dictionary." }, { ...
How to remove line breaks from the string in PHP? - GeeksforGeeks
01 Apr, 2021 The line break can be removed from string by using str_replace() function. The str_replace() function is an inbuilt function in PHP which is used to replace all the occurrences of the search string or array of search strings by replacement string or array of replacement strings in the given string or array respectively.Syntax: str_replace ( $searchVal, $replaceVal, $subjectVal, $count ) Return Type: This function returns a new string or array based on the $subjectVal parameter with replaced values.Example: After replacing the <br> tag, the new string is taken in the variable text. php <?php // Declare a variable and initialize it// with strings containing <br> tag$text = "Geeks<br>For<br>Geeks"; // Display the stringecho $text;echo "\n"; // Use str_replace() function to// remove <br> tag$text = str_replace("<br>", "", $text); // Display the new stringecho $text; ?> Geeks For Geeks GeeksForGeeks Using preg_replace() function: The preg_replace() function is an inbuilt function in PHP which is used to perform a regular expression for search and replace the content.Syntax: preg_replace( $pattern, $replacement, $subject, $limit, $count ) Return Value: This function returns an array if the subject parameter is an array, or a string otherwise.Example: This example use preg_replace() function to remove line break. php <?php // Declare a variable and initialize it// with strings containing <br> tag$text = "Geeks<br>For<br>Geeks"; // Display the stringecho $text;echo "\n"; // Use preg_replace() function to// remove <br> and \n$text = preg_replace( "/<br>|\n/", "", $text ); // Display the new stringecho $text; ?> Geeks For Geeks GeeksForGeeks arorakashish0911 Picked PHP PHP Programs Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime Comparing two dates in PHP How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to call PHP function on the click of a Button ? How to check whether an array is empty using PHP? Comparing two dates in PHP
[ { "code": null, "e": 25158, "s": 25130, "text": "\n01 Apr, 2021" }, { "code": null, "e": 25489, "s": 25158, "text": "The line break can be removed from string by using str_replace() function. The str_replace() function is an inbuilt function in PHP which is used to replace all th...
Write a java program to tOGGLE each word in string?
You can change the cases of the letters of a word using toUpperCase() and toLowerCase() methods. Split each word in the string using the split() method, change the first letter of each word to lower case and remaining letters to upper case. Live Demo public class Sample{ public static void main(String args[]){ String sample = "Hello How are you"; String[] words = sample.split(" "); String result = ""; for(String word:words){ String firstSub = word.substring(0, 1); String secondSub = word.substring(1); result = result+firstSub.toLowerCase()+secondSub.toUpperCase()+" "; } System.out.println(result); } } hELLO hOW aRE yOU
[ { "code": null, "e": 1159, "s": 1062, "text": "You can change the cases of the letters of a word using toUpperCase() and toLowerCase() methods." }, { "code": null, "e": 1303, "s": 1159, "text": "Split each word in the string using the split() method, change the first letter of ea...
ip command in Linux with examples - GeeksforGeeks
22 May, 2019 ip command in Linux is present in the net-tools which is used for performing several network administration tasks. IP stands for Internet Protocol. This command is used to show or manipulate routing, devices, and tunnels. It is similar to ifconfig command but it is much more powerful with more functions and facilities attached to it. ifconfig is one of the deprecated commands in the net-tools of Linux that has not been maintained for many years. ip command is used to perform several tasks like assigning an address to a network interface or configuring network interface parameters.It can perform several other tasks like configuring and modifying the default and static routing, setting up tunnel over IP, listing IP addresses and property information, modifying the status of the interface, assigning, deleting and setting up IP addresses and routes. Syntax: ip [ OPTIONS ] OBJECT { COMMAND | help } Options: -address: This option is used to show all IP addresses associated on all network devices.ip addressThis will show the information related to all interfaces available on our system, but if we want to view the information of any particular interface, add the options show followed by the name of the particular network interface.ip address show (interface)Example:ip address show enp3s0 ip address This will show the information related to all interfaces available on our system, but if we want to view the information of any particular interface, add the options show followed by the name of the particular network interface. ip address show (interface) Example: ip address show enp3s0 -link: It is used to display link layer information, it will fetch characteristics of the link layer devices currently available. Any networking device which has a driver loaded can be classified as an available device.ip linkThis link option when used with -s option is used to show the statistics of the various network interfaces.ip -s linkAnd, to get information about a particular network interface, add option show followed by the name of the particular network interface.ip -s link show (interface)Example:ip -s link show enp3s0 ip link This link option when used with -s option is used to show the statistics of the various network interfaces. ip -s link And, to get information about a particular network interface, add option show followed by the name of the particular network interface. ip -s link show (interface) Example: ip -s link show enp3s0 -route: This command helps you to see the route packets your network will take as set in your routing table. The first entry is the default route.ip route ip route -add: This is used to assign an IP address to an interface.ip a add (ip_address) dev interfaceExample:ip a add 192.168.1.50/24 dev enp3s0 ip a add (ip_address) dev interface Example: ip a add 192.168.1.50/24 dev enp3s0 -del: This is used to delete an assigned IP address to an interface.ip a del (ip_address) dev interfaceExample:ip a del 192.168.1.50/24 dev enp3s0 ip a del (ip_address) dev interface Example: ip a del 192.168.1.50/24 dev enp3s0 -up: This option enables a network interface.ip link set (interface) upExample:ip link set enp3s0 up ip link set (interface) up Example: ip link set enp3s0 up -down: This option disables a network interface.ip link set (interface) downExample:ip link set enp3s0 down ip link set (interface) down Example: ip link set enp3s0 down -monitor: This command can monitor and displays the state of devices, addresses and routes continuously.ip monitor ip monitor -help: This command is used as a help to know more about ip command.ip help ip help -neighbour: This command is used to view the MAC address of the devices connected to your system.ip neighbourSTABLE: This means that the neighbor is valid, but is probably already unreachable, so the kernel will try to check it at the first transmission.REACHABLE: This means that the neighbor is valid and reachable.DELAY: This means that a packet has been sent to the stable neighbor and the kernel is waiting for confirmation.Modifying ARP(address resolution protocol) entries:Delete an ARP entry:ip neighbour del (ip_address) dev interface Example:ip neighbour del 192.168.0.200 dev enp3s0 Add an ARP entry:ip neighbour add (ip_address) dev interface Example:ip neighbour add 192.168.0.200 dev enp3s0 My Personal Notes arrow_drop_upSave ip neighbour STABLE: This means that the neighbor is valid, but is probably already unreachable, so the kernel will try to check it at the first transmission. REACHABLE: This means that the neighbor is valid and reachable. DELAY: This means that a packet has been sent to the stable neighbor and the kernel is waiting for confirmation. Modifying ARP(address resolution protocol) entries: Delete an ARP entry:ip neighbour del (ip_address) dev interface Example:ip neighbour del 192.168.0.200 dev enp3s0 ip neighbour del (ip_address) dev interface Example: ip neighbour del 192.168.0.200 dev enp3s0 Add an ARP entry:ip neighbour add (ip_address) dev interface Example:ip neighbour add 192.168.0.200 dev enp3s0 ip neighbour add (ip_address) dev interface Example: ip neighbour add 192.168.0.200 dev enp3s0 linux-command Linux-networking-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments TCP Server-Client implementation in C ZIP command in Linux with examples UDP Server-Client implementation in C SORT command in Linux/Unix with examples tar command in Linux with examples Named Pipe or FIFO with example C program Mutex lock for Linux Thread Synchronization echo command in Linux with Examples Thread functions in C/C++ diff command in Linux with examples
[ { "code": null, "e": 24292, "s": 24264, "text": "\n22 May, 2019" }, { "code": null, "e": 25150, "s": 24292, "text": "ip command in Linux is present in the net-tools which is used for performing several network administration tasks. IP stands for Internet Protocol. This command is...
How to connect a variable to the Tkinter Entry widget?
Tkinter Entry widget is an Input widget that supports and accepts single-line user input. It accepts all types of characters in UTF-8 module. In order to get the input from the Entry widget, we have to define a variable (based on Data Types it accepts) that accepts only string characters. Then, by using get() method, we can print the given input from the Entry widget. # Import the Tkinter Library from tkinter import * # Create an instance of Tkinter Frame win = Tk() # Set the geometry of window win.geometry("700x250") # Define a String Variable var = StringVar() # Define a function to print the Entry widget Input def printinput(*args): print(var.get()) # Create an Entry widget entry = Entry(win, width=35, textvariable=var) entry.pack() # Trace the Input from Entry widget var.trace("w", printinput) win.mainloop() Running the above code will display a window with an Entry widget. When we write something in the Entry widget, it will just print out all the characters from the Entry widget on the console. H He Hel Hell Hello Hello Hello W Hello Wo Hello Wor Hello Worl Hello World Hello World!
[ { "code": null, "e": 1433, "s": 1062, "text": "Tkinter Entry widget is an Input widget that supports and accepts single-line user input. It accepts all types of characters in UTF-8 module. In order to get the input from the Entry widget, we have to define a variable (based on Data Types it accepts) ...
How to Align modal content box to center of any screen? - GeeksforGeeks
30 Jul, 2021 The Bootstrap Modal plugin is a dialog box/popup window that is displayed on top of the current page. By default, the Bootstrap modal window is aligned to the top of the page with some margin. But you can align it in the middle of the page vertically by using CSS vertical-align property. We also can use JavaScript to centered the modalBelow examples illustrate the approach: Example 1: First, we will design modal content for the sign-up then by using CSS we will align that modal centered(vertically). Using the vertical-align property, the vertical-align property sets the vertical alignment of an element. <!DOCTYPE html><html> <head> <title>Bootstrap Modal Alignment</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> </script> <style> /* Text alignment for body */ body { text-align: center; } /* Styling h1 tag */ h1 { color: green; text-align: center; } /* Styling modal */ .modal:before { content: ''; display: inline-block; height: 100%; vertical-align: middle; } .modal-dialog { display: inline-block; vertical-align: middle; } .modal .modal-content { padding: 20px 20px 20px 20px; -webkit-animation-name: modal-animation; -webkit-animation-duration: 0.5s; animation-name: modal-animation; animation-duration: 0.5s; } @-webkit-keyframes modal-animation { from { top: -100px; opacity: 0; } to { top: 0px; opacity: 1; } } @keyframes modal-animation { from { top: -100px; opacity: 0; } to { top: 0px; opacity: 1; } } </style></head> <body> <h1> GeeksforGeeks </h1> <p> A Computer Science Portal for Geeks </p> <a href="#signupModal" data-toggle="modal"> Sign-Up</a> <div class="modal" id="signupModal" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <!-- Modal root --> <div class="m-header"> <button class="close" data-dismiss="modal"> × </button> <h2 class="myModalLabel"> Sign Up </h2> </div> <!-- Modal body --> <div class="inputs"> <!-- username input --> <div class="form-group input-group"> <label for="username" class="sr-only"> Username </label> <span class="input-group-addon"> <i class="fa fa-user"></i> </span> <input type="text" class="form-control" id="username" placeholder="Username"> </div> <!-- Email input --> <div class="form-group input-group"> <span class="input-group-addon"> <i class="fa fa-envelope"></i> </span> <label for="email" class="sr-only"> Email </label> <input type="email" class="form-control" id="email" placeholder="Email Address"> </div> <!-- Password --> <div class="form-group input-group"> <span class="input-group-addon"> <i class="fa fa-lock"></i> </span> <label for="password" class="sr-only"> Password </label> <input type="password" class="form-control" id="password" placeholder="Choose a password"> </div> <!-- Confirm Password --> <div class="form-group input-group"> <span class="input-group-addon"> <i class="fa fa-lock"></i> </span> <label for="password2" class="sr-only"> Confirm Password </label> <input type="password" class="form-control" id="password2" placeholder="Confirm password"> </div> </div> <!-- Modal footer --> <div class="footer"> <button type="submit">Sign Up</button> <p> Already have an account?! <a href="#loginModal" data-toggle="modal" data-dismiss="modal"> Login! </a> </p> </div> </div> </div> </div> </body> </html> Output : Example 2: Similarly we first create a modal content for the sign-up then instead of CSS we will use JavaScript to centered the modal(vertically). We will use CSS for designing just. In this example first, use the find() method to find out the modal dialog. Then subtract the modal height from the window height and divide that into half and will place the modal that will be the centered(vertically). This solution will dynamically adjust the alignment of the modal. <!DOCTYPE html><html> <head> <title>Center Align Bootstrap Modal Vertically</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> </script> <style> /* Text alignment for body */ body { text-align: center; } /* Styling h1 tag */ h1 { color: green; text-align: center; } /* Styling modal */ .modal .modal-content { padding: 20px 20px 20px 20px; -webkit-animation-name: modal-animation; -webkit-animation-duration: 0.5s; animation-name: modal-animation; animation-duration: 0.5s; } @-webkit-keyframes modal-animation { from { top: -100px; opacity: 0; } to { top: 0px; opacity: 1; } } @keyframes modal-animation { from { top: -100px; opacity: 0; } to { top: 0px; opacity: 1; } } </style></head> <body> <h1> GeeksforGeeks </h1> <p> A Computer Science Portal for Geeks </p> <a href="#signupModal" data-toggle="modal"> Sign-Up </a> <div class="modal" id="signupModal" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <!-- Modal root --> <div class="m-header"> <button class="close" data-dismiss="modal"> × </button> <h2 class="myModalLabel">Sign Up</h2> </div> <!-- Modal body --> <div class="inputs"> <!-- username input --> <div class="form-group input-group"> <label for="username" class="sr-only"> Username </label> <span class="input-group-addon"> <i class="fa fa-user"></i> </span> <input type="text" class="form-control" id="username" placeholder="Username"> </div> <!-- Email input --> <div class="form-group input-group"> <span class="input-group-addon"> <i class="fa fa-envelope"></i> </span> <label for="email" class="sr-only"> Email </label> <input type="email" class="form-control" id="email" placeholder="Email Address"> </div> <!-- Password --> <div class="form-group input-group"> <span class="input-group-addon"> <i class="fa fa-lock"></i> </span> <label for="password" class="sr-only"> Password </label> <input type="password" class="form-control" id="password" placeholder="Choose a password"> </div> <!-- Confirm Password --> <div class="form-group input-group"> <span class="input-group-addon"> <i class="fa fa-lock"></i> </span> <label for="password2" class="sr-only"> Confirm Password </label> <input type="password" class="form-control" id="password2" placeholder="Confirm password"> </div> </div> <!-- MOdal footer --> <div class="footer"> <button type="submit">Sign Up</button> <p> Already have an account?! <a href="#loginModal" data-toggle="modal" data-dismiss="modal"> Login! </a> </p> </div> </div> </div> </div> <script> $(document).ready(function() { /* Centering the modal vertically */ function alignModal() { var modalDialog = $(this).find(".modal-dialog"); modalDialog.css("margin-top", Math.max(0, ($(window).height() - modalDialog.height()) / 2)); } $(".modal").on("shown.bs.modal", alignModal); /* Resizing the modal according the screen size */ $(window).on("resize", function() { $(".modal:visible").each(alignModal); }); }); </script> </body> </html> Output : HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc JavaScript-Misc Picked Technical Scripter 2019 Bootstrap CSS HTML Technical Scripter Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Show Images on Click using HTML ? How to set Bootstrap Timepicker using datetimepicker library ? Create a Homepage for Restaurant using HTML , CSS and Bootstrap How to place two bootstrap cards next to each other ? How to Use Bootstrap with React? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet)
[ { "code": null, "e": 24224, "s": 24196, "text": "\n30 Jul, 2021" }, { "code": null, "e": 24601, "s": 24224, "text": "The Bootstrap Modal plugin is a dialog box/popup window that is displayed on top of the current page. By default, the Bootstrap modal window is aligned to the top ...
How to convert string to camel case in JavaScript ? - GeeksforGeeks
21 Jun, 2019 Given a string and the task is to convert it into camelCase using JavaScript. In this case, the first character of string converted into lower case and other characters after space will be converted into upper case character. Approach: Use str.replace() method to replace the first character of string into lower case and other characters after space will be into upper case. The toUpperCase() and toLowerCase() methods are used to convert the string character into upper case and lower case respectively. Example 1: This example uses RegExp, toLowerCase() and toUpperCase() methods to convert a string into camelCase. <!DOCTYPE html><html> <head> <title> How to convert string to camel case in JavaScript ? </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <p id="GFG_UP" style= "font-size: 15px; font-weight: bold;"> </p> <button onclick="gfg_Run();"> click here </button> <p id="GFG_DOWN" style= "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var str = 'Click the button to convert to camelCase'; el_up.innerHTML = str; function camelCase(str) { return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function(word, index) { return index == 0 ? word.toLowerCase() : word.toUpperCase(); }).replace(/\s+/g, ''); } function gfg_Run() { el_down.innerHTML = camelCase(str); } </script></body> </html> Output: Before clicking the button: After clicking the button: Example 2: This example uses replace(), toLowerCase() and toUpperCase() methods to convert a string into camelCase. <!DOCTYPE html><html> <head> <title> How to convert string to camel case in JavaScript ? </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <p id="GFG_UP" style= "font-size: 15px; font-weight: bold;"> </p> <button onclick="gfg_Run();"> click here </button> <p id="GFG_DOWN" style= "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var str = 'Click the button to convert to camelCase'; el_up.innerHTML = str; function camelCase(str) { return str .replace(/\s(.)/g, function(a) { return a.toUpperCase(); }) .replace(/\s/g, '') .replace(/^(.)/, function(b) { return b.toLowerCase(); }); } function gfg_Run() { el_down.innerHTML = camelCase(str); } </script></body> </html> Output: Before clicking the button: After clicking the button: javascript-string JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Convert a string to an integer in JavaScript How to append HTML code to a div using JavaScript ? Difference Between PUT and PATCH Request Installation of Node.js on Linux Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24524, "s": 24496, "text": "\n21 Jun, 2019" }, { "code": null, "e": 24750, "s": 24524, "text": "Given a string and the task is to convert it into camelCase using JavaScript. In this case, the first character of string converted into lower case and other chara...
Swift - Functions
A function is a set of statements organized together to perform a specific task. A Swift 4 function can be as simple as a simple C function to as complex as an Objective C language function. It allows us to pass local and global parameter values inside the function calls. Function Declaration − tells the compiler about a function's name, return type, and parameters. Function Declaration − tells the compiler about a function's name, return type, and parameters. Function Definition − It provides the actual body of the function. Function Definition − It provides the actual body of the function. Swift 4 functions contain parameter type and its return types. In Swift 4, a function is defined by the "func" keyword. When a function is newly defined, it may take one or several values as input 'parameters' to the function and it will process the functions in the main body and pass back the values to the functions as output 'return types'. Every function has a function name, which describes the task that the function performs. To use a function, you "call" that function with its name and pass input values (known as arguments) that match the types of the function's parameters. Function parameters are also called as 'tuples'. A function's arguments must always be provided in the same order as the function's parameter list and the return values are followed by →. func funcname(Parameters) -> returntype { Statement1 Statement2 --- Statement N return parameters } Take a look at the following code. The student’s name is declared as string datatype declared inside the function 'student' and when the function is called, it will return student’s name. func student(name: String) -> String { return name } print(student(name: "First Program")) print(student(name: "About Functions")) When we run the above program using playground, we get the following result − First Program About Functions Let us suppose we defined a function called 'display' to Consider for example to display the numbers a function with function name 'display' is initialized first with argument 'no1' which holds integer data type. Then the argument 'no1' is assigned to argument 'a' which hereafter will point to the same data type integer. Now the argument 'a' is returned to the function. Here display() function will hold the integer value and return the integer values when each and every time the function is invoked. func display(no1: Int) -> Int { let a = no1 return a } print(display(no1: 100)) print(display(no1: 200)) When we run above program using playground, we get the following result − 100 200 Swift 4 provides flexible function parameters and its return values from simple to complex values. Similar to that of C and Objective C, functions in Swift 4 may also take several forms. A function is accessed by passing its parameter values to the body of the function. We can pass single to multiple parameter values as tuples inside the function. func mult(no1: Int, no2: Int) -> Int { return no1*no2 } print(mult(no1: 2, no2: 20)) print(mult(no1: 3, no2: 15)) print(mult(no1: 4, no2: 30)) When we run above program using playground, we get the following result − 40 45 120 We may also have functions without any parameters. func funcname() -> datatype { return datatype } Following is an example having a function without a parameter − func votersname() -> String { return "Alice" } print(votersname()) When we run the above program using playground, we get the following result − Alice Functions are also used to return string, integer, and float data type values as return types. To find out the largest and smallest number in a given array function 'ls' is declared with large and small integer datatypes. An array is initialized to hold integer values. Then the array is processed and each and every value in the array is read and compared for its previous value. When the value is lesser than the previous one it is stored in 'small' argument, otherwise it is stored in 'large' argument and the values are returned by calling the function. func ls(array: [Int]) -> (large: Int, small: Int) { var lar = array[0] var sma = array[0] for i in array[1..<array.count] { if i < sma { sma = i } else if i > lar { lar = i } } return (lar, sma) } let num = ls(array: [40,12,-5,78,98]) print("Largest number is: \(num.large) and smallest number is: \(num.small)") When we run the above program using playground, we get the following result − Largest number is: 98 and smallest number is: -5 Some functions may have arguments declared inside the function without any return values. The following program declares a and b as arguments to the sum() function. inside the function itself the values for arguments a and b are passed by invoking the function call sum() and its values are printed thereby eliminating return values. func sum(a: Int, b: Int) { let a = a + b let b = a - b print(a, b) } sum(a: 20, b: 10) sum(a: 40, b: 10) sum(a: 24, b: 6) When we run the above program using playground, we get the following result − 30 20 50 40 30 24 Swift 4 introduces 'optional' feature to get rid of problems by introducing a safety measure. Consider for example we are declaring function values return type as integer but what will happen when the function returns a string value or either a nil value. In that case compiler will return an error value. 'optional' are introduced to get rid of these problems. Optional functions will take two forms 'value' and a 'nil'. We will mention 'Optionals' with the key reserved character '?' to check whether the tuple is returning a value or a nil value. func minMax(array: [Int]) -> (min: Int, max: Int)? { if array.isEmpty { return nil } var currentMin = array[0] var currentMax = array[0] for value in array[1..<array.count] { if value < currentMin { currentMin = value } else if value > currentMax { currentMax = value } } return (currentMin, currentMax) } if let bounds = minMax(array: [8, -6, 2, 109, 3, 71]) { print("min is \(bounds.min) and max is \(bounds.max)") } When we run above program using playground, we get following result − min is -6 and max is 109 ''Optionals' are used to check 'nil' or garbage values thereby consuming lot of time in debugging and make the code efficient and readable for the user. Local parameter names are accessed inside the function alone. func sample(number: Int) { print(number) } Here, the func sample argument number is declared as internal variable since it is accessed internally by the function sample(). Here the 'number' is declared as local variable but the reference to the variable is made outside the function with the following statement − func sample(number: Int) { print(number) } sample(number: 1) sample(number: 2) sample(number: 3) When we run the above program using playground, we get the following result − 1 2 3 External parameter names allow us to name a function parameters to make their purpose more clear. For example below you can name two function parameters and then call that function as follows − func pow(firstArg a: Int, secondArg b: Int) -> Int { var res = a for _ in 1..<b { res = res * a } print(res) return res } pow(firstArg:5, secondArg:3) When we run the above program using playground, we get the following result − 125 When we want to define function with multiple number of arguments, then we can declare the members as 'variadic' parameters. Parameters can be specified as variadic by (···) after the parameter name. func vari<N>(members: N...){ for i in members { print(i) } } vari(members: 4,3,5) vari(members: 4.5, 3.1, 5.6) vari(members: "Swift 4", "Enumerations", "Closures") When we run the above program using playground, we get the following result − 4 3 5 4.5 3.1 5.6 Swift 4 Enumerations Closures Functions by default consider the parameters as 'constant', whereas the user can declare the arguments to the functions as variables also. We already discussed that 'let' keyword is used to declare constant parameters and variable parameters is defined with 'var' keyword. I/O parameters in Swift 4 provide functionality to retain the parameter values even though its values are modified after the function call. At the beginning of the function parameter definition, 'inout' keyword is declared to retain the member values. It derives the keyword 'inout' since its values are passed 'in' to the function and its values are accessed and modified by its function body and it is returned back 'out' of the function to modify the original argument. Variables are only passed as an argument for in-out parameter since its values alone are modified inside and outside the function. Hence no need to declare strings and literals as in-out parameters. '&' before a variable name refers that we are passing the argument to the in-out parameter. func temp(a1: inout Int, b1: inout Int) { let t = a1 a1 = b1 b1 = t } var no = 2 var co = 10 temp(a1: &no, b1: &co) print("Swapped values are \(no), \(co)") When we run the above program using playground, we get the following result − Swapped values are 10, 2 Each and every function follows the specific function by considering the input parameters and outputs the desired result. func inputs(no1: Int, no2: Int) -> Int { return no1/no2 } Following is an example − func inputs(no1: Int, no2: Int) -> Int { return no1/no2 } print(inputs(no1: 20, no2: 10)) print(inputs(no1: 36, no2: 6)) When we run the above program using playground, we get the following result − 2 6 Here the function is initialized with two arguments no1 and no2 as integer data types and its return type is also declared as 'int' Func inputstr(name: String) -> String { return name } Here the function is declared as string datatype. Functions may also have void data types and such functions won't return anything. func inputstr() { print("Swift 4 Functions") print("Types and its Usage") } inputstr() When we run the above program using playground, we get the following result − Swift 4 Functions Types and its Usage The above function is declared as a void function with no arguments and no return values. Functions are first passed with integer, float or string type arguments and then it is passed as constants or variables to the function as mentioned below. var addition: (Int, Int) -> Int = sum Here sum is a function name having 'a' and 'b' integer variables which is now declared as a variable to the function name addition. Hereafter both addition and sum function both have same number of arguments declared as integer datatype and also return integer values as references. func sum(a: Int, b: Int) -> Int { return a + b } var addition: (Int, Int) -> Int = sum print("Result: \(addition(40, 89))") When we run the above program using playground, we get the following result − Result: 129 We can also pass the function itself as parameter types to another function. func sum(a: Int, b: Int) -> Int { return a + b } var addition: (Int, Int) -> Int = sum print("Result: \(addition(40, 89))") func another(addition: (Int, Int) -> Int, a: Int, b: Int) { print("Result: \(addition(a, b))") } another(sum, 10, 20) When we run the above program using playground, we get the following result − Result: 129 Result: 30 A nested function provides the facility to call the outer function by invoking the inside function. func calcDecrement(forDecrement total: Int) -> () -> Int { var overallDecrement = 0 func decrementer() -> Int { overallDecrement -= total return overallDecrement } return decrementer } let decrem = calcDecrement(forDecrement: 30) print(decrem()) When we run the above program using playground, we get the following result − -30 38 Lectures 1 hours Ashish Sharma 13 Lectures 2 hours Three Millennials 7 Lectures 1 hours Three Millennials 22 Lectures 1 hours Frahaan Hussain 12 Lectures 39 mins Devasena Rajendran 40 Lectures 2.5 hours Grant Klimaytys Print Add Notes Bookmark this page
[ { "code": null, "e": 2526, "s": 2253, "text": "A function is a set of statements organized together to perform a specific task. A Swift 4 function can be as simple as a simple C function to as complex as an Objective C language function. It allows us to pass local and global parameter values inside ...
D3.js — How to Make a Beautiful Bar Chart With The Most Powerful Visualization Library | by Dario Radečić | Towards Data Science
Choosing a go-to data visualization library is harder than it seems at first. There are so many to choose from, especially if you factor in different languages. I’ve spent most of my time with Plotly and Matplotlib in Python, but today we’ll try something different — D3.js, written in — you’ve guessed it — Javascript. Let’s get a couple of things out of the way. First, I’m not a JavaScript expert, so there’s no need to point out if some things weren’t written optimally. Second, this library is verbose as they come, and it took me almost 100 rows of code to produce a decent-looking bar chart. That’s isn’t necessarily a bad thing, as you can customize the hell out of every visualization. Before proceeding further, let’s take a quick look at the end result: This color-changing happens on hover, so no, it’s not a glitch of any sort. The visualization is fairly simple but requires a decent amount of work. Let’s talk a little bit about D3 before proceeding with the code. D3 stands for Data Driven Documents. Here’s a statement from the official documentation page: D3 helps you bring data to life using HTML, SVG, and CSS. D3’s emphasis on web standards gives you the full capabilities of modern browsers without tying yourself to a proprietary framework, combining powerful visualization components and a data-driven approach to DOM manipulation. Awesome! So, what’s the point of using it? One feature I like in particular is that D3 outputs SVGs instead of PNGs, which Matplotlib outputs. It’s not my goal to confuse you with 3 letter acronyms, so I won’t dive deep into SVG and PNG differences. Here’s the only thing you should now (to start with) — SVGs are used to draw vector graphics, which means there are no pixels, which further means we don’t lose quality on zooming and scaling. That’s not the case with PNGs. Consider this image as an example: The image says it all. Let’s now make our chart. Be aware, it will be a lot of work. First things first — the data. We’ll store some dummy data in the JSON format. I’ve named mine sales.json and it looks like this: [ {“Period”: “Q1–2020”, “Amount”: 1000000}, {“Period”: “Q2–2020”, “Amount”: 875000}, {“Period”: “Q3–2020”, “Amount”: 920000}, {“Period”: “Q4–2020”, “Amount”: 400000}] And that’s it for the data. Next, we need the HTML file. Don’t worry if you don’t know HTML, as it’s fairly straightforward, and we won’t spend much time on it. For simplicity's sake, I’ve decided to embed CSS and JavaScript to the HTML file, but feel free to separate them if you wish. My file is named barchart.html: <!DOCTYPE html><html lang=”en”><head> <meta charset=”UTF-8"> <meta name=”viewport” content=”width=device-width, initial-scale=1.0"> <title>D3.JS Bar Chart</title></head> <style> rect.bar-rect { fill: #189ad3; } rect.bar-rect:hover { fill: #107dac; transition: all .2s; } </style><body> <div class=”canvas”></div> <script src=”https://d3js.org/d3.v6.js"></script> <script> // Everything else will go here </script></body></html> This is a starter template. Don’t worry about the CSS, I’ve used it just to color the bars in their normal state and in the hover state. We can now start with the chart itself! Let’s get started with the real deal. Our chart section needs some dimension info — like width and height. Also, we don’t want to make the chart occupy the entirety of the chart section, so we’ll need to add some margins on the top, right, bottom, and left. To do so we’ll set up a couple of constants: const width = 1000;const height = 600;const margin = {‘top’: 20, ‘right’: 20, ‘bottom’: 100, ‘left’: 100};const graphWidth = width — margin.left — margin.right;const graphHeight = height — margin.top — margin.bottom; I think those are pretty much self-explanatory. If not, here’s a quick clarification: The entire chart area will occupy 1000 x 600 pixels The chart itself will be inside the chart area and will have margins on all sides Margins on the bottom and on the left are larger because we will put the axes there As simple as that. Let’s proceed. Okay, we’re ready to proceed with the fun part. We need to somehow select the div with the class of canvas, as our chart will be stored there. In it, we’ll create a svg (remember that D3 outputs SVGs) and set its height and width to the ones declared earlier. Next, we can insert the graph element into the svg element, and set it dimensions to ones declared earlier. We don’t want it to start at the top left corner of the svg, so we need to translate it accordingly. Finally, we can declare constants for both X and Y-axis groups (don’t worry about those for a moment). Here’s the code: const svg = d3.select(‘.canvas’) .append(‘svg’) .attr(‘width’, width) .attr(‘height’, height);const graph = svg.append(‘g’) .attr(‘width’, graphWidth) .attr(‘height’, graphHeight) .attr(‘transform’, `translate(${margin.left}, ${margin.top})`);const gXAxis = graph.append(‘g’) .attr(‘transform’, `translate(0, ${graphHeight})`);const gYAxis = graph.append('g') If you were to open the HTML file now there’s nothing you would see, but that doesn’t mean nothing is happening. Just pop up the console and go to the elements inspector. Here’s what you should see: Awesome! Let’s finish this thing next. And now the moment you’ve been waiting for. We still have a lot of things to do, so let’s get right to it. First of all, we need to read our JSON data somehow. Then, we’ll declare scales in constants x and y respectively, and those are there to ensure that individual bars don’t overflow the svg container by accident. Next, we need to make a rect element (rectangle) for every entry we have in the dataset. Each rectangle has its height and width, X and Y values, and we’ve also added a custom class to it, just so it’s easier to style with CSS. Pretty much the same needs to be done afterward, after the enter function, and after that we can set up the axes as we wish. Our chart will have only 5 ticks on the Y-axis, and the values on the same axis will be formatted as currency. And yeah, axis label sizes are set to 14. It’s a lot of code to write, so take your time to understand what each part does: d3.json(‘sales.json’).then(data => { const y = d3.scaleLinear() .domain([0, d3.max(data, d => d.Amount)]) .range([graphHeight, 0]); const x = d3.scaleBand() .domain(data.map(item => item.Period)) .range([0, 500]) .paddingInner(0.2) .paddingOuter(0.2); const rects = graph.selectAll(‘rect’) .data(data); rects.attr(‘width’, x.bandwidth) .attr(‘class’, ‘bar-rect’) .attr(‘height’, d => graphHeight — y(d.Amount)) .attr(‘x’, d => x(d.Period)) .attr(‘y’, d => y(d.Amount)); rects.enter() .append(‘rect’) .attr(‘class’, ‘bar-rect’) .attr(‘width’, x.bandwidth) .attr(‘height’, d => graphHeight — y(d.Amount)) .attr(‘x’, d => x(d.Period)) .attr(‘y’, d => y(d.Amount)); const xAxis = d3.axisBottom(x); const yAxis = d3.axisLeft(y) .ticks(5) .tickFormat(d => `USD ${d / 1000}K`); gXAxis.call(xAxis); gYAxis.call(yAxis); gXAxis.selectAll(‘text’) .style(‘font-size’, 14); gYAxis.selectAll(‘text’) .style(‘font-size’, 14);}); If you were to refresh the HTML page now, you would see a chart presented on it. Not only that, but we’ve also added different color on bar hover. Nice! That’s it for today. Let’s wrap things up in the next section. D3.js requires a lot of code — no arguing there. But that’s just what makes it so special — the ability to customize absolutely everything. We’ve only scratched the surface here, and options to tweak are endless. Let me know if you’ve enjoyed this piece, as I intend to do an entire series on the library. Thanks for reading. Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.
[ { "code": null, "e": 492, "s": 172, "text": "Choosing a go-to data visualization library is harder than it seems at first. There are so many to choose from, especially if you factor in different languages. I’ve spent most of my time with Plotly and Matplotlib in Python, but today we’ll try something...
Explain the removal of useless symbols
All grammars are not always optimized, which means the grammar may consist of some extra symbols (non-terminals) which increase the length of grammar. So, we have to reduce the grammar by removing such useless symbols. The properties to reduce grammar are explained below − Each non-terminal and terminal of G appears in the derivation of some word in L There should not be any production as X->Y where X and Y are non-terminals. If epsilon is not in language L then, there need not be in the production X-> ε. The use of reducing grammar is as follows − A symbol X is useful if there is a derivation of the form S=>* aXb =* w Otherwise, the symbol X is useless. Note that in a derivation, finally, we should get a string of terminals and all these symbols must be reachable from the start symbol S. Those symbols and productions which are not at all used in the derivation are useless. Consider the following example for removing symbol S->aAa|bBb| ε A->C|a B->C|b C->CDE| ε D->A|B|ab The useless symbols from the given grammar is E. Because E is not a derivative on the right hand side (RHS). After removing the useless symbol, the production is as follows S->aDa|bDb D->a|b|ab
[ { "code": null, "e": 1213, "s": 1062, "text": "All grammars are not always optimized, which means the grammar may consist of some extra symbols (non-terminals) which increase the length of grammar." }, { "code": null, "e": 1281, "s": 1213, "text": "So, we have to reduce the gramm...
Exception header in C++ with examples - GeeksforGeeks
16 Jul, 2020 C++ provides a list of standard exceptions defined in header <exception> in namespace std where “exception” is the base class for all standard exceptions. All exceptions like bad_alloc, bad_cast, runtime_error, etc generated by the standard library inherit from std::exception. Therefore, all standard exceptions can be caught by reference. Header File: #include <exception> Below are the errors are thrown in C++: Below is the program to illustrate some of the errors in exception class in C++: Program 1:Below is the illustration of std::bad_alloc error: using class bad_alloc using class exception // C++ program to illustrate bad_alloc// using class bad_alloc#include <exception>#include <iostream>using namespace std; // Function to illustrate bad_allocvoid createArray(int N){ // Try Block try { // Create an array of length N int* array = new int[N]; // If created successfully then // print the message cout << "Array created successfully" << " of length " << N << " \n"; } // Check if the memory // was allocated or not // using class bad_alloc catch (bad_alloc& e) { // If not, print the error message cout << e.what() << " for array of length " << N << " \n"; }} // Driver Codeint main(){ // Function call to create an // array of 1000 size createArray(1000); // Function call to create an // array of 1000000000 size createArray(1000000000); return 0;} // C++ program to illustrate bad_alloc// using class exception#include <exception>#include <iostream>using namespace std; // Function to illustrate bad_allocvoid createArray(int N){ // Try Block try { // Create an array of length N int* array = new int[N]; // If created successfully then // print the message cout << "Array created successfully" << " of length " << N << " \n"; } // Check if the memory // was allocated or not // using class exception catch (exception& e) { // If not, print the error message cout << e.what() << " for array of length " << N << " \n"; }} // Driver Codeint main(){ // Function call to create an // array of 1000 size createArray(1000); // Function call to create an // array of 1000000000 size createArray(1000000000); return 0;} Array created successfully of length 1000 std::bad_alloc for array of length 1000000000 Explanation: For creating an array of length 1000 the memory allocation was successful and there was no exception thrown for the same. For creating an array of length 1000 the memory allocation was not successful and the exception “std::bad_alloc” was thrown. The exception thrown is of type bad_alloc which is derived from the class exception. The function what() is a virtual function defined in the base class exception. The function what() returns a null terminated string which is generally a description of error. Note: bad_alloc exception is thrown by operator “new” when memory allocation fails. Why did we catch an exception by reference?Catching an exception by value will call the copy constructor and create a copy of the exception which adds run-time overhead. Thus, catching by reference is a better option. If we want to modify exception or add some additional information to the error message then catching by reference is best for it. For this case: catch (std::string str){ s += "Additional info"; throw;} The above program wants to catch the exception, add some information to it and re-throw it. But str is a call by value variable which gets changed locally in the function and when the function re-throw the exception then the original exception is passed. Correct Code: catch (std::string& s){ s += "Additional info"; throw;} Program 2:Below is the program to illustrate the logic_error: // C++ program to illustrate logic_error#include <exception>#include <iostream>using namespace std; // Function to find factorial of N and// throws error if occursvoid findFactorial(int N){ // Initialise variable by 1 int factorial = 1; // Check for errors try { // If N is less than zero then, // it shows errors as factorial // of negative number can't be // calculated if (N < 0) { // Exception object which // returns the message passed // to it throw invalid_argument( "negative not allowed"); } // Find factorial if no error occurs for (int i = N; i > 0; i--) { factorial *= i; } cout << "Factorial of " << N << " is " << factorial << endl; } // Print the error message catch (exception& e) { cout << e.what(); }} // Driver Codeint main(){ // Function call to find factorial // of 0 findFactorial(0); // Function call to find factorial // of 3 findFactorial(3); // Function call to find factorial // of -1 findFactorial(-1); return 0;} Factorial of 0 is 1 Factorial of 3 is 6 negative not allowed nidhi_biet C++-Exception Handling cpp-exception C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Iterators in C++ STL Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Inline Functions in C++ 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": 23731, "s": 23703, "text": "\n16 Jul, 2020" }, { "code": null, "e": 24072, "s": 23731, "text": "C++ provides a list of standard exceptions defined in header <exception> in namespace std where “exception” is the base class for all standard exceptions. All exce...
How to use Tickers in Golang?
There are often cases where we would want to perform a particular task after a specific interval of time repeatedly. In Golang, we achieve this with the help of tickers. We can use them with goroutines as well so that we can run these tasks in the background of our application without breaking the flow of the application. The function that we use in tickers is the NewTicker() function which takes time as an argument and we can supply seconds and even milliseconds in it. The following example demonstrates how we can use a ticker in Golang. Consider the code shown below. package main import ( "fmt" "time" ) func main() { fmt.Println("Starting the ticker") ticker := time.NewTicker(1 * time.Second) for _ = range ticker.C { fmt.Println("Ticking..") } } If we run the above code with the command go run main.go then we will get the following output. Starting the ticker Ticking.. Ticking.. It should be noted that the above program will keep on executing unless we forcefully stop it. We can stop it with CTRL+C. We can also run the ticker in the background with the help of goroutines. Consider the code shown below. package main import ( "fmt" "time" ) func inBackground() { ticker := time.NewTicker(1 * time.Second) for _ = range ticker.C { fmt.Println("Ticking..") } } func main() { fmt.Println("Starting the ticker") go inBackground() fmt.Println("After goroutine..") select {} } If we run the above code with the command go run main.go then we will get the following output. Starting the ticker After goroutine.. Ticking.. Ticking.. It should be noted that the above program will keep on executing unless we forcefully stop it. We can stop it with CTRL+C. Now let's consider a more advanced use-case of the ticker, in which we will make use of a channel and a select statement and the ticker will run for a defined period of time as well. Consider the code shown below. package main import ( "fmt" "time" ) func main() { ticker := time.NewTicker(400 * time.Millisecond) done := make(chan bool) fmt.Println("Started!") go func() { for { select { case <-done: return case t := <-ticker.C: fmt.Println("Tick at", t) } } }() time.Sleep(1600 * time.Millisecond) ticker.Stop() done <- true fmt.Println("Stopped!") } If we run the above code with the command go run main.go then we will get the following output. Started! Tick at 2009-11-10 23:00:00.4 +0000 UTC m=+0.400000001 Tick at 2009-11-10 23:00:00.8 +0000 UTC m=+0.800000001 Tick at 2009-11-10 23:00:01.2 +0000 UTC m=+1.200000001 Tick at 2009-11-10 23:00:01.6 +0000 UTC m=+1.600000001 Stopped!
[ { "code": null, "e": 1232, "s": 1062, "text": "There are often cases where we would want to perform a particular task after a specific interval of time repeatedly. In Golang, we achieve this with the help of tickers." }, { "code": null, "e": 1386, "s": 1232, "text": "We can use t...
How to cartesian product of 2 arrays using JavaScript ? - GeeksforGeeks
11 Oct, 2019 The task is to compute the cartesian product of 2 JavaScript arrays with the help of JavaScript. Here are few techniques discussed.Approach 1: Create a new array. Traverse the first array by outer loop and second array by inner loop. In the inner loop, Concatenate the first array element with the second array element and push it in a new array. Example 1: This example uses the approach as discussed above. <!DOCTYPE HTML><html> <head> <title> cartesian product of 2 arrays using JavaScript </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;" id="h1"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var arr1 = [ [13, 'G'], [16, 'C'] ]; var arr2 = [ [8, 'F'], [36, 'P'] ]; up.innerHTML = "Click on the button to compute the "+ "Cartesian Product of 2 arrays.<br>Array1-"; var res = ""; for (var i = 0; i < arr1.length; i++) { res = res + "[" + arr1[i] + "]"; } up.innerHTML = up.innerHTML + res + "<br>Array2-"; res = ""; for (var i = 0; i < arr2.length; i++) { res = res + "[" + arr2[i] + "]"; } up.innerHTML = up.innerHTML + res; function GFG_Fun() { var ans = []; for (var i = 0; i < arr1.length; i++) { for (var l = 0; l < arr2.length; l++) { ans.push(arr1[i].concat(arr2[l])); } } res = ""; for (var i = 0; i < ans.length; i++) { res = res + "[" + ans[i] + "]<br>"; } down.innerHTML = res; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Approach 2: Create a new array. The same approach is followed here, for every element of first array, every element of second array is concatenated and pushed to the new array with the help of .apply() and .map() method. Example 2: This example uses the approach as discussed above. <!DOCTYPE HTML><html> <head> <title> cartesian product of 2 arrays using JavaScript </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;" id="h1"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var arr1 = [ [13, 'G'], [16, 'C'] ]; var arr2 = [ [8, 'F'], [36, 'P'] ]; up.innerHTML = "Click on the button to compute"+ " the Cartesian Product of 2 arrays.<br>Array1-"; var res = ""; for (var i = 0; i < arr1.length; i++) { res = res + "[" + arr1[i] + "]"; } up.innerHTML = up.innerHTML + res + "<br>Array2-"; res = ""; for (var i = 0; i < arr2.length; i++) { res = res + "[" + arr2[i] + "]"; } up.innerHTML = up.innerHTML + res; function GFG_Fun() { var ans = [].concat.apply([], arr1.map( arr1 => (arr2.map(arr2 => arr1.concat(arr2))))); res = ""; for (var i = 0; i < ans.length; i++) { res = res + "[" + ans[i] + "]<br>"; } down.innerHTML = res; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript-Misc JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26597, "s": 26569, "text": "\n11 Oct, 2019" }, { "code": null, "e": 26740, "s": 26597, "text": "The task is to compute the cartesian product of 2 JavaScript arrays with the help of JavaScript. Here are few techniques discussed.Approach 1:" }, { "code"...
Octal Number System
Octal Number System is one the type of Number Representation techniques, in which there value of base is 8. That means there are only 8 symbols or possible digit values, there are 0, 1, 2, 3, 4, 5, 6, 7. It requires only 3 bits to represent value of any digit. Octal numbers are indicated by the addition of either an 0o prefix or an 8 suffix. Position of every digit has a weight which is a power of 8. Each position in the Octal system is 8 times more significant than the previous position, that means numeric value of an octal number is determined by multiplying each digit of the number by the value of the position in which the digit appears and then adding the products. So, it is also a positional (or weighted) number system. Each Octal number can be represented using only 3 bits, with each group of bits having a distich values between 000 (for 0) and 111 (for 7 = 4+2+1). The equivalent binary number of Octal number are as given below − Octal number system is similar to Hexadecimal number system. Octal number system provides convenient way of converting large binary numbers into more compact and smaller groups, however this octal number system is less popular. Since base value of Octal number system is 8, so there maximum value of digit is 7 and it can not be more than 7. In this number system, the successive positions to the left of the octal point having weights of 80, 81, 82, 83 and so on. Similarly, the successive positions to the right of the octal point having weights of 8-1, 8-2, 8-3and so on. This is called base power of 8. The decimal value of any octal number can be determined using sum of product of each digit with its positional value. Example-1 − The number 111 is interpreted as 111 = 1x82+5x81+7x80 = 157 Here, right most bit 7 is the least significant bit (LSB) and left most bit 1 is the most significant bit (MSB). Example-2 − The number 65.125 is interpreted as 65.125 =1x82+0x81+1x80+1x8-1=101.10 Here, right most bit 0 is the least significant bit (LSB) and left most bit 1 is the most significant bit (MSB). Example-3 − A decimal number 21 to represent in Octal representation (21)10=2x81+5x80=(25)8 So, decimal value 21 is equivalent to 25 in Octal Number System. The octal numbers are not as common as they used to be. However, Octal is used when the number of bits in one word is a multiple of 3. It is also used as a shorthand for representing file permissions on UNIX systems and representation of UTF8 numbers, etc. The main advantage of using Octal numbers is that it uses less digits than decimal and Hexadecimal number system. So, it has fewer computations and less computational errors. It uses only 3 bits to represent any digit in binary and easy to convert from octal to binary and vice-versa. It is easier to handle input and output in the octal form. The major disadvantage of Octal number system is that computer does not understand octal number system directly, so we need octal to binary converter. Simply, 7’s complement of a octal number is the subtraction of it’s each digits from 7. For example, 7’s complement of octal number 127 is 777 - 127 = 650. 8’s complement of octal number is 7’s complement of given number plus 1 to the least significant bit (LSB). For example 8’s complement of octal number 320 is (777 - 320) + 1 = 457 + 1 = 460. Please note that maximum digit of octal number system is 7, so addition of 7+1 will be 0 with carry 1.
[ { "code": null, "e": 1406, "s": 1062, "text": "Octal Number System is one the type of Number Representation techniques, in which there value of base is 8. That means there are only 8 symbols or possible digit values, there are 0, 1, 2, 3, 4, 5, 6, 7. It requires only 3 bits to represent value of any...
Find the perimeter of a cylinder - GeeksforGeeks
24 Nov, 2021 Given diameter and height, find the perimeter of a cylinder.Perimeter is the length of the outline of a two – dimensional shape. A cylinder is a three – dimensional shape. So, technically we cannot find the perimeter of a cylinder but we can find the perimeter of the cross-section of the cylinder. This can be done by creating the projection on its base, thus, creating the projection on its side, then the shape would be reduced to a rectangle. Formula : Perimeter of cylinder ( P ) = here d is the diameter of the cylinder h is the height of the cylinderExamples : Input : diameter = 5, height = 10 Output : Perimeter = 30 Input : diameter = 50, height = 150 Output : Perimeter = 400 C++ Java Python C# PHP Javascript // CPP program to find // perimeter of cylinder#include <iostream>using namespace std; // Function to calculate perimeterint perimeter(int diameter, int height){ return 2 * (diameter + height);} // Driver functionint main(){ int diameter = 5; int height = 10; cout << "Perimeter = "; cout<< perimeter(diameter, height); cout<<" units\n"; return 0;} // Java program to find // perimeter of cylinderimport java.io.*; class GFG { // Function to calculate perimeter static int perimeter(int diameter, int height) { return 2 * (diameter + height); } /* Driver program to test above function */ public static void main(String[] args) { int diameter = 5; int height = 10; System.out.println("Perimeter = " + perimeter(diameter, height) + " units\n"); }} // This code is contributed by Gitanjali. # Function to calculate # the perimeter of a cylinderdef perimeter( diameter, height ) : return 2 * ( diameter + height ) # Driver functiondiameter = 5 ;height = 10 ;print ("Perimeter = ", perimeter(diameter, height)) // C# program to find perimeter of cylinderusing System; class GFG { // Function to calculate perimeter static int perimeter(int diameter, int height) { return 2 * (diameter + height); } /* Driver program to test above function */ public static void Main(String[] args) { int diameter = 5; int height = 10; Console.Write("Perimeter = " + perimeter(diameter, height) + " units\n"); }} // This code is contributed by parashar... <?php// PHP program to find // perimeter of cylinder // Function to calculate perimeterfunction perimeter($diameter, $height){ return 2 * ($diameter + $height);} // Driver Code $diameter = 5; $height = 10; echo("Perimeter = "); echo(perimeter($diameter, $height)); echo(" units"); // This code is contributed by vt_m.?> <script> // javascript program to find // perimeter of cylinder // Function to calculate perimeter function perimeter(diameter, height) { return 2 * (diameter + height); } // Driver Function let diameter = 5; let height = 10; document.write("Perimeter = " + perimeter(diameter, height) + " units\n"); // This code is contributed by susmitakundugoaldanga.</script> Output : Perimeter = 30 units parashar vt_m susmitakundugoaldanga area-volume-programs Geometric Mathematical School Programming Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Convex Hull | Set 2 (Graham Scan) Check whether a given point lies inside a triangle or not Convex Hull using Divide and Conquer Algorithm Program for Fibonacci numbers C++ Data Types Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26407, "s": 26379, "text": "\n24 Nov, 2021" }, { "code": null, "e": 26855, "s": 26407, "text": "Given diameter and height, find the perimeter of a cylinder.Perimeter is the length of the outline of a two – dimensional shape. A cylinder is a three – dimensiona...
Hopfield Neural Network - GeeksforGeeks
07 Jul, 2021 Prerequisites: RNN The Hopfield Neural Networks, invented by Dr John J. Hopfield consists of one layer of ‘n’ fully connected recurrent neurons. It is generally used in performing auto association and optimization tasks. It is calculated using a converging interactive process and it generates a different response than our normal neural nets. Discrete Hopfield Network: It is a fully interconnected neural network where each unit is connected to every other unit. It behaves in a discrete manner, i.e. it gives finite distinct output, generally of two types: Binary (0/1) Bipolar (-1/1) The weights associated with this network is symmetric in nature and has the following properties. Structure & Architecture Each neuron has an inverting and a non-inverting output. Being fully connected, the output of each neuron is an input to all other neurons but not self. Fig 1 shows a sample representation of a Discrete Hopfield Neural Network architecture having the following elements. Fig 1: Discrete Hopfield Network Architecture [ x1 , x2 , ... , xn ] -> Input to the n given neurons. [ y1 , y2 , ... , yn ] -> Output obtained from the n given neurons Wij -> weight associated with the connection between the ith and the jth neuron. Training Algorithm For storing a set of input patterns S(p) [p = 1 to P], where S(p) = S1(p) ... Si(p) ... Sn(p), the weight matrix is given by: For binary patterns For bipolar patterns (i.e. weights here have no self connection) Steps Involved Step 1 - Initialize weights (wij) to store patterns (using training algorithm). Step 2 - For each input vector yi, perform steps 3-7. Step 3 - Make initial activators of the network equal to the external input vector x. Step 4 - For each vector yi, perform steps 5-7. Step 5 - Calculate the total input of the network yin using the equation given below. Step 6 - Apply activation over the total input to calculate the output as per the equation given below: (where θi (threshold) and is normally taken as 0) Step 7 - Now feedback the obtained output yi to all other units. Thus, the activation vectors are updated. Step 8 - Test the network for convergence. Example Problem Consider the following problem. We are required to create Discrete Hopfield Network with bipolar representation of input vector as [1 1 1 -1] or [1 1 1 0] (in case of binary representation) is stored in the network. Test the hopfield network with missing entries in the first and second component of the stored vector (i.e. [0 0 1 0]). Step by Step Solution Step 1 - given input vector, x = [1 1 1 -1] (bipolar) and we initialize the weight matrix (wij) as: and weight matrix with no self connection is: Step 3 - As per the question, input vector x with missing entries, x = [0 0 1 0] ([x1 x2 x3 x4]) (binary) - Make yi = x = [0 0 1 0] ([y1 y2 y3 y4]) Step 4 - Choosing unit yi (order doesn't matter) for updating its activation. - Take the ith column of the weight matrix for calculation. (we will do the next steps for all values of yi and check if there is convergence or not) ‘ now for next unit, we will take updated value via feedback. (i.e. y = [1 0 1 0]) now for next unit, we will take updated value via feedback. (i.e. y = [1 0 1 0]) now for next unit, we will take updated value via feedback. (i.e. y = [1 0 1 0]) Continuous Hopfield Network: Unlike the discrete hopfield networks, here the time parameter is treated as a continuous variable. So, instead of getting binary/bipolar outputs, we can obtain values that lie between 0 and 1. It can be used to solve constrained optimization and associative memory problems. The output is defined as: where, vi = output from the continuous hopfield network ui = internal activity of a node in continuous hopfield network. Energy Function The hopfield networks have an energy function associated with them. It either diminishes or remains unchanged on update (feedback) after every iteration. The energy function for a continuous hopfield network is defined as: To determine if the network will converge to a stable configuration, we see if the energy function reaches its minimum by: The network is bound to converge if the activity of each neuron wrt time is given by the following differential equation: rajeev0719singh Neural Network Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Support Vector Machine Algorithm Intuition of Adam Optimizer Introduction to Recurrent Neural Network Singular Value Decomposition (SVD) CNN | Introduction to Pooling Layer k-nearest neighbor algorithm in Python Python | Decision Tree Regression using sklearn DBSCAN Clustering in ML | Density based clustering Bagging vs Boosting in Machine Learning Python | Stemming words with NLTK
[ { "code": null, "e": 24468, "s": 24440, "text": "\n07 Jul, 2021" }, { "code": null, "e": 24487, "s": 24468, "text": "Prerequisites: RNN" }, { "code": null, "e": 24813, "s": 24487, "text": "The Hopfield Neural Networks, invented by Dr John J. Hopfield consists ...
Create a Sorted Array Using Binary Search - GeeksforGeeks
16 Jun, 2021 Given an array, the task is to create a new sorted array in ascending order from the elements of the given array.Examples: Input : arr[] = {2, 5, 4, 9, 8} Output : 2 4 5 8 9 Input : arr[] = {10, 45, 98, 35, 45} Output : 10 35 45 45 98 The above problem can be solved efficiently using Binary Search. We create a new array and insert the first element if it’s empty. Now for every new element, we find the correct position for the element in the new array using binary search and then insert that element at the corresponding index in the new array.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to create a sorted array// using Binary Search #include <bits/stdc++.h>using namespace std; // Function to create a new sorted array// using Binary Searchvoid createSorted(int a[], int n){ // Auxiliary Array vector<int> b; for (int j = 0; j < n; j++) { // if b is empty any element can be at // first place if (b.empty()) b.push_back(a[j]); else { // Perform Binary Search to find the correct // position of current element in the // new array int start = 0, end = b.size() - 1; // let the element should be at first index int pos = 0; while (start <= end) { int mid = start + (end - start) / 2; // if a[j] is already present in the new array if (b[mid] == a[j]) { // add a[j] at mid+1. you can add it at mid b.emplace(b.begin() + max(0, mid + 1), a[j]); break; } // if a[j] is lesser than b[mid] go right side else if (b[mid] > a[j]) // means pos should be between start and mid-1 pos = end = mid - 1; else // else pos should be between mid+1 and end pos = start = mid + 1; // if a[j] is the largest push it at last if (start > end) { pos = start; b.emplace(b.begin() + max(0, pos), a[j]); // here max(0, pos) is used because sometimes // pos can be negative as smallest duplicates // can be present in the array break; } } } } // Print the new generated sorted array for (int i = 0; i < n; i++) cout << b[i] << " ";} // Driver Codeint main(){ int a[] = { 2, 5, 4, 9, 8 }; int n = sizeof(a) / sizeof(a[0]); createSorted(a, n); return 0;} // Java program to create a sorted array// using Binary Searchimport java.util.*; class GFG{ // Function to create a new sorted array// using Binary Searchstatic void createSorted(int a[], int n){ // Auxiliary Array Vector<Integer> b = new Vector<>(); for (int j = 0; j < n; j++) { // if b is empty any element can be at // first place if (b.isEmpty()) b.add(a[j]); else { // Perform Binary Search to find the correct // position of current element in the // new array int start = 0, end = b.size() - 1; // let the element should be at first index int pos = 0; while (start <= end) { int mid = start + (end - start) / 2; // if a[j] is already present in the new array if (b.get(mid) == a[j]) { // add a[j] at mid+1. you can add it at mid b.add((Math.max(0, mid + 1)), a[j]); break; } // if a[j] is lesser than b[mid] go right side else if (b.get(mid) > a[j]) // means pos should be between start and mid-1 pos = end = mid - 1; else // else pos should be between mid+1 and end pos = start = mid + 1; // if a[j] is the largest push it at last if (start > end) { pos = start; b.add(Math.max(0, pos), a[j]); // here max(0, pos) is used because sometimes // pos can be negative as smallest duplicates // can be present in the array break; } } } } // Print the new generated sorted array for (int i = 0; i < n; i++) System.out.print(b.get(i) + " ");} // Driver Codepublic static void main(String args[]){ int a[] = { 2, 5, 4, 9, 8 }; int n = a.length; createSorted(a, n);}} /* This code is contributed by PrinciRaj1992 */ # Python program to create a sorted array# using Binary Search # Function to create a new sorted array# using Binary Searchdef createSorted(a: list, n: int): # Auxiliary Array b = [] for j in range(n): # if b is empty any element can be at # first place if len(b) == 0: b.append(a[j]) else: # Perform Binary Search to find the correct # position of current element in the # new array start = 0 end = len(b) - 1 # let the element should be at first index pos = 0 while start <= end: mid = start + (end - start) // 2 # if a[j] is already present in the new array if b[mid] == a[j]: # add a[j] at mid+1. you can add it at mid b.insert(max(0, mid + 1), a[j]) break # if a[j] is lesser than b[mid] go right side elif b[mid] > a[j]: # means pos should be between start and mid-1 pos = end = mid - 1 else: # else pos should be between mid+1 and end pos = start = mid + 1 # if a[j] is the largest push it at last if start > end: pos = start b.insert(max(0, pos), a[j]) # here max(0, pos) is used because sometimes # pos can be negative as smallest duplicates # can be present in the array break # Print the new generated sorted array for i in range(n): print(b[i], end=" ") # Driver Codeif __name__ == "__main__": a = [2, 5, 4, 9, 8] n = len(a) createSorted(a, n) # This code is contributed by# sanjeev2552 // C# program to create a sorted array// using Binary Searchusing System;using System.Collections.Generic; class GFG{ // Function to create a new sorted array// using Binary Searchstatic void createSorted(int []a, int n){ // Auxiliary Array List<int> b = new List<int>(); for (int j = 0; j < n; j++) { // if b is empty any element can be at // first place if (b.Count == 0) b.Add(a[j]); else { // Perform Binary Search to find the correct // position of current element in the // new array int start = 0, end = b.Count - 1; // let the element should be at first index int pos = 0; while (start <= end) { int mid = start + (end - start) / 2; // if a[j] is already present in the new array if (b[mid] == a[j]) { // add a[j] at mid+1. you can add it at mid b.Insert((Math.Max(0, mid + 1)), a[j]); break; } // if a[j] is lesser than b[mid] go right side else if (b[mid] > a[j]) // means pos should be between start and mid-1 pos = end = mid - 1; else // else pos should be between mid+1 and end pos = start = mid + 1; // if a[j] is the largest push it at last if (start > end) { pos = start; b.Insert(Math.Max(0, pos), a[j]); // here Max(0, pos) is used because sometimes // pos can be negative as smallest duplicates // can be present in the array break; } } } } // Print the new generated sorted array for (int i = 0; i < n; i++) Console.Write(b[i] + " ");} // Driver Codepublic static void Main(String []args){ int []a = { 2, 5, 4, 9, 8 }; int n = a.Length; createSorted(a, n);}} // This code is contributed by 29AjayKumar <script> // JavaScript program to create a sorted array // using Binary Search // Function to create a new sorted array // using Binary Search function createSorted(a, n) { // Auxiliary Array var b = []; for (var j = 0; j < n; j++) { // if b is empty any element can be at // first place if (b.length == 0) b.push(a[j]); else { // Perform Binary Search to find the correct // position of current element in the // new array var start = 0, end = b.length - 1; // let the element should be at first index var pos = 0; while (start <= end) { var mid = start + parseInt((end - start) / 2); // if a[j] is already present in the new array if (b[mid] === a[j]) { // add a[j] at mid+1. you can add it at mid b.insert(Math.max(0, mid + 1), a[j]); break; } // if a[j] is lesser than b[mid] go right side else if (b[mid] > a[j]) // means pos should be between start and mid-1 pos = end = mid - 1; // else pos should be between mid+1 and end else pos = start = mid + 1; // if a[j] is the largest push it at last if (start > end) { pos = start; b.insert(Math.max(0, pos), a[j]); // here Max(0, pos) is used because sometimes // pos can be negative as smallest duplicates // can be present in the array break; } } } } // Print the new generated sorted array for (var i = 0; i < n; i++) document.write(b[i] + " "); } Array.prototype.insert = function (index, item) { this.splice(index, 0, item); }; // Driver Code var a = [2, 5, 4, 9, 8]; var n = a.length; createSorted(a, n); </script> 2 4 5 8 9 Time Complexity: O(N*N). Although binary search is being used, the list insert calls run in O(N) time on averageAuxiliary Space: O(N) princiraj1992 29AjayKumar sanjeev2552 nidhi_biet gqfgtks44jbg1patgpz4bnxsxjvtaml4foqqto9c rdtank Binary Search Arrays Greedy Searching Sorting Arrays Searching Greedy Sorting Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Find duplicates in O(n) time and O(1) extra space | Set 1 Dijkstra's shortest path algorithm | Greedy Algo-7 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Write a program to print all permutations of a given string Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 26177, "s": 26149, "text": "\n16 Jun, 2021" }, { "code": null, "e": 26302, "s": 26177, "text": "Given an array, the task is to create a new sorted array in ascending order from the elements of the given array.Examples: " }, { "code": null, "e": 2...
How to set Echo Char for JPasswordField in Java?
With echo char, you can set a character that would appear whenever a user will type the password in the JPasswordField. Let us first create a new JPassword field − JPasswordField passwd = new JPasswordField(); Now, use the setEchoChar() to set the echo char for password field. Here, we have asterisk (*) as the field for password − passwd.setEchoChar('*'); The following is an example to set echo char for password field − package my; import java.awt.GridLayout; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.SwingConstants; public class SwingDemo { public static void main(String[] args) throws Exception { JFrame frame = new JFrame("Register!"); JLabel label1, label2, label3; frame.setLayout(new GridLayout(2, 2)); label1 = new JLabel("Id", SwingConstants.CENTER); label2 = new JLabel("Age", SwingConstants.CENTER); label3 = new JLabel("Password", SwingConstants.CENTER); JTextField emailId = new JTextField(20); JTextField age = new JTextField(20); JPasswordField passwd = new JPasswordField(); passwd.setEchoChar('*'); frame.add(label1); frame.add(label2); frame.add(label3); frame.add(emailId); frame.add(age); frame.add(passwd); frame.setSize(550,250); frame.setVisible(true); } }
[ { "code": null, "e": 1182, "s": 1062, "text": "With echo char, you can set a character that would appear whenever a user will type the password in the JPasswordField." }, { "code": null, "e": 1226, "s": 1182, "text": "Let us first create a new JPassword field −" }, { "cod...
Minimum peak elements from an array by their repeated removal at every iteration of the array - GeeksforGeeks
19 May, 2021 Given an array arr[] consisting of N distinct positive integers, the task is to repeatedly find the minimum peak element from the given array and remove that element until all the array elements are removed. Peak Element: Any element in the array is know as the peak element based on the following conditions: If arr[i – 1] < arr[i] > arr[i + 1], where 1 < i < N – 1, then arr[i] is the peak element. If arr[0] > arr[1], then arr[0] is the peak element, where N is the size of the array. If arr[N – 2] < arr[N – 1], then arr[N – 1] is the peak element, where N is the size of the array. If more than one peak element exists in the array, then the minimum value among them needs to be printed. Examples: Input: arr[] = {1, 9, 7, 8, 2, 6}Output: [6, 8, 9, 7, 2, 1]Explanation: First min peak = 6, as 2 < 6.The array after removing min peak will be [1, 9, 7, 8, 2]. Second min peak = 8, as 7 < 8 > 2.The array after removing min peak will be [1, 9, 7, 2]Third min peak = 9, as 1 < 9 > 7.The array after removing min peak will be [1, 7, 2]Fourth min peak = 7, as 1 < 7 > 2.The array after removing min peak will be [1, 2]Fifth min peak = 2, as 1 < 2.The array after removing min peak will be [1]Sixth min peak = 1.Therefore, the list of minimum peak is [6, 8, 9, 7, 2, 1]. Input: arr []= {1, 5, 3, 7, 2}Output: [5, 7, 3, 2, 1]Explanation:First min peak = 5, as 1 < 5 > 3.The array after removing min peak will be [1, 3, 7, 2] Second min peak = 7, as 3 < 7 > 2.The array after removing min peak will be [1, 3, 2]Third min peak = 3, as 1 < 3 > 2.The array after removing min peak will be [1, 2]Fourth min peak = 2, as 1 < 2.The array after removing min peak will be [1]Fifth min peak = 1.Therefore, the list of minimum peak is [5, 7, 3, 2, 1] Approach: The idea is to find the minimum peak element of the array by iterating over the array using two nested loops, where the outer loop points to the current element and the inner loop execute to find the index of min peak element, remove that peak element from the array and store the current peak element in the resultant list. After completing the above steps, print all the minimum peak elements stored in the list. 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 return the list of// minimum peak elementsvoid minPeaks(vector<int>list){ // Length of original list int n = list.size(); // Initialize resultant list vector<int>result; // Traverse each element of list for(int i = 0; i < n; i++) { int min = INT_MAX; int index = -1; // Length of original list after // removing the peak element int size = list.size(); // Traverse new list after removal // of previous min peak element for(int j = 0; j < size; j++) { // Update min and index, // if first element of // list > next element if (j == 0 && j + 1 < size) { if (list[j] > list[j + 1] && min > list[j]) { min = list[j]; index = j; } } else if (j == size - 1 && j - 1 >= 0) { // Update min and index, // if last element of // list > previous one if (list[j] > list[j - 1] && min > list[j]) { min = list[j]; index = j; } } // Update min and index, if // list has single element else if (size == 1) { min = list[j]; index = j; } // Update min and index, // if current element > // adjacent elements else if (list[j] > list[j - 1] && list[j] > list[j + 1] && min > list[j]) { min = list[j]; index = j; } } // Remove current min peak // element from list list.erase(list.begin() + index); // Insert min peak into // resultant list result.push_back(min); } // Print resultant list cout << "["; for(int i = 0; i < result.size(); i++) { cout << result[i] << ", "; } cout << "]";} // Driver Codeint main(){ // Given array arr[] vector<int> arr = { 1, 9, 7, 8, 2, 6 }; // Function call minPeaks(arr);} // This code is contributed by bikram2001jha // Java program for the above approach import java.util.*;import java.lang.*; class GFG { // Function to return the list of // minimum peak elements static void minPeaks(ArrayList<Integer> list) { // Length of original list int n = list.size(); // Initialize resultant list ArrayList<Integer> result = new ArrayList<>(); // Traverse each element of list for (int i = 0; i < n; i++) { int min = Integer.MAX_VALUE; int index = -1; // Length of original list after // removing the peak element int size = list.size(); // Traverse new list after removal // of previous min peak element for (int j = 0; j < size; j++) { // Update min and index, // if first element of // list > next element if (j == 0 && j + 1 < size) { if (list.get(j) > list.get(j + 1) && min > list.get(j)) { min = list.get(j); index = j; } } else if (j == size - 1 && j - 1 >= 0) { // Update min and index, // if last element of // list > previous one if (list.get(j) > list.get(j - 1) && min > list.get(j)) { min = list.get(j); index = j; } } // Update min and index, if // list has single element else if (size == 1) { min = list.get(j); index = j; } // Update min and index, // if current element > // adjacent elements else if (list.get(j) > list.get(j - 1) && list.get(j) > list.get(j + 1) && min > list.get(j)) { min = list.get(j); index = j; } } // Remove current min peak // element from list list.remove(index); // Insert min peak into // resultant list result.add(min); } // Print resultant list System.out.println(result); } // Driver Code public static void main(String[] args) { // Given array arr[] ArrayList<Integer> arr = new ArrayList<>( Arrays.asList(1, 9, 7, 8, 2, 6)); // Function Call minPeaks(arr); }} # Python3 program for# the above approachimport sys # Function to return the list of# minimum peak elementsdef minPeaks(list1): # Length of original list n = len(list1) # Initialize resultant list result = [] # Traverse each element of list for i in range (n): min = sys.maxsize index = -1 # Length of original list # after removing the peak # element size = len(list1) # Traverse new list after removal # of previous min peak element for j in range (size): # Update min and index, # if first element of # list > next element if (j == 0 and j + 1 < size): if (list1[j] > list1[j + 1] and min > list1[j]): min = list1[j]; index = j; elif (j == size - 1 and j - 1 >= 0): # Update min and index, # if last element of # list > previous one if (list1[j] > list1[j - 1] and min > list1[j]): min = list1[j] index = j # Update min and index, if # list has single element elif (size == 1): min = list1[j] index = j # Update min and index, # if current element > # adjacent elements elif (list1[j] > list1[j - 1] and list1[j] > list1[j + 1] and min > list1[j]): min = list1[j] index = j # Remove current min peak # element from list list1.pop(index) # Insert min peak into # resultant list result.append(min) # Print resultant list print (result) # Driver Codeif __name__ == "__main__": # Given array arr[] arr = [1, 9, 7, 8, 2, 6] # Function call minPeaks(arr) # This code is contributed by Chitranayal // C# program for// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to return the list of// minimum peak elementsstatic void minPeaks(List<int> list){ // Length of original list int n = list.Count; // Initialize resultant list List<int> result = new List<int>(); // Traverse each element of list for (int i = 0; i < n; i++) { int min = int.MaxValue; int index = -1; // Length of original list after // removing the peak element int size = list.Count; // Traverse new list after removal // of previous min peak element for (int j = 0; j < size; j++) { // Update min and index, // if first element of // list > next element if (j == 0 && j + 1 < size) { if (list[j] > list[j + 1] && min > list[j]) { min = list[j]; index = j; } } else if (j == size - 1 && j - 1 >= 0) { // Update min and index, // if last element of // list > previous one if (list[j] > list[j - 1] && min > list[j]) { min = list[j]; index = j; } } // Update min and index, if // list has single element else if (size == 1) { min = list[j]; index = j; } // Update min and index, // if current element > // adjacent elements else if (list[j] > list[j - 1] && list[j] > list[j + 1] && min > list[j]) { min = list[j]; index = j; } } // Remove current min peak // element from list list.RemoveAt(index); // Insert min peak into // resultant list result.Add(min); } // Print resultant list for (int i = 0; i < result.Count; i++) Console.Write(result[i] +", ");} // Driver Codepublic static void Main(String[] args){ // Given array []arr List<int> arr = new List<int>{1, 9, 7, 8, 2, 6}; // Function Call minPeaks(arr);}} // This code is contributed by 29AjayKumar <script> // Javascript program for the above approach // Function to return the list of// minimum peak elementsfunction minPeaks(list){ // Length of original list var n = list.length; // Initialize resultant list var result = []; // Traverse each element of list for(var i = 0; i < n; i++) { var min = 1000000000; var index = -1; // Length of original list after // removing the peak element var size = list.length; // Traverse new list after removal // of previous min peak element for(var j = 0; j < size; j++) { // Update min and index, // if first element of // list > next element if (j == 0 && j + 1 < size) { if (list[j] > list[j + 1] && min > list[j]) { min = list[j]; index = j; } } else if (j == size - 1 && j - 1 >= 0) { // Update min and index, // if last element of // list > previous one if (list[j] > list[j - 1] && min > list[j]) { min = list[j]; index = j; } } // Update min and index, if // list has single element else if (size == 1) { min = list[j]; index = j; } // Update min and index, // if current element > // adjacent elements else if (list[j] > list[j - 1] && list[j] > list[j + 1] && min > list[j]) { min = list[j]; index = j; } } // Remove current min peak // element from list list.splice(index, 1); // Insert min peak into // resultant list result.push(min); } // Print resultant list document.write( "["); for(var i = 0; i < result.length; i++) { document.write( result[i] + ", "); } document.write( "]");} // Driver Code// Given array arr[]var arr = [1, 9, 7, 8, 2, 6]; // Function callminPeaks(arr); // This code is contributed by itsok.</script> [6, 8, 9, 7, 2, 1] Time Complexity: O(N2)Auxiliary Space: O(N) bikram2001jha 29AjayKumar ukasp surinderdawra388 itsok array-rearrange Arrays Greedy Searching Arrays Searching Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Huffman Coding | Greedy Algo-3 Write a program to print all permutations of a given string
[ { "code": null, "e": 25188, "s": 25160, "text": "\n19 May, 2021" }, { "code": null, "e": 25396, "s": 25188, "text": "Given an array arr[] consisting of N distinct positive integers, the task is to repeatedly find the minimum peak element from the given array and remove that eleme...
How to create the ArrayList in C# - GeeksforGeeks
18 Feb, 2019 ArrayList() constructor is used to initialize a new instance of the ArrayList class which will be empty and will have the default initial capacity. ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. Syntax: public ArrayList (); Important Points: The number of elements that an ArrayList can hold is known as the Capacity of the ArrayList. If the elements will be added to the ArrayList then capacity will be automatically increased by reallocating the internal array. Specifying the initial capacity will eliminate the requirement to perform a number of resizing operations while adding elements to the ArrayList if the size of the collection can be estimated. This constructor is an O(1) operation. Example 1: // C# Program to illustrate how// to create a ArrayListusing System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // arrlist is the ArrayList object // ArrayList() is the constructor // used to initializes a new // instance of the ArrayList class ArrayList arrlist = new ArrayList(); // Count property is used to get the // number of elements in ArrayList // It will give 0 as no elements // are present currently Console.WriteLine(arrlist.Count); }} 0 Example 2: // C# Program to illustrate how// to create a ArrayListusing System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // arrlist is the ArrayList object // ArrayList() is the constructor // used to initializes a new // instance of the ArrayList class ArrayList arrlist = new ArrayList(); Console.Write("Before Add Method: "); // Count property is used to get the // number of elements in ArrayList // It will give 0 as no elements // are present currently Console.WriteLine(arrlist.Count); // Adding the elements // to the ArrayList arrlist.Add("This"); arrlist.Add("is"); arrlist.Add("C#"); arrlist.Add("ArrayList"); Console.Write("After Add Method: "); // Count property is used to get the // number of elements in arrlist Console.WriteLine(arrlist.Count); }} Before Add Method: 0 After Add Method: 4 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.-ctor?view=netframework-4.7.2#System_Collections_ArrayList__ctor CSharp-Collections-ArrayList CSharp-Collections-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Method Overriding C# | Abstract Classes Extension Method in C# Difference between Ref and Out keywords in C# C# | Replace() Method C# | Class and Object C# | Constructors C# | String.IndexOf( ) Method | Set - 1
[ { "code": null, "e": 25480, "s": 25452, "text": "\n18 Feb, 2019" }, { "code": null, "e": 25853, "s": 25480, "text": "ArrayList() constructor is used to initialize a new instance of the ArrayList class which will be empty and will have the default initial capacity. ArrayList repre...
How to Share Text of Your App with Another App and Vice Versa in Android? - GeeksforGeeks
29 Apr, 2021 Most of the time while using an app we want to share text from the app to another app. While using Many Social Media Platforms we find this feature to be very useful when we want to share information from one app to another. The Android intent resolver is used when sending data to another app as part of a well-defined task flow. To use the Android intent resolver, create an intent and add extras. Here we are going to understand how to do that. Also, we are going to implement the vice versa (Another App to Your App) case in this article. 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: Working with the activity_main.xml file Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" tools:context=".MainActivity"> <!--Here we will be input out=r text share--> <EditText android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="write Something here to share" android:textColor="#000" android:textSize="22sp" /> <!--We will click on it then shareonlytext function will be called--> <Button android:id="@+id/share" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:background="@color/black" android:padding="5dp" android:text="Share" android:textSize="10dp" /> </LinearLayout> Step 3: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import androidx.appcompat.app.AppCompatActivity; import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText; public class MainActivity extends AppCompatActivity { Button share; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); share = findViewById(R.id.share); // initialising text field where we will enter data final EditText editText = findViewById(R.id.text); share.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Now share text only function will be called // here we will be passing the text to share shareTextOnly(editText.getText().toString()); } }); } private void shareTextOnly(String titlee) { String sharebody = titlee; // The value which we will sending through data via // other applications is defined // via the Intent.ACTION_SEND Intent intentt = new Intent(Intent.ACTION_SEND); // setting type of data shared as text intentt.setType("text/plain"); intentt.putExtra(Intent.EXTRA_SUBJECT, "Subject Here"); // Adding the text to share using putExtra intentt.putExtra(Intent.EXTRA_TEXT, sharebody); startActivity(Intent.createChooser(intentt, "Share Via")); }} Output: Let’s think that we are developing a chat App. In that case, we may want to share text from another app with some users of our app. Here Basically what we are doing is taking text from google and sharing that in our app and entering that text in edit text. In that case, we need to write some code to implement this feature in our app (Share text from Another App to our App). 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: Working with the AndroidManifest.xml file For adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml and Inside that file add the below permissions to it. <uses-permission android:name="android.permission.INTERNET" /> Also, make the following changes in your manifest file. The complete AndroidManifest.xml file is given below. XML <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sharetext"> <uses-permission android:name="android.permission.INTERNET" /> <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/Theme.ShareText"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.SEND" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.SEND" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="text/plain" /> </intent-filter> </activity> </application> </manifest> Step 3: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" tools:context=".MainActivity"> <EditText android:id="@+id/gettext" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="Get text" android:textSize="22sp" android:textStyle="bold" /> </LinearLayout> Step 4: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.content.Intent;import android.os.Bundle;import android.widget.EditText; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { EditText gettext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); gettext = findViewById(R.id.gettext); // initiating the intent Intent intent = getIntent(); String action = intent.getAction(); // getting type of content shared String type = intent.getType(); // if value is not null then show the content if (Intent.ACTION_SEND.equals(action) && type != null) { handlesendText(intent); } } private void handlesendText(Intent intent) { // here we are getting the text String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT); if (sharedText != null) { // showing the text in edittext gettext.setText(sharedText); } }} Output: annianni Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Retrofit with Kotlin Coroutine in Android Android Listview in Java with Example How to Read Data from SQLite Database in Android? Flutter - Custom Bottom Navigation Bar How to Change the Background Color After Clicking the Button in Android? Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Initialize an ArrayList in Java
[ { "code": null, "e": 25060, "s": 25032, "text": "\n29 Apr, 2021" }, { "code": null, "e": 25603, "s": 25060, "text": "Most of the time while using an app we want to share text from the app to another app. While using Many Social Media Platforms we find this feature to be very usef...
Separating mixed signals with Independent Component Analysis | by Carsten Klein | Towards Data Science
The world around is a dynamic mixture of signals from various sources. Just like the colors in the above picture blend into one another, giving rise to new shades and tones, everything we perceive is a fusion of simpler components. Most of the time we are not even aware that the world around us is such a chaotic intermix of independent processes. Only in situations where different stimuli, that do not mix well, compete for our attention we realize this mess. A typical example is the scenario at a cocktail party where one is listening to the voice of another person while filtering out the voices of all the other guests. Depending on the loudness in the room this can either be a simple or a hard task but somehow our brains are capable of separating the signal from the noise. While it is not understood how our brains do this separation there are several computational techniques out there that aim at splitting a signal into its fundamental components. One of these methods is termed Independent Component Analysis (ICA) and here we will have a closer look on how this algorithm works and how to write it down in Python code. If you are more interested in the code than in the explanation you can also directly check out the Jupyter Notebook for this post on Github. Lets stay with the example of the cocktail party for now. Imaging there are two people talking, you can hear both of them but one is closer to you than the other. The sound waves of both sources will mix and reach your ears as a combined signal. Your brain will un-mix both sources and you will perceive the voices of both guests separately with the one standing closer to you as the louder one. Now lets describe this in a more abstract and simplified way. Each source is a sine wave with a constant frequency. Both sources mix depending on where you stand. This means the source closer to you will be more dominant in the mixed signal than the one more far away. We can write this down as follows in vector-matrix notation: Where x is the observed signal, s are the source signals and A is the mixing matrix. In other words our model assumes that the signals x are generated through a linear combination of the source signals. In Python code our example will look like this: >> import numpy as np>>> # Number of samples >>> ns = np.linspace(0, 200, 1000)>>> # Sources with (1) sine wave, (2) saw tooth and (3) random noise>>> S = np.array([np.sin(ns * 1), signal.sawtooth(ns * 1.9), np.random.random(len(ns))]).T>>> # Quadratic mixing matrix>>> A = np.array([[0.5, 1, 0.2], [1, 0.5, 0.4], [0.5, 0.8, 1]])>>> # Mixed signal matrix>>> X = S.dot(A).T As can be seen from the plots in Figure 1 below the code generates one sine wave signal, one saw tooth signal and some random noise. These three signals are our independent sources. In the plot below we can also see the three linear combinations of the source signals. Further we see that the first mixed signal is dominated by the saw tooth component, the second mixed signal is influence more by the sine wave component and the last mixed signal is dominated by the noise component. Now, according to our model we can retrieve the source signals again from the mixed signals by multiplying x with the inverse of A: This means in order to find the source signals we need to calculate W. So the task for the rest of this post will be to find W and retrieve the three independent source signals from the three mixed signals. Now, before we continue we need to think a little more about what properties our source signals need to have so that the ICA successfully estimates W. The first precondition for the algorithm to work is that the mixed signals are a linear combination of any number of source signals. The second precondition is that the source signals are independent. So what does independence mean? Two signals are independent if the information in signal s1 does not give any information about signal s2. This implies that they are not correlated, which means that their covariance is 0. However, one has to be careful here as uncorrelatedness does not automatically mean independence. The third precondition is that the independent components are non-Gaussian. Why is that? The joint density distribution of two independent non-Gaussian signals will be uniform on a square; see upper left plot in Figure 2 below. Mixing these two signals with an orthogonal matrix will result in two signals that are now not independent anymore and have a uniform distribution on a parallelogram; see lower left plot in Figure 2. Which means that if we are at the minimum or maximum value of one of our mixed signals we know the value of the other signal. Therefore they are not independent anymore. Doing the same with two Gaussian signals will result in something else (see right panel of Figure 2). The joint distribution of the source signals is completely symmetric and so is the joint distribution of the mixed signals. Therefore it does not contain any information about the mixing matrix, the inverse of which we want to calculate. It follows that in this case the ICA algorithm will fail. So in summary for the ICA algorithm to work the following preconditions need to be met: Our sources are a (1) lineare mixture of (2) independent, (3) non-Gaussian signals. So lets quickly check if our test signals from above meet these preconditions. In the left plot below we see the sine wave signal plottet against the saw tooth signal while the color of each dot represents the noise component. The signals are distributed on a square as expected for non-Gaussian random variables. Likewise the mixed signals form a parallelogram in the right plot of Figure 3 which shows that the mixed signals are not independent anymore. Now taking the mixed signals and feeding them directly into the ICA is not a good idea. To get an optimal estimate of the independent components it is advisable to do some pre-processing of the data. In the following the two most important pre-processing techniques are explained in more detail. The first pre-processing step we will discuss here is centering. This is a simple subtraction of the mean from our input X. As a result the centered mixed signals will have zero mean which implies that also our source signals s are of zero mean. This simplifies the ICA calculation and the mean can later be added back. The centering function in Python looks as follows. >>> def center(x):>>> return x - np.mean(x, axis=1, keepdims=True) The second pre-processing step that we need is whitening of our signals X. The goal here is to linearly transform X so that potential correlations between the signals are removed and their variances equal unity. As a result the covariance matrix of the whitened signals will be equal to the identity matrix: Where I is the identity matrix. Since we also need to calculate the covariance during the whitening procedure we will write a small Python function for it. >>> def covariance(x):>>> mean = np.mean(x, axis=1, keepdims=True)>>> n = np.shape(x)[1] - 1>>> m = x - mean>>> return (m.dot(m.T))/n The code for the whitening step is shown below. It is based on the Singular Value Decomposition (SVD) of the covariance matrix of X. If you are interested in the details of this procedure I recommend this article. >>> def whiten(x):>>> # Calculate the covariance matrix>>> coVarM = covariance(X) >>> # Singular value decoposition>>> U, S, V = np.linalg.svd(coVarM) >>> # Calculate diagonal matrix of eigenvalues>>> d = np.diag(1.0 / np.sqrt(S)) >>> # Calculate whitening matrix>>> whiteM = np.dot(U, np.dot(d, U.T)) >>> # Project onto whitening matrix>>> Xw = np.dot(whiteM, X) >>> return Xw, whiteM OK, now that we have our pre-processing functions in place we can finally start implementing the ICA algorithm. There are several ways of implementing the ICA based on the contrast function that measures independence. Here we will use an approximation of negentropy in an ICA version called FastICA. So how does it work? As discussed above one precondition for ICA to work is that our source signals are non-Gaussian. An interesting thing about two independent, non-Gaussian signals is that their sum is more Gaussian than any of the source signals. Therefore we need to optimize W in a way that the resulting signals of Wx are as non-Gaussian as possible. In order to do so we need a measure of gaussianity. The simplest measure would be kurtosis, which is the fourth moment of the data and measures the “tailedness” of a distribution. A normal distribution has a value of 3, a uniform distribution like the one we used in Figure 2 has a kurtosis < 3. The implementation in Python is straight forward as can be seen from the code below which also calculates the other moments of the data. The first moment is the mean, the second is the variance, the third is the skewness and the fourth is the kurtosis. Here 3 is subtracted from the fourth moment so that a normal distribution has a kurtosis of 0. >>> def kurtosis(x):>>> n = np.shape(x)[0]>>> mean = np.sum((x**1)/n) # Calculate the mean>>> var = np.sum((x-mean)**2)/n # Calculate the variance>>> skew = np.sum((x-mean)**3)/n # Calculate the skewness>>> kurt = np.sum((x-mean)**4)/n # Calculate the kurtosis>>> kurt = kurt/(var**2)-3>>> return kurt, skew, var, mean For our implementation of ICA however we will not use kurtosis as a contrast function but we can use it later to check our results. Instead we will use the following contrast function g(u) and its first derivative g’(u): The FastICA algorithm uses the two above functions in the following way in a fixed-point iteration scheme: So according to the above what we have to do is to take a random guess for the weights of each component. The dot product of the random weights and the mixed signals is passed into the two functions g and g’. We then subtract the result of g’ from g and calculate the mean. The result is our new weights vector. Next we could directly divide the new weights vector by its norm and repeat the above until the weights do not change anymore. There would be nothing wrong with that. However the problem we are facing here is that in the iteration for the second component we might identify the same component as in the first iteration. To solve this problem we have to decorrelate the new weights from the previously identified weights. This is what is happening in the step between updating the weights and dividing by their norm. In Python the implementation then looks as follows: >>> def fastIca(signals, alpha = 1, thresh=1e-8, iterations=5000):>>> m, n = signals.shape>>> # Initialize random weights>>> W = np.random.rand(m, m)>>> for c in range(m):>>> w = W[c, :].copy().reshape(m, 1)>>> w = w/ np.sqrt((w ** 2).sum())>>> i = 0>>> lim = 100>>> while ((lim > thresh) & (i < iterations)):>>> # Dot product of weight and signal>>> ws = np.dot(w.T, signals)>>> # Pass w*s into contrast function g>>> wg = np.tanh(ws * alpha).T>>> # Pass w*s into g'>>> wg_ = (1 - np.square(np.tanh(ws))) * alpha>>> # Update weights wNew = (signals * wg.T).mean(axis=1) - >>> wg_.mean() * w.squeeze()>>> # Decorrelate weights >>> wNew = wNew - np.dot(np.dot(wNew, W[:c].T), W[:c])>>> wNew = wNew / np.sqrt((wNew ** 2).sum())>>> # Calculate limit condition>>> lim = np.abs(np.abs((wNew * w).sum()) - 1) >>> # Update weights>>> w = wNew >>> # Update counter>>> i += 1>>> W[c, :] = w.T>>> return W So now that we have all the code written up, lets run the whole thing! >>> # Center signals>>> Xc, meanX = center(X)>>> # Whiten mixed signals>>> Xw, whiteM = whiten(Xc)>>> # Run the ICA to estimate W>>> W = fastIca(Xw, alpha=1)>>> #Un-mix signals using W>>> unMixed = Xw.T.dot(W.T)>>> # Subtract mean from the unmixed signals>>> unMixed = (unMixed.T - meanX).T The results of the ICA are shown in Figure 4 below where the upper panel represents the original source signals and the lower panel the independent components retrieved by our ICA implementation. And the result looks very good. We got all three sources back! So finally lets check one last thing: The kurtosis of the signals. As we can see in Figure 5 all of our mixed signals have a kurtosis of ≤ 1 whereas all recovered independent components have a kurtosis of 1.5 which means they are less Gaussian than their sources. This has to be the case since the ICA tries to maximize non-Gaussianity. Also it nicely illustrates the fact mentioned above that the mixture of non-Gaussian signals will be more Gaussian than the sources. So to summarize: We saw how ICA works and how to implement it from scratch in Python. Of course there are many Python implementations available that can be directly used. However it is always advisable to understand the underlying principle of the method to know when and how to use it. If you are interested in diving deeper into ICA and learn about the details I recommend this paper by Aapo Hyvärinen and Erkki Oja, 2000. Otherwise you can check out the complete code here, follow me on Twitter or connect via LinkedIn. The code for this project can be found on Github.
[ { "code": null, "e": 1323, "s": 47, "text": "The world around is a dynamic mixture of signals from various sources. Just like the colors in the above picture blend into one another, giving rise to new shades and tones, everything we perceive is a fusion of simpler components. Most of the time we are...
What do you mean by timeOut in TestNG?
The timeOut is a helper attribute in TestNG that can put an end to the execution of a test method if that method takes time beyond the timeOut duration. A timeOut time is set in milliseconds, after that the test method will be marked Failed. @Test public void ContactVerify(){ System.out.println("Contact validation is successful”); } @Test(timeOut = 1000) public void LandingPage(){ System.out.println("Landing page verification is successful”); } @Test public void LoanContact(){ System.out.println("Loan contact details verification is successful”); } After 1000ms, if LandingPage() execution continues , that test method will be considered as failed. The rest of the test methods will have no impact.
[ { "code": null, "e": 1304, "s": 1062, "text": "The timeOut is a helper attribute in TestNG that can put an end to the\nexecution of a test method if that method takes time beyond the timeOut duration.\nA timeOut time is set in milliseconds, after that the test method will be marked\nFailed." }, ...
Find the largest Alphabetic character present in the string - GeeksforGeeks
08 Sep, 2021 Given a string str, our task is to find the Largest Alphabetic Character, whose both uppercase and lowercase are present in the string. The uppercase character should be returned. If there is no such character then return -1 otherwise print the uppercase letter of the character. Examples: Input: str = “admeDCAB” Output: D Explanation: Both the uppercase and lowercase characters for letter D is present in the string and it is also the largest alphabetical character, hence our output is D. Input: str = “dAeB” Output: -1 Explanation: Although the largest character is d in the string but the uppercase version is not present hence the output is -1. Naive Approach: To solve the problem mentioned above the naive method is to check for the presence of each character in the string for both uppercase or lowercase character that is for letter A both ‘a’ and ‘A’ should be there in the string. If such a letter is present then will keep track of that character and update only if the current character is greater than the previously chosen character. This method takes O(n2) time in the worst case and can be further optimized. Efficient Approach: To optimize the above method we use the fact that we have 26 characters in the English alphabet, we can keep track of both lowercase and uppercase character by maintaining an array of size 26. While iterating through the given string we will mark true in both the array if the current character is present in both uppercase and lowercase letter. After marking all characters present in the respective array we will run a loop from 25 to 0 and check if both the array has ‘true’ marked in them. If yes then we print the uppercase letter of that character otherwise return -1. Below is the implementation of the above approach: Java Python3 C# Javascript // Java program to Find the Largest Alphabetic// Character present in the string of both// uppercase and lowercase English characters public class Main { // Function to find the Largest Alphabetic Character public static String largestCharacter(String str) { // Array for keeping track of both uppercase // and lowercase english alphabets boolean[] uppercase = new boolean[26]; boolean[] lowercase = new boolean[26]; char[] arr = str.toCharArray(); for (char c : arr) { if (Character.isLowerCase(c)) lowercase = true; if (Character.isUpperCase(c)) uppercase = true; } // Iterate from right side of array // to get the largest index character for (int i = 25; i >= 0; i--) { // Check for the character if both its // uppercase and lowercase exist or not if (uppercase[i] && lowercase[i]) return (char)(i + 'A') + ""; } // Return -1 if no such character whose // uppercase and lowercase present in // string str return "-1"; } // Driver code public static void main(String[] args) { String str = "admeDCAB"; System.out.println(largestCharacter(str)); }} # Java program to Find the Largest Alphabetic# Character present in the string of both# uppercase and lowercase English characters # Function to find the Largest Alphabetic Characterdef largestCharacter(str): # Array for keeping track of both uppercase # and lowercase english alphabets uppercase = [False] * 26 lowercase = [False] * 26 arr = list(str) for c in arr: if (c.islower()): lowercase[ord(c) - ord('a')] = True if (c.isupper()): uppercase[ord(c) - ord('A')] = True # Iterate from right side of array # to get the largest index character for i in range(25,-1,-1): # Check for the character if both its # uppercase and lowercase exist or not if (uppercase[i] and lowercase[i]): return chr(i + ord('A')) + "" # Return -1 if no such character whose # uppercase and lowercase present in # string str return "-1" # Driver code str = "admeDCAB"print(largestCharacter(str)) # This code is contributed by shivanisinghss2110 // C# program to Find the Largest Alphabetic// char present in the string of both// uppercase and lowercase English charactersusing System; class GFG{ // Function to find the Largest Alphabetic charpublic static String largestchar(String str){ // Array for keeping track of both uppercase // and lowercase english alphabets bool[] uppercase = new bool[26]; bool[] lowercase = new bool[26]; char[] arr = str.ToCharArray(); foreach(char c in arr) { if (char.IsLower(c)) lowercase = true; if (char.IsUpper(c)) uppercase = true; } // Iterate from right side of array // to get the largest index character for(int i = 25; i >= 0; i--) { // Check for the character if both its // uppercase and lowercase exist or not if (uppercase[i] && lowercase[i]) return (char)(i + 'A') + ""; } // Return -1 if no such character whose // uppercase and lowercase present in // string str return "-1";} // Driver codepublic static void Main(String[] args){ String str = "admeDCAB"; Console.WriteLine(largestchar(str));}} // This code is contributed by amal kumar choubey <script> // JavaScript program to Find the Largest Alphabetic // Character present in the string of both // uppercase and lowercase English characters // Function to find the Largest Alphabetic Character function largestCharacter(str) { // Array for keeping track of both uppercase // and lowercase english alphabets let uppercase = new Array(26); uppercase.fill(false); let lowercase = new Array(26); lowercase.fill(false); let arr = str.split(''); for (let c = 0; c < arr.length; c++) { if (arr == arr.toLowerCase()) lowercase[arr.charCodeAt() - 97] = true; if (arr == arr.toUpperCase()) uppercase[arr.charCodeAt() - 65] = true; } // Iterate from right side of array // to get the largest index character for (let i = 25; i >= 0; i--) { // Check for the character if both its // uppercase and lowercase exist or not if (uppercase[i] && lowercase[i]) return String.fromCharCode(i + 'A'.charCodeAt()) + ""; } // Return -1 if no such character whose // uppercase and lowercase present in // string str return "-1"; } let str = "admeDCAB"; document.write(largestCharacter(str)); </script> Output: D Time complexity: O(n) where n is length of string. Space complexity: O(52) Amal Kumar Choubey suresh07 surindertarika1234 shivanisinghss2110 Microsoft Strings Microsoft Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python program to check if a string is palindrome or not Convert string to char array in C++ Longest Palindromic Substring | Set 1 Array of Strings in C++ (5 Different Ways to Create) Caesar Cipher in Cryptography Check whether two strings are anagram of each other Reverse words in a given string Top 50 String Coding Problems for Interviews Length of the longest substring without repeating characters How to split a string in C/C++, Python and Java?
[ { "code": null, "e": 25210, "s": 25182, "text": "\n08 Sep, 2021" }, { "code": null, "e": 25490, "s": 25210, "text": "Given a string str, our task is to find the Largest Alphabetic Character, whose both uppercase and lowercase are present in the string. The uppercase character sho...
Rectangle Overlap in Python
Suppose there is a rectangle that is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinates of its bottom-left corner, and (x2, y2) is the coordinates of its top-right corner. Now two rectangles overlap if the area of their intersection is positive. So, we can understand that two rectangles that only touch at the corner or edges do not overlap. If we have two (axis-aligned) rectangles, we have to check whether they overlap or not. So, if the input is like R1 = [0,0,2,2], R2 = [1,1,3,3], then the output will be True. To solve this, we will follow these steps − if R1[0]>=R2[2] or R1[2]<=R2[0] or R1[3]<=R2[1] or R1[1]>=R2[3], thenreturn False return False otherwise,return True return True Let us see the following implementation to get better understanding − Live Demo class Solution: def isRectangleOverlap(self, R1, R2): if (R1[0]>=R2[2]) or (R1[2]<=R2[0]) or (R1[3]<=R2[1]) or (R1[1]>=R2[3]): return False else: return True ob = Solution() print(ob.isRectangleOverlap([0,0,2,2],[1,1,3,3])) [0,0,2,2],[1,1,3,3] True
[ { "code": null, "e": 1428, "s": 1062, "text": "Suppose there is a rectangle that is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinates of its bottom-left corner, and (x2, y2) is the coordinates of its top-right corner. Now\ntwo rectangles overlap if the area of their intersect...
How to permanently hide Navigation Bar in an Android Activity?
This example demonstrates how do I permanently hide Navigation Bar in an Android Activity in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 3 − Add the following code to src/MainActivity.java import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.os.Build; import android.os.Bundle; import android.view.View; public class MainActivity extends AppCompatActivity { private int currentApiVersion; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); currentApiVersion = android.os.Build.VERSION.SDK_INT; final int flags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; if (currentApiVersion >= Build.VERSION_CODES.KITKAT) { getWindow().getDecorView().setSystemUiVisibility(flags); final View decorView = getWindow().getDecorView(); decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() { @Override public void onSystemUiVisibilityChange(int visibility) { if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) { decorView.setSystemUiVisibility(flags); } } }); } } @SuppressLint("NewApi") @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (currentApiVersion >= Build.VERSION_CODES.KITKAT && hasFocus) { getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); } } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1164, "s": 1062, "text": "This example demonstrates how do I permanently hide Navigation Bar in an Android Activity in android." }, { "code": null, "e": 1293, "s": 1164, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fi...
How to create a text area in JavaFX?
A text area is a multi-line editor where you can enter text. Unlike previous versions, in the latest versions of JavaFX, a TextArea does not allow single lines in it. You can create a text area by instantiating the javafx.scene.control.TextArea class. The following Example demonstrates the creation of a TextArea. import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.TextArea; import javafx.scene.layout.HBox; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; import javafx.stage.Stage; public class TextAreaExample extends Application { public void start(Stage stage) { //Setting the label Label label = new Label("Address"); Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12); label.setFont(font); //Creating a pagination TextArea area = new TextArea(); //Setting number of pages area.setText("Enter your address here"); area.setPrefColumnCount(15); area.setPrefHeight(120); area.setPrefWidth(300); //Creating a hbox to hold the pagination HBox hbox = new HBox(); hbox.setSpacing(20); hbox.setPadding(new Insets(20, 50, 50, 60)); hbox.getChildren().addAll(label, area); //Setting the stage Group root = new Group(hbox); Scene scene = new Scene(root, 595, 200, Color.BEIGE); stage.setTitle("Text Area"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
[ { "code": null, "e": 1314, "s": 1062, "text": "A text area is a multi-line editor where you can enter text. Unlike previous versions, in the latest versions of JavaFX, a TextArea does not allow single lines in it. You can create a text area by instantiating the javafx.scene.control.TextArea class." ...
Spectral Clustering Algorithm Implemented From Scratch | by Cory Maklin | Towards Data Science
Spectral clustering is a popular unsupervised machine learning algorithm which often outperforms other approaches. In addition, spectral clustering is very simple to implement and can be solved efficiently by standard linear algebra methods. In spectral clustering, the affinity, and not the absolute location (i.e. k-means), determines what points fall under which cluster. The latter is particularly useful in tackling problems where the data forms complicated shapes. The algorithm can be broken down into 4 basic steps. Construct a similarity graphDetermine the Adjacency matrix W, Degree matrix D and the Laplacian matrix LCompute the eigenvectors of the matrix LUsing the second smallest eigenvector as input, train a k-means model and use it to classify the data Construct a similarity graph Determine the Adjacency matrix W, Degree matrix D and the Laplacian matrix L Compute the eigenvectors of the matrix L Using the second smallest eigenvector as input, train a k-means model and use it to classify the data In the proceeding section, we’ll implement spectral clustering from scratch. We’re going to need the following libraries. import numpy as npfloat_formatter = lambda x: "%.3f" % xnp.set_printoptions(formatter={'float_kind':float_formatter})from sklearn.datasets.samples_generator import make_circlesfrom sklearn.cluster import SpectralClustering, KMeansfrom sklearn.metrics import pairwise_distancesfrom matplotlib import pyplot as pltimport networkx as nximport seaborn as snssns.set() Typically, you will have a dataset composed of samples (rows) and their features (columns). However, the spectral clustering algorithm can only be applied to a graph of connected nodes. Therefore, we must apply transformations to our data in order to go from a table of rows and columns to a graph. Assume that we had the following dataset. We can clearly see that the data can be segregated into three clusters. X = np.array([ [1, 3], [2, 1], [1, 1], [3, 2], [7, 8], [9, 8], [9, 9], [8, 7], [13, 14], [14, 14], [15, 16], [14, 15]])plt.scatter(X[:,0], X[:,1], alpha=0.7, edgecolors='b')plt.xlabel('Weight')plt.ylabel('Height') First, we construct the similarity matrix, a NxN matrix where N is the number of samples. We fill the cells with the euclidean distance between each pair of points. Then we create the adjacency matrix by copying the contents of the similarity matrix and only this time, we set a threshold such that if the distance is greater than the predefined limit, we set the value to 0 and 1 otherwise. The adjacency matrix can then be used to build a graph. If there’s a 1 in the cell of the adjacency matrix then we draw an edge between the nodes of the column and row. W = pairwise_distances(X, metric="euclidean")vectorizer = np.vectorize(lambda x: 1 if x < 5 else 0)W = np.vectorize(vectorizer)(W)print(W) For the remainder of this tutorial, we’ll be using the networkx library to visualize graphs. def draw_graph(G): pos = nx.spring_layout(G) nx.draw_networkx_nodes(G, pos) nx.draw_networkx_labels(G, pos) nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5) To start, we randomly generate a graph and print its adjacency matrix. G = nx.random_graphs.erdos_renyi_graph(10, 0.5)draw_graph(G)W = nx.adjacency_matrix(G)print(W.todense()) Notice how the nodes form a single component (i.e. all other nodes can be reached from a given node). Once we’ve built the adjacency matrix, we construct the degree matrix. For each row of the degree matrix we fill the cell along the diagonal by summing all the elements of the corresponding row in the adjacency matrix. Then, we compute the laplacian matrix by subtracting the adjacency matrix from the degree matrix. # degree matrixD = np.diag(np.sum(np.array(W.todense()), axis=1))print('degree matrix:')print(D)# laplacian matrixL = D - Wprint('laplacian matrix:')print(L) Once we have the laplacian matrix, we can take advantage of one of its special properties to classify our data. If the graph (W) has K connected components, then L has K eigenvectors with an eigenvalue of 0. Therefore, since in our current example we only have one component, one eigenvalue will be equal to 0. e, v = np.linalg.eig(L)# eigenvaluesprint('eigenvalues:')print(e)# eigenvectorsprint('eigenvectors:')print(v) fig = plt.figure()ax1 = plt.subplot(121)plt.plot(e)ax1.title.set_text('eigenvalues')i = np.where(e < 10e-6)[0]ax2 = plt.subplot(122)plt.plot(v[:, i[0]])fig.tight_layout()plt.show() As we can see, of the 10 eigenvalues one is equal to 0. Let’s take a look at another example. The proceeding graph is composed of two components. Thus, 2 eigenvalues be equal to 0. G = nx.Graph()G.add_edges_from([ [1, 2], [1, 3], [1, 4], [2, 3], [2, 7], [3, 4], [4, 7], [1, 7], [6, 5], [5, 8], [6, 8], [9, 8], [9, 6]])draw_graph(G)W = nx.adjacency_matrix(G)print(W.todense()) # degree matrixD = np.diag(np.sum(np.array(W.todense()), axis=1))print('degree matrix:')print(D)# laplacian matrixL = D - Wprint('laplacian matrix:')print(L) e, v = np.linalg.eig(L)# eigenvaluesprint('eigenvalues:')print(e)# eigenvectorsprint('eigenvectors:')print(v) fig = plt.figure(figsize=[18, 6])ax1 = plt.subplot(131)plt.plot(e)ax1.title.set_text('eigenvalues')i = np.where(e < 10e-6)[0]ax2 = plt.subplot(132)plt.plot(v[:, i[0]])ax2.title.set_text('first eigenvector with eigenvalue of 0')ax3 = plt.subplot(133)plt.plot(v[:, i[1]])ax3.title.set_text('second eigenvector with eigenvalue of 0') If we take a closer look at the plot of each eigenvector, we can clearly see that the first 5 nodes are mapped to the same value and the other 5 nodes are mapped to another value. We can use this fact to place the nodes into one of two categories. Let’s take a look at a slightly more complicated example. The proceeding graph is made up of a single component. However, it looks like we have two classes. G = nx.Graph()G.add_edges_from([ [1, 2], [1, 3], [1, 4], [2, 3], [3, 4], [4, 5], [1, 5], [6, 7], [7, 8], [6, 8], [6, 9], [9, 6], [7, 10], [7, 2]])draw_graph(G)W = nx.adjacency_matrix(G)print(W.todense()) # degree matrixD = np.diag(np.sum(np.array(W.todense()), axis=1))print('degree matrix:')print(D)# laplacian matrixL = D - Wprint('laplacian matrix:')print(L) e, v = np.linalg.eig(L)# eigenvaluesprint('eigenvalues:')print(e)# eigenvectorsprint('eigenvectors:')print(v) fig = plt.figure(figsize=[18, 6])ax1 = plt.subplot(131)plt.plot(e)ax1.title.set_text('eigenvalues')i = np.where(e < 0.5)[0]ax2 = plt.subplot(132)plt.plot(v[:, i[0]])ax3 = plt.subplot(133)plt.plot(v[:, i[1]])ax3.title.set_text('second eigenvector with eigenvalue close to 0') Because we have a single component, only 1 eigenvalue will be equal to 0. However, if we look at the second smallest eigenvalue, we can still observe a distinction between the two classes. If we drew a horizontal line across, we’d correctly classify the nodes. Let’s take a look at another example. Again, the graph will be composed of a single component, but this time, it looks as if the nodes should be placed in one of three bins. G = nx.Graph()G.add_edges_from([ [1, 2], [1, 3], [1, 4], [2, 3], [3, 4], [4, 5], [1, 5], [6, 7], [7, 8], [6, 8], [6, 9], [9, 6], [7, 10], [7, 2], [11, 12], [12, 13], [7, 12], [11, 13]])draw_graph(G)W = nx.adjacency_matrix(G)print(W.todense()) # degree matrixD = np.diag(np.sum(np.array(W.todense()), axis=1))print('degree matrix:')print(D)# laplacian matrixL = D - Wprint('laplacian matrix:')print(L) e, v = np.linalg.eig(L)# eigenvaluesprint('eigenvalues:')print(e)# eigenvectorsprint('eigenvectors:')print(v) fig = plt.figure(figsize=[18, 6])ax1 = plt.subplot(221)plt.plot(e)ax1.title.set_text('eigenvalues')i = np.where(e < 0.5)[0]ax2 = plt.subplot(222)plt.plot(v[:, i[0]])ax3 = plt.subplot(223)plt.plot(v[:, i[1]])ax3.title.set_text('second eigenvector with eigenvalue close to 0')ax4 = plt.subplot(224)plt.plot(v[:, i[2]])ax4.title.set_text('third eigenvector with eigenvalue close to 0')fig.tight_layout() Since we only have 1 component, 1 eigenvalue will be equal to 0. However, we can again use the the second smallest eigenvalue to figure out which node should be placed in which category. In practice, we use k-means to classify the nodes based off their corresponding values in the eigenvector. U = np.array(v[:, i[1]])km = KMeans(init='k-means++', n_clusters=3)km.fit(U)km.labels_ Next, let’s compare k-means to spectral clustering using scitkit-learn’s implementation. Suppose our data took the following shape when graphed. X, clusters = make_circles(n_samples=1000, noise=.05, factor=.5, random_state=0)plt.scatter(X[:,0], X[:,1]) When using k-means, we get the following. km = KMeans(init='k-means++', n_clusters=2)km_clustering = km.fit(X)plt.scatter(X[:,0], X[:,1], c=km_clustering.labels_, cmap='rainbow', alpha=0.7, edgecolors='b') In contrast, when using spectral clustering we place each circle in its own cluster. sc = SpectralClustering(n_clusters=2, affinity='nearest_neighbors', random_state=0)sc_clustering = sc.fit(X)plt.scatter(X[:,0], X[:,1], c=sc_clustering.labels_, cmap='rainbow', alpha=0.7, edgecolors='b') In contrast to k-means, spectral clustering takes the relative position of data points into account.
[ { "code": null, "e": 643, "s": 172, "text": "Spectral clustering is a popular unsupervised machine learning algorithm which often outperforms other approaches. In addition, spectral clustering is very simple to implement and can be solved efficiently by standard linear algebra methods. In spectral c...
Python MongoDB - Update
You can update the contents of an existing documents using the update() method or save() method. The update method modifies the existing document whereas the save method replaces the existing document with the new one. Following is the syntax of the update() and save() methods of MangoDB − >db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA) Or, db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA}) Assume we have created a collection in a database and inserted 3 records in it as shown below − > use testdatabase switched to db testdatabase > data = [ ... {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"}, ... {"_id": "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" }, ... {"_id": "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" } ] [ { "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" }, { "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" }, { "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" } ] > db.createCollection("sample") { "ok" : 1 } > db.sample.insert(data) Following method updates the city value of the document with id 1002. > db.sample.update({"_id":"1002"},{"$set":{"city":"Visakhapatnam"}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.sample.find() { "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" } { "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Visakhapatnam" } { "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" } Similarly you can replace the document with new data by saving it with same id using the save() method. > db.sample.save( { "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Vijayawada" } ) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.sample.find() { "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Vijayawada" } { "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Visakhapatnam" } { "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" } Similar to find_one() method which retrieves single document, the update_one() method of pymongo updates a single document. This method accepts a query specifying which document to update and the update operation. Following python example updates the location value of a document in a collection. from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['myDB'] #Creating a collection coll = db['example'] #Inserting document into a collection data = [ {"_id": "101", "name": "Ram", "age": "26", "city": "Hyderabad"}, {"_id": "102", "name": "Rahim", "age": "27", "city": "Bangalore"}, {"_id": "103", "name": "Robert", "age": "28", "city": "Mumbai"} ] res = coll.insert_many(data) print("Data inserted ......") #Retrieving all the records using the find() method print("Documents in the collection: ") for doc1 in coll.find(): print(doc1) coll.update_one({"_id":"102"},{"$set":{"city":"Visakhapatnam"}}) #Retrieving all the records using the find() method print("Documents in the collection after update operation: ") for doc2 in coll.find(): print(doc2) Data inserted ...... Documents in the collection: {'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'} {'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'} {'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'} Documents in the collection after update operation: {'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'} {'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Visakhapatnam'} {'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'} Similarly, the update_many() method of pymongo updates all the documents that satisfies the specified condition. Following example updates the location value in all the documents in a collection (empty condition) − from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['myDB'] #Creating a collection coll = db['example'] #Inserting document into a collection data = [ {"_id": "101", "name": "Ram", "age": "26", "city": "Hyderabad"}, {"_id": "102", "name": "Rahim", "age": "27", "city": "Bangalore"}, {"_id": "103", "name": "Robert", "age": "28", "city": "Mumbai"} ] res = coll.insert_many(data) print("Data inserted ......") #Retrieving all the records using the find() method print("Documents in the collection: ") for doc1 in coll.find(): print(doc1) coll.update_many({},{"$set":{"city":"Visakhapatnam"}}) #Retrieving all the records using the find() method print("Documents in the collection after update operation: ") for doc2 in coll.find(): print(doc2) Data inserted ...... Documents in the collection: {'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'} {'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'} {'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'} Documents in the collection after update operation: {'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Visakhapatnam'} {'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Visakhapatnam'} {'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Visakhapatnam'} 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": 3302, "s": 3205, "text": "You can update the contents of an existing documents using the update() method or save() method." }, { "code": null, "e": 3424, "s": 3302, "text": "The update method modifies the existing document whereas the save method replaces the...
Check whether the two Binary Search Trees are Identical or Not - GeeksforGeeks
28 Feb, 2022 Given the root nodes of the two binary search trees. The task is to print 1 if the two Binary Search Trees are identical else print 0. Two trees are identical if they are identical structurally and nodes have the same values. In the above images, both Tree1 and Tree2 are identical. To identify if two trees are identical, we need to traverse both trees simultaneously, and while traversing we need to compare data and children of the trees.Below is the step by step algorithm to check if two BSTs are identical: If both trees are empty then return 1.Else If both trees are non -empty Check data of the root nodes (tree1->data == tree2->data)Check left subtrees recursively i.e., call sameTree(tree1->left_subtree, tree2->left_subtree)Check right subtrees recursively i.e., call sameTree(tree1->right_subtree, tree2->right_subtree)If the values returned in the above three steps are true then return 1.Else return 0 (one is empty and other is not). If both trees are empty then return 1. Else If both trees are non -empty Check data of the root nodes (tree1->data == tree2->data)Check left subtrees recursively i.e., call sameTree(tree1->left_subtree, tree2->left_subtree)Check right subtrees recursively i.e., call sameTree(tree1->right_subtree, tree2->right_subtree)If the values returned in the above three steps are true then return 1. Check data of the root nodes (tree1->data == tree2->data) Check left subtrees recursively i.e., call sameTree(tree1->left_subtree, tree2->left_subtree) Check right subtrees recursively i.e., call sameTree(tree1->right_subtree, tree2->right_subtree) If the values returned in the above three steps are true then return 1. Else return 0 (one is empty and other is not). Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to check if two BSTs// are identical #include <iostream>using namespace std; // BST nodestruct Node { int data; struct Node* left; struct Node* right;}; // Utility function to create a new Nodestruct Node* newNode(int data){ struct Node* node = (struct Node*) malloc(sizeof(struct Node)); node->data = data; node->left = NULL; node->right = NULL; return node;} // Function to perform inorder traversalvoid inorder(Node* root){ if (root == NULL) return; inorder(root->left); cout << root->data << " "; inorder(root->right);} // Function to check if two BSTs// are identicalint isIdentical(Node* root1, Node* root2){ // Check if both the trees are empty if (root1 == NULL && root2 == NULL) return 1; // If any one of the tree is non-empty // and other is empty, return false else if (root1 != NULL && root2 == NULL) return 0; else if (root1 == NULL && root2 != NULL) return 0; else { // Check if current data of both trees equal // and recursively check for left and right subtrees if (root1->data == root2->data && isIdentical(root1->left, root2->left) && isIdentical(root1->right, root2->right)) return 1; else return 0; }} // Driver codeint main(){ struct Node* root1 = newNode(5); struct Node* root2 = newNode(5); root1->left = newNode(3); root1->right = newNode(8); root1->left->left = newNode(2); root1->left->right = newNode(4); root2->left = newNode(3); root2->right = newNode(8); root2->left->left = newNode(2); root2->left->right = newNode(4); if (isIdentical(root1, root2)) cout << "Both BSTs are identical"; else cout << "BSTs are not identical"; return 0;} // Java program to check if two BSTs// are identicalclass GFG{ // BST nodestatic class Node{ int data; Node left; Node right;}; // Utility function to create a new Nodestatic Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return node;} // Function to perform inorder traversalstatic void inorder(Node root){ if (root == null) return; inorder(root.left); System.out.print(root.data + " "); inorder(root.right);} // Function to check if two BSTs// are identicalstatic int isIdentical(Node root1, Node root2){ // Check if both the trees are empty if (root1 == null && root2 == null) return 1; // If any one of the tree is non-empty // and other is empty, return false else if (root1 != null && root2 == null) return 0; else if (root1 == null && root2 != null) return 0; else { // Check if current data of both trees equal // and recursively check for left and right subtrees if (root1.data == root2.data && isIdentical(root1.left, root2.left) == 1 && isIdentical(root1.right, root2.right) == 1) return 1; else return 0; }} // Driver codepublic static void main(String[] args){ Node root1 = newNode(5); Node root2 = newNode(5); root1.left = newNode(3); root1.right = newNode(8); root1.left.left = newNode(2); root1.left.right = newNode(4); root2.left = newNode(3); root2.right = newNode(8); root2.left.left = newNode(2); root2.left.right = newNode(4); if (isIdentical(root1, root2)==1) System.out.print("Both BSTs are identical"); else System.out.print("BSTs are not identical");}} // This code is contributed by 29AjayKumar # Python3 program to construct all unique# BSTs for keys from 1 to n # Binary Tree Node""" A utility function to create anew BST node """class newNode: # Construct to create a newNode def __init__(self, data): self.data = data self.left = None self.right = None # Function to perform inorder traversaldef inorder(root) : if (root == None): return inorder(root.left) print(root.data, end = " ") inorder(root.right) # Function to check if two BSTs# are identicaldef isIdentical(root1, root2) : # Check if both the trees are empty if (root1 == None and root2 == None) : return 1 # If any one of the tree is non-empty # and other is empty, return false elif (root1 != None and root2 == None) : return 0 elif (root1 == None and root2 != None) : return 0 else: # Check if current data of both trees # equal and recursively check for left # and right subtrees if (root1.data == root2.data and isIdentical(root1.left, root2.left) and isIdentical(root1.right, root2.right)) : return 1 else: return 0 # Driver Codeif __name__ == '__main__': root1 = newNode(5) root2 = newNode(5) root1.left = newNode(3) root1.right = newNode(8) root1.left.left = newNode(2) root1.left.right = newNode(4) root2.left = newNode(3) root2.right = newNode(8) root2.left.left = newNode(2) root2.left.right = newNode(4) if (isIdentical(root1, root2)): print("Both BSTs are identical") else: print("BSTs are not identical") # This code is contributed by# Shubham Singh(SHUBHAMSINGH10) // C# program to check if two BSTs// are identicalusing System; class GFG{ // BST nodeclass Node{ public int data; public Node left; public Node right;}; // Utility function to create a new Nodestatic Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return node;} // Function to perform inorder traversalstatic void inorder(Node root){ if (root == null) return; inorder(root.left); Console.Write(root.data + " "); inorder(root.right);} // Function to check if two BSTs// are identicalstatic int isIdentical(Node root1, Node root2){ // Check if both the trees are empty if (root1 == null && root2 == null) return 1; // If any one of the tree is non-empty // and other is empty, return false else if (root1 != null && root2 == null) return 0; else if (root1 == null && root2 != null) return 0; else { // Check if current data of both trees equal // and recursively check for left and right subtrees if (root1.data == root2.data && isIdentical(root1.left, root2.left) == 1 && isIdentical(root1.right, root2.right) == 1) return 1; else return 0; }} // Driver codepublic static void Main(String[] args){ Node root1 = newNode(5); Node root2 = newNode(5); root1.left = newNode(3); root1.right = newNode(8); root1.left.left = newNode(2); root1.left.right = newNode(4); root2.left = newNode(3); root2.right = newNode(8); root2.left.left = newNode(2); root2.left.right = newNode(4); if (isIdentical(root1, root2) == 1) Console.Write("Both BSTs are identical"); else Console.Write("BSTs are not identical");}} // This code is contributed by PrinciRaj1992 <script>// Javascript program to check if two BSTs// are identical // BST nodeclass Node{ // Utility function to create a new Node constructor(data) { this.data = data; this.left = this.right = null; }} // Function to perform inorder traversalfunction inorder(root){ if (root == null) return; inorder(root.left); document.write(root.data + " "); inorder(root.right);} // Function to check if two BSTs// are identicalfunction isIdentical(root1,root2){ // Check if both the trees are empty if (root1 == null && root2 == null) return 1; // If any one of the tree is non-empty // and other is empty, return false else if (root1 != null && root2 == null) return 0; else if (root1 == null && root2 != null) return 0; else { // Check if current data of both trees equal // and recursively check for left and right subtrees if (root1.data == root2.data && isIdentical(root1.left, root2.left) == 1 && isIdentical(root1.right, root2.right) == 1) return 1; else return 0; }} // Driver codelet root1 = new Node(5); let root2 = new Node(5); root1.left = new Node(3); root1.right = new Node(8); root1.left.left = new Node(2); root1.left.right = new Node(4); root2.left = new Node(3); root2.right = new Node(8); root2.left.left = new Node(2); root2.left.right = new Node(4); if (isIdentical(root1, root2)==1) document.write("Both BSTs are identical"); else document.write("BSTs are not identical"); // This code is contributed by avanitrachhadiya2155</script> Both BSTs are identical Time Complexity: O(N)Auxiliary Space: O(N) SHUBHAMSINGH10 29AjayKumar princiraj1992 pankajsharmagfg rag2127 surinderdawra388 Binary Search Tree Data Structures Recursion Data Structures Recursion Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorted Array to Balanced BST Optimal Binary Search Tree | DP-24 Red-Black Tree | Set 2 (Insert) Inorder Successor in Binary Search Tree Find the node with minimum value in a Binary Search Tree SDE SHEET - A Complete Guide for SDE Preparation Top 50 Array Coding Problems for Interviews DSA Sheet by Love Babbar Doubly Linked List | Set 1 (Introduction and Insertion) How to Start Learning DSA?
[ { "code": null, "e": 26729, "s": 26701, "text": "\n28 Feb, 2022" }, { "code": null, "e": 26956, "s": 26729, "text": "Given the root nodes of the two binary search trees. The task is to print 1 if the two Binary Search Trees are identical else print 0. Two trees are identical if t...
Getting Started with R Shiny. Take the first steps towards becoming... | by Sheenal Srivastava | Towards Data Science
Shiny is an R package that allows programmers to build web applications within R. For someone like me, who found building GUI applications in Java really hard, Shiny makes it much easier. This blog article will get you building Shiny apps straight away with working examples. First things first, make sure you install the shiny package. install.packages("shiny") Like R files, Shiny apps also end with a .R extension. The app structure consists of three components, which are: A user interface object (ui)A server functionA function call to shinyApp A user interface object (ui) A server function A function call to shinyApp The user interface (ui) object is used to manage the appearance and layout of the app, such as radio buttons, panels, and selection boxes. # Define UI for app ui <- fluidPage( # App title ---- titlePanel("!"), # Sidebar layout with input and output definitions ---- sidebarLayout( # Sidebar panel for inputs sidebarPanel( )# Allow user to select input for a y-axis variable from drop-down selectInput("y_varb", label="Y-axis variable",choices=names(data)[c(-1,-3,-4)]),# Output: Plot ("plot", dblclick = "plot_reset")) The server function contains information that is required to build the app. This includes instructions to generate a plot or table and react to user clicks for example. # Define server logic here ----server <- function(input, output) { # 1. It is "reactive" and therefore updates x-variable based on y- variable selection # 2. Its output type is a plot output$distPlot <- renderPlot({ remaining <- reactive({ names(data)[c(-1,-3,-4,-match(input$y_varb,names(data)))] }) observeEvent(remaining(),{ choices <- remaining() updateSelectInput(session = getDefaultReactiveDomain(),inputId = "x_varb", choices = choices) })}output$plot <- renderPlot({ #ADD YOUR GGPLOT CODE HERE subset_data<-data[1:input$sample_sz,] ggplot(subset_data, aes_string(input$x_varb, input$y_varb))+ geom_point(aes_string(colour=input$cat_colour))+ geom_smooth(method="lm",formula=input$formula)}, res = 96)} Lastly, the shinyAppfunction builds Shiny app objects based on the UI/server pair. library(shiny)# Build shiny objectshinyApp(ui = ui, server = server)# Call to run the applicationrunApp("my_app") Reactivity is all about linking user inputs to app outputs; so that the display in the Shiny app is dynamically updated based on user input or selection. The input object, which is passed to the shinyServerfunction allows the user to access the app’s input fields. It is a list-like object that contains all the input data sent from the browser, named according to the input ID. Unlike a typical list, input objects are read-only. If you attempt to modify an input inside the server function, you’ll get an error. The input can only be set by the user. This is done by creating a reactive expression, where a normal expression is passed into reactive. To read from an input, you must be in a reactive context created by a function like renderText() or reactive(). To allow reactive values or inputs to be viewed in an app, they need to be assigned to the output object. Like the input object, it is also a list-like object. It typically works with a renderfunction like renderTable. The renderfunction performs the following two operations: It sets up a reactive context that is used to automatically associate inputs with outputs.It converts the R code output into HTML code to allow it to be displayed on an app. It sets up a reactive context that is used to automatically associate inputs with outputs. It converts the R code output into HTML code to allow it to be displayed on an app. Reactive expressions are used to split the code within the app into sizeable code chunks that not only reduce code duplication but also avoid re-computation. In the below example, the reactive code receives four inputs from the user, which are then used to output results from an independent-samples t-test. server <- function(input, output) {x1 <- reactive(rnorm(input$n1, input$mean1, input$sd1))x2 <- reactive(rnorm(input$n2, input$mean2, input$sd2))output$ttest <- renderPrint({t.test(x1(), x2())})} Now, that we know some basics let’s build some apps. The app uses a dummy dataset that includes three continuous variables. The requirements for the app are as follows: Produce a scatterplot between two of the three continuous variables in the dataset, where the first variable can’t be graphed against itself.User can select the x and y-variables for plottingUser can select the formula for plotting (“y~x”, “y~poly(x,2)”, “y~log(x)”).The categorical variable selected is used to colour the points the scatterplotThe user can select the number of rows (sample size), ranging from 1 to 1,000 for plotting. Produce a scatterplot between two of the three continuous variables in the dataset, where the first variable can’t be graphed against itself. User can select the x and y-variables for plotting User can select the formula for plotting (“y~x”, “y~poly(x,2)”, “y~log(x)”). The categorical variable selected is used to colour the points the scatterplot The user can select the number of rows (sample size), ranging from 1 to 1,000 for plotting. #Load librarieslibrary(shiny)library(ggplot2)#Create dummy datasetk<-1000set.seed(999)data<-data.frame(id=1:k)data$gest.age<-round(rnorm(k,34,.5),1)data$gender<-factor(rbinom(k,1,.5),labels=c("female","male"))z = -1.5+((((data$gest.age-mean(data$gest.age)))/sd(data$gest.age))*-1.5)pr = 1/(1+exp(-z))data$mat.smoke = factor(rbinom(k,1,pr))data$bwt<- round(-3+data$gest.age*0.15+ ((as.numeric(data$mat.smoke)-1)*-.1)+ ((as.numeric(data$mat.smoke)-1))*((data$gest.age*-0.12))+ (((as.numeric(data$mat.smoke)-1))*(4))+ ((as.numeric(data$gender)-1)*.2)+rnorm(k,0,0.1),3)data$mat.bmi<-round((122+((data$bwt*10)+((data$bwt^8)*2))/200)+ rnorm(k,0,1.5)+(data$gest.age*-3),1)rm(z, pr, k)#Define UIui <- fluidPage( #1. Select 1 of 3 continuous variables as y-variable and x-variable selectInput("y_varb", label="Y-axis variable",choices=names(data)[c(-1,-3,-4)]), selectInput("x_varb", label="X-axis variable", choices=NULL), #2. Colour points using categorical variable (1 of 4 options) selectInput("cat_colour", label="Select Categorical variable", choices=names(data)[c(-1,-2,-5,-6)]), #3. Select sample size selectInput("sample_sz", label = "Select sample size", choices = c(1:1000)), #4. Three different types of linear regression plots selectInput("formula", label="Formula", choices=c("y~x", "y~poly(x,2)", "y~log(x)")), #5. Reset plot output after each selection plotOutput("plot", dblclick = "plot_reset") )server <- function(input, output) { #1. Register the y-variable selected, the remaining variables are now options for x-variable remaining <- reactive({ names(data)[c(-1,-3,-4,-match(input$y_varb,names(data)))] }) observeEvent(remaining(),{ choices <- remaining() updateSelectInput(session = getDefaultReactiveDomain(),inputId = "x_varb", choices = choices) }) output$plot <- renderPlot({ #Produce scatter plot subset_data<-data[1:input$sample_sz,] ggplot(subset_data, aes_string(input$x_varb, input$y_varb))+ geom_point(aes_string(colour=input$cat_colour))+ geom_smooth(method="lm",formula=input$formula)}, res = 96)}# Run the application shinyApp(ui = ui, server = server) Once the user has selected the inputs, the scatter plot below is generated. There you go, that’s your first web app built. However, let’s break the code down further. App One Explanation The function selectInputis utilised to display the drop-down menus for a user to select the variables for plotting, the variable for colouring the points in the scatter plot, and the sample size. Within the serverfunction, based on the user’s selection for the y-variable, the user’s choices are updated for the x-variable. The observeEventfunction is used to perform an action in response to an event. In this example, it updates the list of x-variables that can be selected for the x-axis; so that the same variable can not be plotted on both the y-axis and the x-axis. The function renderPlotis then used to take all the inputs, x-variable, y-variable, categorical-variable, sample size, and formula to generate or ‘render’ a plot. There you have it, your first Shiny App. Now, what if we wanted the drop-down to be a slider instead. You can modify the code by adding this code snippet in. ui <- fluidPage( #3. Select sample size # numericInput("sample_sz", "Input sample size", 10000), sliderInput(inputId = "sample_sz", label = "Select sample size:", min = 1, max = 10000, value = 1)) The output will then look like what’s displayed in Now, let’s move onto the next example which is slightly more complicated. In this app, we are looking at a dataset that looks at five life-threatening outcomes as a result of the COVID-19 infection. We want the app to do the following: Allow the user to select one of the five outcomes as an inputCompare the different counties by the selected outcome in a forest plotIf a user selects a county in the plot, then another forest plot should be generated that shows all five outcomes for the selected country.Display an error message for missing values. Allow the user to select one of the five outcomes as an input Compare the different counties by the selected outcome in a forest plot If a user selects a county in the plot, then another forest plot should be generated that shows all five outcomes for the selected country. Display an error message for missing values. #Load librarieslibrary(shiny)library(ggplot2)library(exactci)#import the data and restrict the data to variables and patients of interestpatient.data<-read.csv("Synthea_patient_covid.csv", na.strings = "")cons.data<-read.csv("Synthea_conditions_covid.csv", na.strings = "")data<-merge(cons.data, patient.data)data<-data[which(data$covid_status==1),] data<-data[,c(12,14,65,96,165,194)]#Get the state average for each outcomestate.average<-apply(data[,-6],MARGIN=2,FUN=mean)#Make better names for the outcomesnames<-c("pulmonary embolism", "respiratory failure", "dyspnea", "hypoxemia", "sepsis")#Calculate and aggregate the obs and exp by outcome and countydata$sample.size<-1list<-list()for (i in 1:5) { list[[i]]<-cbind(outcome=rep(names[i],length(unique(data$COUNTY))), aggregate(data[,i]~COUNTY, sum,data=data), exp=round(aggregate(sample.size~COUNTY, sum,data=data)[,2] *state.average[i],2))}plot.data<-do.call(rbind,list)names(plot.data)[3]<-"obs"#Lastly, obtain the smr (called est), lci and uci for each row#Add confidence limitsplot.data$est<-NAplot.data$lci<-NAplot.data$uci<-NA#Calculate the confidence intervals for each row with a for loop and add them to the plot.datafor (i in 1:nrow(plot.data)){ plot.data[i,5]<-as.numeric(poisson.exact(plot.data[i,3],plot.data[i,4], tsmethod = "central")$estimate) plot.data[i,6]<-as.numeric(poisson.exact(plot.data[i,3],plot.data[i,4], tsmethod = "central")$conf.int[1]) plot.data[i,7]<-as.numeric(poisson.exact(plot.data[i,3],plot.data[i,4], tsmethod = "central")$conf.int[2])}# Define UI for application ui <- fluidPage( selectInput("outcome_var", label="Outcome",unique(plot.data$outcome)), plotOutput("plot", click = "plot_click"), plotOutput("plot2"))server <- function(input, output) { output$plot <- renderPlot({#Output error message for missing values validate( need( nrow(plot.data) > 0, "Data insufficient for plot") ) ggplot(subset(plot.data,outcome==input$outcome_var), aes(x = COUNTY,y = est, ymin = pmax(0.25,lci), ymax = pmin(2.25,uci))) + geom_pointrange()+ geom_hline(yintercept =1, linetype=2)+ coord_flip() + xlab("")+ ylab("SMR (95% Confidence Interval)")+ theme(legend.position="none")+ ylim(0.25, 2.25) }, res = 96) #Output error message for missing values #modify this plot so it's the same forest plot as above but shows all outcomes for the selected county output$plot2 <- renderPlot({validate( need( nrow(plot.data) > 0, "Data insufficient for plot as it contains a missing value") ) #Output error message for trying to round a value when it doesn't exist/missing validate( need( as.numeric(input$plot_click$y), "Non-numeric y-value selected") ) forestp_data<-plot.data[which(plot.data$COUNTY==names(table(plot.data$COUNTY))[round(input$plot_click$y,0)]),] ggplot(forestp_data, aes(x = outcome,y = est, ymin = pmax(0.25,lci), ymax = pmin(2.25,uci))) + geom_pointrange()+ geom_hline(yintercept =1, linetype=2)+ coord_flip() + xlab("")+ ylab("SMR (95% Confidence Interval)")+ theme(legend.position="none")+ ylim(0.25, 2.25) }) }# Run the application shinyApp(ui = ui, server = server) App Two Explanation In this app, like App One, the user makes a selection for an outcome from the drop-down box. This results in a forest plot. The calculations for this forest plot are done outside of the Shiny user interface. The tricky bit in this application is to build a reactive second plot in response to the user clicked county in the first plot. This reactivity happens in the server function using this line plot.data[which(plot.data$COUNTY==names(table(plot.data$COUNTY))[round(input$plot_click$y,0)]),] where we checked to see which county had been selected in order to display the second forest plot for all five outcomes. In the app, an error message is displayed using the validatefunction where if there is missing data, then there is an error displayed due to this piece of syntax: [round(input$plot_click$y,0)],] The final web app’s objective is to allow the user to plot the relationship between the variables in the data set. Some variables are categorical, while others are continuous. When plotting two continuous variables, the user should only be able to plot them on a scatter plot. When one continuous variable and one categorical variable is selected, the user should only be able to make a box plot. The user should not be able to make a plot with two categorical variables. The app should only display one plot at a time, based on the user’s selection. #Load librarieslibrary(shiny)library(ggplot2)#import datasetwd("C:/Users/User/Desktop/Synthea")patient.data<-read.csv("Synthea_patient_covid.csv", na.strings = "")obs.data<-read.csv("Synthea_observations_covid.csv", na.strings = "")patient.data$dob<-as.Date(patient.data$BIRTHDATE, tryFormats = "%d/%m/%Y")patient.data$enc.date<-as.Date(patient.data$DATE, tryFormats = "%d/%m/%Y")patient.data$age<-as.numeric((patient.data$enc.date-patient.data$dob)/365.25)data<-merge(obs.data, patient.data)data<-na.omit(data[,c(4,5,10:12,20,24,32,18,15,23,31,33,48:51,60)])names(data)<-substr(names(data),1,10)data$covid_stat<-as.factor(data$covid_stat)data$dead<-as.factor(data$dead)# Define UI for application ui <- fluidPage( #1. Select 1 of many continuous variables as y-variable selectInput("y_varb", label="Y-axis variable",choices=names(data)[c(-1,-2,-14,-15,-16,-17)]), #2 Select any variable in dataset as x-variable selectInput("x_varb", label="X-axis variable", choices=names(data)), #3. Reset plot1 output after each selection plotOutput("plot", dblclick = "plot_reset"))server <- function(input, output) { remaining <- reactive({ names(data)[-match(input$y_varb,names(data))] }) observeEvent(remaining(),{ choices <- remaining() updateSelectInput(session = getDefaultReactiveDomain(),inputId = "x_varb", choices = choices) }) output$plot <- renderPlot({if ( is.numeric(data[[input$x_varb]]) ) { ggplot(data, aes_string(input$x_varb, input$y_varb)) + geom_point() } else { ggplot(data, aes_string(input$x_varb, input$y_varb)) + stat_boxplot() }}) }# Run the application shinyApp(ui = ui, server = server) App Three Explanation The tricky bit in this app is using the if-else condition within renderPlotso that only one of the two types of plots (scatter plot or box plot) can be selected. Furthermore, when you want to check the class of the input$x_varb the use of double square brackets (list) is required, data[[input$x_varb]],otherwise the output will always be character. So, there you have it, three simple apps. Let’s recap very quickly on what was covered in this blog article. Structure of an R Shiny app Linking inputs and outputs Creating a dynamic user interface by using reactive() and observeEvent Displaying error messages using validate
[ { "code": null, "e": 360, "s": 172, "text": "Shiny is an R package that allows programmers to build web applications within R. For someone like me, who found building GUI applications in Java really hard, Shiny makes it much easier." }, { "code": null, "e": 509, "s": 360, "text":...
How to detect integer overflow in C++?
The only safe way is to check for overflow before it occurs. There are some hacky ways of checking for integer overflow though. So if you're aiming for detecting overflow in unsigned int addition, you can check if the result is actually lesser than either value-added. So for example, unsigned int x, y; unsigned int value = x + y; bool overflow = value < x; // Alternatively "value < y" should also work This is because if x and y are both unsigned ints if added and they overflow, their values can't be greater than either of them as it would need to be greater than max possible unsigned int to be able to wrap around and get ahead of these values. Another way is to try and access the Overflow flag in your CPU. Some compilers provide access to it which you could then test but this isn't standard. There are other ways to achieve this but they provide estimates only. You can check them out here − https://stackoverflow.com/a/199455/3719089
[ { "code": null, "e": 1347, "s": 1062, "text": "The only safe way is to check for overflow before it occurs. There are some hacky ways of checking for integer overflow though. So if you're aiming for detecting overflow in unsigned int addition, you can check if the result is actually lesser than eith...
GATE | GATE CS 2021 | Set 2 | Question 50 - GeeksforGeeks
23 May, 2021 Suppose the following functional dependencies hold on a relation U with attributes P,Q,R,S, and T: P → QR RS → T Which of the following functional dependencies can be inferred from the above functional dependencies?(A) PS → T(B) R → T(C) P → R(D) PS → QAnswer: (A) (C) (D)Explanation: P-> QR RS-> T From P->QR we derived P->Q and P->R. After getting R from P we derive PS->T . We directly derive Q from P so PS->Q also holds true. Correct Option A , C, D Quiz of this Question 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-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE-CS-2006 | Question 47 GATE | GATE MOCK 2017 | Question 24 GATE | GATE-CS-2000 | Question 41 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25805, "s": 25777, "text": "\n23 May, 2021" }, { "code": null, "e": 25904, "s": 25805, "text": "Suppose the following functional dependencies hold on a relation U with attributes P,Q,R,S, and T:" }, { "code": null, "e": 25919, "s": 25904, ...
Program to print Swastika Pattern - GeeksforGeeks
19 Apr, 2021 Given the number of rows and columns, print the corresponding swastika pattern using loops. Note : The number of rows and columns should be same and an odd number. This will generate a perfect swastika pattern. Examples : Input : row = 7, column = 7 Output: * * * * * * * * * * * * * * * * * * * * * * * * * Input : row = 11, column = 11 Output : * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Recommended: Please try your approach on {IDE} first, before moving on solutionBelow is the implementation to print swastika pattern. C++ Java Python3 C# PHP Javascript // C++ implementation to// print swastika pattern#include <bits/stdc++.h>using namespace std; // function to print swastikavoid swastika(int row, int col){for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { // checking if i < row/2 if (i < row / 2) { // checking if j<col/2 if (j < col / 2) { // print '*' if j=0 if (j == 0) cout << "*"; // else print space else cout << " " << " "; } // check if j=col/2 else if (j == col / 2) cout << " *"; else { // if i=0 then first row will have '*' if (i == 0) cout << " *"; } } else if (i == row / 2) cout << "* "; else { // middle column and last column will have '*' // after i > row/2 if (j == col / 2 || j == col - 1) cout << "* "; // last row else if (i == row - 1) { // last row will be have '*' if // j <= col/2 or if it is last column if (j <= col / 2 || j == col - 1) cout << "* "; else cout << " " << " "; } else cout << " " << " "; } } cout << "\n";}} // driver codeint main(){ // odd number of row and column // to get perfect swastika int row = 7, col = 7; // function calling swastika(row, col); return 0;} // Java implementation to// print swastika pattern class GFG{ // function to print swastika static void swastika(int row, int col) { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { // checking if i < row/2 if (i < row / 2) { // checking if j<col/2 if (j < col / 2) { // print '*' if j=0 if (j == 0) System.out.print("*"); // else print space else System.out.print(" "+ " "); } // check if j=col/2 else if (j == col / 2) System.out.print(" *"); else { // if i=0 then first row // will have '*' if (i == 0) System.out.print(" *"); } } else if (i == row / 2) System.out.print("* "); else { // middle column and last column // will have '*' after i > row/2 if (j == col / 2 || j == col - 1) System.out.print("* "); // last row else if (i == row - 1) { // last row will be have '*' if // j <= col/2 or if it is last column if (j <= col / 2 || j == col - 1) System.out.print("* "); else System.out.print(" "+ " "); } else System.out.print(" "+" "); } } System.out.print("\n"); } } // Driver code public static void main (String[] args) { // odd number of row and column // to get perfect swastika int row = 7, col = 7; // function calling swastika(row, col); }} // This code is contributed by Anant Agarwal. # Python3 implementation to print swastika pattern # Function to print swastikadef swastika(row,col): for i in range(row): for j in range(col): # checking if i < row/2 if(i < row // 2): # checking if j<col/2 if (j < col // 2): # print '*' if j=0 if (j == 0): print("*", end = "") # else print space else: print(" ", end = " ") # check if j=col/2 elif (j == col // 2): print(" *", end = "") else: # if i=0 then first row will have '*' if (i == 0): print(" *", end = "") elif (i == row // 2): print("* ", end = "") else: # middle column and last column will # have '*' after i > row/2 if (j == col // 2 or j == col - 1): print("* ", end = "") # last row elif (i == row - 1): # last row will be have '*' if # j <= col/2 or if it is last column if (j <= col // 2 or j == col - 1): print("* ", end = "") else: print(" ", end = " ") else: print(" ", end = " ") print() # Driver code # odd number of row and column# to get perfect swastikarow = 7; col = 7 # Function callingswastika(row, col) # This code is contributed by Azkia Anam. // C# implementation to print swastika patternusing System; class GFG { // function to print swastika static void swastika(int row, int col) { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { // checking if i < row/2 if (i < row / 2) { // checking if j < col/2 if (j < col / 2) { // print '*' if j = 0 if (j == 0) Console.Write("*"); // else print space else Console.Write(" "+ " "); } // check if j = col/2 else if (j == col / 2) Console.Write(" *"); else { // if i=0 then first row // will have '*' if (i == 0) Console.Write(" *"); } } else if (i == row / 2) Console.Write("* "); else { // middle column and last column // will have '*' after i > row/2 if (j == col / 2 || j == col - 1) Console.Write("* "); // last row else if (i == row - 1) { // last row will be have '*' if // j <= col/2 or if it is last column if (j <= col / 2 || j == col - 1) Console.Write("* "); else Console.Write(" "+ " "); } else Console.Write(" "+" "); } } Console.WriteLine(); } } // Driver code public static void Main () { // odd number of row and column // to get perfect swastika int row = 7, col = 7; // function calling swastika(row, col); }} // This code is contributed by vt_m. <?php// PHP implementation to// print swastika pattern // function to print swastikafunction swastika($row, $col){for ($i = 0; $i < $row; $i++){ for ($j = 0; $j < $col; $j++) { // checking if i < row/2 if ($i < floor($row / 2)) { // checking if j<col/2 if ($j < floor($col / 2)) { // print '*' if j=0 if ($j == 0) echo "*"; // else print space else echo " " . " "; } // check if j=col/2 else if ($j == floor($col / 2)) echo " *"; else { // if i=0 then first // row will have '*' if ($i == 0) echo " *"; } } else if ($i == floor($row / 2)) echo "* "; else { // middle column and last // column will have '*' // after i > row/2 if ($j == floor($col / 2 )|| $j == $col - 1) echo "* "; // last row else if ($i == $row - 1) { // last row will be have // '*' if j <= col/2 or // if it is last column if ($j <= floor($col / 2) || $j == $col - 1) echo "* "; else echo " " . " "; } else echo " " . " "; } } echo "\n";}} // Driver Code // odd number of row// and column to get// perfect swastika$row = 7;$col = 7; // function callingswastika($row, $col); // This code is contributed by ajit?> <script> // JavaScript implementation to // print swastika pattern // function to print swastika function swastika(row, col) { for (var i = 0; i < row; i++) { for (var j = 0; j < col; j++) { // checking if i < row/2 if (i < Math.floor(row / 2)) { // checking if j<col/2 if (j < Math.floor(col / 2)) { // print '*' if j=0 if (j == 0) document.write("*"); // else print space else document.write(" " + " "); } // check if j=col/2 else if (j == Math.floor(col / 2)) document.write(" *"); else { // if i=0 then first row will have '*' if (i == 0) document.write(" *"); } } else if (i == Math.floor(row / 2)) document.write("* "); else { // middle column and last column will have '*' // after i > row/2 if (j == Math.floor(col / 2) || j == col - 1) document.write("* "); // last row else if (i == row - 1) { // last row will be have '*' if // j <= col/2 or if it is last column if (j <= Math.floor(col / 2) || j == col - 1) document.write("* "); else document.write(" " + " "); } else document.write(" " + " "); } } document.write("<br>"); } } // driver code // odd number of row and column // to get perfect swastika var row = 7, col = 7; // function calling swastika(row, col); // This code is contributed by rdtank. </script> Output: * * * * * * * * * * * * * * * * * * * * * * * * * jit_t rdtank pattern-printing C Programs C++ Programs pattern-printing Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Header files in C/C++ and its uses C Program to read contents of Whole File How to return multiple values from a function in C or C++? How to Append a Character to a String in C C program to sort an array in ascending order Header files in C/C++ and its uses C++ Program for QuickSort How to return multiple values from a function in C or C++? Shallow Copy and Deep Copy in C++ Sorting a Map by value in C++ STL
[ { "code": null, "e": 25883, "s": 25855, "text": "\n19 Apr, 2021" }, { "code": null, "e": 26107, "s": 25883, "text": "Given the number of rows and columns, print the corresponding swastika pattern using loops. Note : The number of rows and columns should be same and an odd number....
Design a stack that supports getMin() in O(1) time and O(1) extra space - GeeksforGeeks
11 May, 2022 Question: Design a Data Structure SpecialStack that supports all the stack operations like push(), pop(), isEmpty(), isFull() and an additional operation getMin() which should return minimum element from the SpecialStack. All these operations of SpecialStack must be O(1). To implement SpecialStack, you should only use standard Stack data structure and no other data structure like arrays, list, .. etc Example: Consider the following SpecialStack 16 --> TOP 15 29 19 18 When getMin() is called it should return 15, which is the minimum element in the current stack. If we do pop two times on stack, the stack becomes 29 --> TOP 19 18 When getMin() is called, it should return 18 which is the minimum in the current stack. An approach that uses O(1) time and O(n) extra space is discussed here.In this article, a new approach is discussed that supports minimum with O(1) extra space. We define a variable minEle that stores the current minimum element in the stack. Now the interesting part is, how to handle the case when minimum element is removed. To handle this, we push “2x – minEle” into the stack instead of x so that previous minimum element can be retrieved using current minEle and its value stored in stack. Below are detailed steps and explanation of working.Push(x) : Inserts x at the top of stack. If stack is empty, insert x into the stack and make minEle equal to x. If stack is not empty, compare x with minEle. Two cases arise:If x is greater than or equal to minEle, simply insert x.If x is less than minEle, insert (2*x – minEle) into the stack and make minEle equal to x. For example, let previous minEle was 3. Now we want to insert 2. We update minEle as 2 and insert 2*2 – 3 = 1 into the stack. If x is greater than or equal to minEle, simply insert x. If x is less than minEle, insert (2*x – minEle) into the stack and make minEle equal to x. For example, let previous minEle was 3. Now we want to insert 2. We update minEle as 2 and insert 2*2 – 3 = 1 into the stack. Pop() : Removes an element from top of stack. Remove element from top. Let the removed element be y. Two cases arise:If y is greater than or equal to minEle, the minimum element in the stack is still minEle.If y is less than minEle, the minimum element now becomes (2*minEle – y), so update (minEle = 2*minEle – y). This is where we retrieve previous minimum from current minimum and its value in stack. For example, let the element to be removed be 1 and minEle be 2. We remove 1 and update minEle as 2*2 – 1 = 3. If y is greater than or equal to minEle, the minimum element in the stack is still minEle. If y is less than minEle, the minimum element now becomes (2*minEle – y), so update (minEle = 2*minEle – y). This is where we retrieve previous minimum from current minimum and its value in stack. For example, let the element to be removed be 1 and minEle be 2. We remove 1 and update minEle as 2*2 – 1 = 3. Important Points: Stack doesn’t hold actual value of an element if it is minimum so far. Actual minimum element is always stored in minEle Illustration Push(x) Number to be Inserted: 3, Stack is empty, so insert 3 into stack and minEle = 3. Number to be Inserted: 5, Stack is not empty, 5> minEle, insert 5 into stack and minEle = 3. Number to be Inserted: 2, Stack is not empty, 2< minEle, insert (2*2-3 = 1) into stack and minEle = 2. Number to be Inserted: 1, Stack is not empty, 1< minEle, insert (2*1-2 = 0) into stack and minEle = 1. Number to be Inserted: 1, Stack is not empty, 1 = minEle, insert 1 into stack and minEle = 1. Number to be Inserted: -1, Stack is not empty, -1 < minEle, insert (2*-1 – 1 = -3) into stack and minEle = -1. Pop() Initially the minimum element minEle in the stack is -1. Number removed: -3, Since -3 is less than the minimum element the original number being removed is minEle which is -1, and the new minEle = 2*-1 – (-3) = 1 Number removed: 1, 1 == minEle, so number removed is 1 and minEle is still equal to 1. Number removed: 0, 0< minEle, original number is minEle which is 1 and new minEle = 2*1 – 0 = 2. Number removed: 1, 1< minEle, original number is minEle which is 2 and new minEle = 2*2 – 1 = 3. Number removed: 5, 5> minEle, original number is 5 and minEle is still 3 C++ Java Python 3 C# // C++ program to implement a stack that supports// getMinimum() in O(1) time and O(1) extra space.#include <bits/stdc++.h>using namespace std; // A user defined stack that supports getMin() in// addition to push() and pop()struct MyStack{ stack<int> s; int minEle; // Prints minimum element of MyStack void getMin() { if (s.empty()) cout << "Stack is empty\n"; // variable minEle stores the minimum element // in the stack. else cout <<"Minimum Element in the stack is: " << minEle << "\n"; } // Prints top element of MyStack void peek() { if (s.empty()) { cout << "Stack is empty "; return; } int t = s.top(); // Top element. cout << "Top Most Element is: "; // If t < minEle means minEle stores // value of t. (t < minEle)? cout << minEle: cout << t; } // Remove the top element from MyStack void pop() { if (s.empty()) { cout << "Stack is empty\n"; return; } cout << "Top Most Element Removed: "; int t = s.top(); s.pop(); // Minimum will change as the minimum element // of the stack is being removed. if (t < minEle) { cout << minEle << "\n"; minEle = 2*minEle - t; } else cout << t << "\n"; } // Removes top element from MyStack void push(int x) { // Insert new number into the stack if (s.empty()) { minEle = x; s.push(x); cout << "Number Inserted: " << x << "\n"; return; } // If new number is less than minEle else if (x < minEle) { s.push(2*x - minEle); minEle = x; } else s.push(x); cout << "Number Inserted: " << x << "\n"; }}; // Driver Codeint main(){ MyStack s; s.push(3); s.push(5); s.getMin(); s.push(2); s.push(1); s.getMin(); s.pop(); s.getMin(); s.pop(); s.peek(); return 0;} // Java program to implement a stack that supports// getMinimum() in O(1) time and O(1) extra space.import java.util.*; // A user defined stack that supports getMin() in// addition to push() and pop()class MyStack{ Stack<Integer> s; Integer minEle; // Constructor MyStack() { s = new Stack<Integer>(); } // Prints minimum element of MyStack void getMin() { // Get the minimum number in the entire stack if (s.isEmpty()) System.out.println("Stack is empty"); // variable minEle stores the minimum element // in the stack. else System.out.println("Minimum Element in the " + " stack is: " + minEle); } // prints top element of MyStack void peek() { if (s.isEmpty()) { System.out.println("Stack is empty "); return; } Integer t = s.peek(); // Top element. System.out.print("Top Most Element is: "); // If t < minEle means minEle stores // value of t. if (t < minEle) System.out.println(minEle); else System.out.println(t); } // Removes the top element from MyStack void pop() { if (s.isEmpty()) { System.out.println("Stack is empty"); return; } System.out.print("Top Most Element Removed: "); Integer t = s.pop(); // Minimum will change as the minimum element // of the stack is being removed. if (t < minEle) { System.out.println(minEle); minEle = 2*minEle - t; } else System.out.println(t); } // Insert new number into MyStack void push(Integer x) { if (s.isEmpty()) { minEle = x; s.push(x); System.out.println("Number Inserted: " + x); return; } // If new number is less than original minEle if (x < minEle) { s.push(2*x - minEle); minEle = x; } else s.push(x); System.out.println("Number Inserted: " + x); }}; // Driver Codepublic class Main{ public static void main(String[] args) { MyStack s = new MyStack(); s.push(3); s.push(5); s.getMin(); s.push(2); s.push(1); s.getMin(); s.pop(); s.getMin(); s.pop(); s.peek(); }} # Class to make a Node class Node: # Constructor which assign argument to nade's value def __init__(self, value): self.value = value self.next = None # This method returns the string representation of the object. def __str__(self): return "Node({})".format(self.value) # __repr__ is same as __str__ __repr__ = __str__ class Stack: # Stack Constructor initialise top of stack and counter. def __init__(self): self.top = None self.count = 0 self.minimum = None # This method returns the string representation of the object (stack). def __str__(self): temp = self.top out = [] while temp: out.append(str(temp.value)) temp = temp.next out = '\n'.join(out) return ('Top {} \n\nStack :\n{}'.format(self.top,out)) # __repr__ is same as __str__ __repr__=__str__ # This method is used to get minimum element of stack def getMin(self): if self.top is None: return "Stack is empty" else: print("Minimum Element in the stack is: {}" .format(self.minimum)) # Method to check if Stack is Empty or not def isEmpty(self): # If top equals to None then stack is empty if self.top == None: return True else: # If top not equal to None then stack is empty return False # This method returns length of stack def __len__(self): self.count = 0 tempNode = self.top while tempNode: tempNode = tempNode.next self.count+=1 return self.count # This method returns top of stack def peek(self): if self.top is None: print ("Stack is empty") else: if self.top.value < self.minimum: print("Top Most Element is: {}" .format(self.minimum)) else: print("Top Most Element is: {}" .format(self.top.value)) # This method is used to add node to stack def push(self,value): if self.top is None: self.top = Node(value) self.minimum = value elif value < self.minimum: temp = (2 * value) - self.minimum new_node = Node(temp) new_node.next = self.top self.top = new_node self.minimum = value else: new_node = Node(value) new_node.next = self.top self.top = new_node print("Number Inserted: {}" .format(value)) # This method is used to pop top of stack def pop(self): if self.top is None: print( "Stack is empty") else: removedNode = self.top.value self.top = self.top.next if removedNode < self.minimum: print ("Top Most Element Removed :{} " .format(self.minimum)) self.minimum = ( ( 2 * self.minimum ) - removedNode ) else: print ("Top Most Element Removed : {}" .format(removedNode)) # Driver program to test above class stack = Stack() stack.push(3)stack.push(5) stack.getMin()stack.push(2)stack.push(1)stack.getMin() stack.pop()stack.getMin()stack.pop() stack.peek() # This code is contributed by Blinkii // C# program to implement a stack // that supports getMinimum() in O(1) // time and O(1) extra space.using System;using System.Collections; // A user defined stack that supports // getMin() in addition to Push() and Pop()public class MyStack{ public Stack s; public int minEle; // Constructor public MyStack() { s = new Stack(); } // Prints minimum element of MyStack public void getMin() { // Get the minimum number // in the entire stack if (s.Count==0) Console.WriteLine("Stack is empty"); // variable minEle stores the minimum // element in the stack. else Console.WriteLine("Minimum Element in the " + " stack is: " + minEle); } // prints top element of MyStack public void Peek() { if (s.Count==0) { Console.WriteLine("Stack is empty "); return; } int t =(int)s.Peek(); // Top element. Console.Write("Top Most Element is: "); // If t < minEle means minEle stores // value of t. if (t < minEle) Console.WriteLine(minEle); else Console.WriteLine(t); } // Removes the top element from MyStack public void Pop() { if (s.Count==0) { Console.WriteLine("Stack is empty"); return; } Console.Write("Top Most Element Removed: "); int t = (int)s.Pop(); // Minimum will change as the minimum element // of the stack is being removed. if (t < minEle) { Console.WriteLine(minEle); minEle = 2*minEle - t; } else Console.WriteLine(t); } // Insert new number into MyStack public void Push(int x) { if (s.Count==0) { minEle = x; s.Push(x); Console.WriteLine("Number Inserted: " + x); return; } // If new number is less than original minEle if (x < minEle) { s.Push(2 * x - minEle); minEle = x; } else s.Push(x); Console.WriteLine("Number Inserted: " + x); }} // Driver Codepublic class main{ public static void Main(String []args) { MyStack s = new MyStack(); s.Push(3); s.Push(5); s.getMin(); s.Push(2); s.Push(1); s.getMin(); s.Pop(); s.getMin(); s.Pop(); s.Peek(); }} // This code is contributed by Arnab Kundu Number Inserted: 3 Number Inserted: 5 Minimum Element in the stack is: 3 Number Inserted: 2 Number Inserted: 1 Minimum Element in the stack is: 1 Top Most Element Removed: 1 Minimum Element in the stack is: 2 Top Most Element Removed: 2 Top Most Element is: 5 Output: Number Inserted: 3 Number Inserted: 5 Minimum Element in the stack is: 3 Number Inserted: 2 Number Inserted: 1 Minimum Element in the stack is: 1 Top Most Element Removed: 1 Minimum Element in the stack is: 2 Top Most Element Removed: 2 Top Most Element is: 5 How does this approach work? When element to be inserted is less than minEle, we insert “2x – minEle”. The important thing to notes is, 2x – minEle will always be less than x (proved below), i.e., new minEle and while popping out this element we will see that something unusual has happened as the popped element is less than the minEle. So we will be updating minEle. How 2*x - minEle is less than x in push()? x < minEle which means x - minEle < 0 // Adding x on both sides x - minEle + x < 0 + x 2*x - minEle < x We can conclude 2*x - minEle < new minEle While popping out, if we find the element(y) less than the current minEle, we find the new minEle = 2*minEle – y. How previous minimum element, prevMinEle is, 2*minEle - y in pop() is y the popped element? // We pushed y as 2x - prevMinEle. Here // prevMinEle is minEle before y was inserted y = 2*x - prevMinEle // Value of minEle was made equal to x minEle = x . new minEle = 2 * minEle - y = 2*x - (2*x - prevMinEle) = prevMinEle // This is what we wanted Exercise: Similar approach can be used to find the maximum element as well. Implement a stack that supports getMax() in O(1) time and constant extra space.This article is contributed by Nikhil Tekwani. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Approach 2: create a class node which has two variables val and min. val will store the actual value that we are going to insert in stack ,where as min will store the min value so far seen upto that node. look into the code for better understanding. Java C# /*package whatever //do not write package name here */ import java.io.*;import java.util.*;class MinStack { Stack<Node> s; class Node{ int val; int min; public Node(int val,int min){ this.val=val; this.min=min; } } /** initialize your data structure here. */ public MinStack() { this.s=new Stack<Node>(); } public void push(int x) { if(s.isEmpty()){ this.s.push(new Node(x,x)); }else{ int min=Math.min(this.s.peek().min,x); this.s.push(new Node(x,min)); } } public int pop() { return this.s.pop().val; } public int top() { return this.s.peek().val; } public int getMin() { return this.s.peek().min; }} class GFG { public static void main (String[] args) { MinStack s=new MinStack(); s.push(-1); s.push(10); s.push(-4); s.push(0); System.out.println(s.getMin()); System.out.println(s.pop()); System.out.println(s.pop()); System.out.println(s.getMin()); }}//time O(1);//it takes o(n) space since every node has to remember min value//this code is contributed by gireeshgudaparthi /*package whatever //do not write package name here */using System;using System.Collections.Generic; public class MinStack { Stack<Node> s; public class Node { public int val; public int min; public Node(int val, int min) { this.val = val; this.min = min; } } /** initialize your data structure here. */ public MinStack() { this.s = new Stack<Node>(); } public void push(int x) { if (s.Count==0) { this.s.Push(new Node(x, x)); } else { int min = Math.Min(this.s.Peek().min, x); this.s.Push(new Node(x, min)); } } public int pop() { return this.s.Pop().val; } public int top() { return this.s.Peek().val; } public int getMin() { return this.s.Peek().min; }} public class GFG { public static void Main(String[] args) { MinStack s = new MinStack(); s.push(-1); s.push(10); s.push(-4); s.push(0); Console.WriteLine(s.getMin()); Console.WriteLine(s.pop()); Console.WriteLine(s.pop()); Console.WriteLine(s.getMin()); }}// time O(1);// it takes o(n) space since every node has to remember min value // This code contributed by gauravrajput1 -4 0 -4 -1 andrew1234 Blinkii gireeshgudaparthi vishalyadavvns12345 GauravRajput1 Adobe Amazon FactSet Flipkart Goldman Sachs GreyOrange Kuliza Microsoft Paytm SAP Labs Sapient Snapdeal STL VMWare Stack Paytm VMWare Flipkart Amazon Microsoft Snapdeal FactSet Goldman Sachs Adobe SAP Labs Sapient Kuliza Stack STL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Queue using Stacks Inorder Tree Traversal without Recursion Program for Tower of Hanoi Stack | Set 4 (Evaluation of Postfix Expression) Implement a stack using singly linked list Next Greater Element Implement Stack using Queues Merge Overlapping Intervals Difference between Stack and Queue Data Structures Iterative Depth First Traversal of Graph
[ { "code": null, "e": 25743, "s": 25715, "text": "\n11 May, 2022" }, { "code": null, "e": 26147, "s": 25743, "text": "Question: Design a Data Structure SpecialStack that supports all the stack operations like push(), pop(), isEmpty(), isFull() and an additional operation getMin() ...
Append the elements of queue in mirror-inverse order - GeeksforGeeks
13 Aug, 2021 Given a queue Q containing N strings, the task is to restructure the queue to double its size such that the second half represents the mirror image of the first half.Examples: Input: Q = {“Hello”, “World”} Output: {“Hello”, “World”, “World”, “Hello”} Explanation: The second half of the output queue is the mirror image of the first half. That is: “Hello”, “World” | “World”, “Hello”Input: Q = {“Hi”, “Geeks”} Output: {“Hi”, “Geeks”, “Geeks”, “Hi”} Approach: On observing carefully, we can say that the second half of the output queue is the reverse of the first half. That is: Store the size of the queue in a variable named size.Push the Queue elements into a stack without actually losing the elements. This can be achieved by using emplace().Repeat the process until size becomes 0.Push the elements of the stack back to the queue. Store the size of the queue in a variable named size. Push the Queue elements into a stack without actually losing the elements. This can be achieved by using emplace(). Repeat the process until size becomes 0. Push the elements of the stack back to the queue. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ program to arrange the// elements of the queue// to the end such that// the halves are mirror// order of each other#include <bits/stdc++.h>using namespace std; // Function to display// the elements of// the queuevoid showq(queue<string> q){ // Iterating through the queue // and printing the elements while (!q.empty()) { cout << q.front() << " "; q.pop(); }} // Function to produce mirror elementsvoid mirrorQueue(queue<string>& q){ int size = q.size(); // Defining a stack stack<string> st; // Pushing the elements // of a queue // in a stack without // losing them // from the queue while (size--) { string x = q.front(); // Push the element // to the end of the // queue q.emplace(x); // Push the element // into the stack st.push(x); // Remove the element q.pop(); } // Appending the elements // from the stack // to the queue while (!st.empty()) { string el = st.top(); q.push(el); st.pop(); }} // Driver Codeint main(){ queue<string> q; q.push("Hello"); q.push("World"); mirrorQueue(q); showq(q); return 0;} // Java program to arrange the// elements of the queue// to the end such that// the halves are mirror// order of each otherimport java.util.*;class GFG{ // Function to display// the elements of// the queuestatic void showq(Queue<String> q){ // Iterating through the queue // and printing the elements while (!q.isEmpty()) { System.out.print(q.peek() + " "); q.remove(); }} // Function to produce mirror elementsstatic void mirrorQueue(Queue<String> q){ int size = q.size(); // Defining a stack Stack<String> st = new Stack<>(); // Pushing the elements // of a queue // in a stack without // losing them // from the queue while (size-->0) { String x = q.peek(); // Push the element // to the end of the // queue q.add(x); // Push the element // into the stack st.add(x); // Remove the element q.remove(); } // Appending the elements // from the stack // to the queue while (!st.isEmpty()) { String el = st.peek(); q.add(el); st.pop(); }} // Driver Codepublic static void main(String[] args){ Queue<String> q = new inkedList<String>(); q.add("Hello"); q.add("World"); mirrorQueue(q); showq(q);}} // This code is contributed by gauravrajput1 # Python3 program to arrange the# elements of the queue# to the end such that# the halves are mirror# order of each other # Function to display# the elements of# the queuedef showq(q) : # Iterating through the queue # and printing the elements while (len(q) != 0) : print(q[0] , end = " ") q.pop(0) # Function to produce mirror elementsdef mirrorQueue(q) : size = len(q) # Defining a stack st = [] # Pushing the elements # of a queue # in a stack without # losing them # from the queue while (size > 0) : x = q[0] # Push the element # to the end of the # queue q.append(x) # Push the element # into the stack st.append(x) # Remove the element q.pop(0) size -= 1 # Appending the elements # from the stack # to the queue while (len(st) != 0) : el = st[len(st) - 1] q.append(el) st.pop() q = []q.append("Hello")q.append("World")mirrorQueue(q)showq(q) # This code is contributed by divyeshrabadiya07 // C# program to arrange the// elements of the queue// to the end such that// the halves are mirror// order of each otherusing System;using System.Collections.Generic;class GFG{ // Function to display// the elements of// the queuestatic void showq(Queue<String> q){ // Iterating through the queue // and printing the elements while (q.Count != 0) { Console.Write(q.Peek() + " "); q.Dequeue(); }} // Function to produce mirror elementsstatic void mirrorQueue(Queue<String> q){ int size = q.Count; // Defining a stack Stack<String> st = new Stack<String>(); // Pushing the elements // of a queue // in a stack without // losing them // from the queue while (size --> 0) { String x = q.Peek(); // Push the element // to the end of the // queue q.Enqueue(x); // Push the element // into the stack st.Push(x); // Remove the element q.Dequeue(); } // Appending the elements // from the stack // to the queue while (st.Count != 0) { String el = st.Peek(); q.Enqueue(el); st.Pop(); }} // Driver Codepublic static void Main(String[] args){ Queue<String> q = new Queue<String>(); q.Enqueue("Hello"); q.Enqueue("World"); mirrorQueue(q); showq(q);}} // This code is contributed by Rajput-Ji <script> // JavaScript program to arrange the// elements of the queue// to the end such that// the halves are mirror// order of each other // Function to display// the elements of// the queuefunction showq(q){ // Iterating through the queue // and printing the elements while (q.length!=0) { document.write(q[0] + " "); q.shift(); }} // Function to produce mirror elementsfunction mirrorQueue(q){ size = q.length; // Defining a stack let st = []; // Pushing the elements // of a queue // in a stack without // losing them // from the queue while (size-->0) { let x = q[0]; // Push the element // to the end of the // queue q.push(x); // Push the element // into the stack st.push(x); // Remove the element q.shift(); } // Appending the elements // from the stack // to the queue while (st.length!=0) { let el = st[st.length-1]; q.push(el); st.pop(); }} // Driver Codelet q=[]; q.push("Hello");q.push("World");mirrorQueue(q);showq(q); // This code is contributed by patel2127 </script> Hello World World Hello Time Complexity: O(N), where N is the size of the queueAuxiliary Space: O(N) Akanksha_Rai GauravRajput1 Rajput-Ji divyeshrabadiya07 patel2127 pankajsharmagfg Competitive Programming Data Structures Queue Stack Data Structures Stack Queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Prefix Sum Array - Implementation and Applications in Competitive Programming Ordered Set and GNU C++ PBDS Modulo 10^9+7 (1000000007) What is Competitive Programming and How to Prepare for It? 7 Best Coding Challenge Websites in 2020 SDE SHEET - A Complete Guide for SDE Preparation Top 50 Array Coding Problems for Interviews DSA Sheet by Love Babbar Doubly Linked List | Set 1 (Introduction and Insertion) How to Start Learning DSA?
[ { "code": null, "e": 26139, "s": 26111, "text": "\n13 Aug, 2021" }, { "code": null, "e": 26317, "s": 26139, "text": "Given a queue Q containing N strings, the task is to restructure the queue to double its size such that the second half represents the mirror image of the first ha...
Input/Output from external file in C/C++, Java and Python for Competitive Programming | Set 2 - GeeksforGeeks
19 May, 2017 Prerequisites : Input/Output from external file in C/C++, Java and Python for Competitive Programming In above post, we saw a way to have standard input/output from external file using file handling. In this post, we will see a very easy way to do this. Here we will compile and run our code from terminal or cmd using input and output streams. Windows Environment For Windows, it’s the case of redirection operators to redirect command input and output streams from the default locations to different locations. Redirecting command input (<) : To redirect command input from the keyboard to a file or device, use the < operator.Redirecting command output (>) : To redirect command output from the Command Prompt window to a file or device, use the > operator. Redirecting command input (<) : To redirect command input from the keyboard to a file or device, use the < operator. Redirecting command output (>) : To redirect command output from the Command Prompt window to a file or device, use the > operator. Run the code a.exe < input_file > output_file // A simple C++ code (test_code.cpp) which takes // one string as input and prints the same string// to output#include <iostream>using namespace std; int main(){ string S; cin >> S; cout << S; return 0;} Input from input.txt: GeeksForGeeks Compile & run: g++ test_code.cpp a.exe < input.txt > output.txt Output in output.txt: GeeksForGeeks Linux Environment I/O Redirection in linux: Input and output in the Linux environment are distributed across three streams. These streams are: standard input (stdin): The standard input stream typically carries data from a user to a program. Programs that expect standard input usually receive input from a device, such as a keyboard, but using < we can redirect input from the text file.standard output (stdout): Standard output writes the data that is generated by a program. When the standard output stream is not redirected, it will output text to the terminal. By using > we can redirect output to a text file.3. standard error (stderr): Standard error writes the errors generated by a program that has failed at some point in its execution. Like standard output, the default destination for this stream is the terminal display. standard input (stdin): The standard input stream typically carries data from a user to a program. Programs that expect standard input usually receive input from a device, such as a keyboard, but using < we can redirect input from the text file. standard output (stdout): Standard output writes the data that is generated by a program. When the standard output stream is not redirected, it will output text to the terminal. By using > we can redirect output to a text file. 3. standard error (stderr): Standard error writes the errors generated by a program that has failed at some point in its execution. Like standard output, the default destination for this stream is the terminal display. Linux includes redirection commands for each stream. Overwrite : Commands with a single bracket overwrite the destination’s existing contents. > – standard output < – standard input 2> – standard error Append : Commands with a double bracket do not overwrite the destination’s existing contents. >> – standard output << – standard input 2>> – standard error Here, we will use Overwrite’s command because we don’t need to append the output i.e we only want the output of one single code. Compile C++ code g++ file_name.cpp Run the code ./a.out < input_file > output_file We can similarly give standard input/output from text files for C or Java by first compiling the code and while running the code we give input/output files in given format. For languages like python which don’t require compilation, we do the following python test_code.py < input.txt > output.txt Related Article: Python Input Methods for Competitive Programming References : Microsoft Digital Ocean This article is contributed by Pratik Chhajer. 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. Competitive Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Prefix Sum Array - Implementation and Applications in Competitive Programming Ordered Set and GNU C++ PBDS Modulo 10^9+7 (1000000007) What is Competitive Programming and How to Prepare for It? Bits manipulation (Important tactics) 7 Best Coding Challenge Websites in 2020 Multistage Graph (Shortest Path) Formatted output in Java Algorithm Library | C++ Magicians STL Algorithm Use of FLAG in programming
[ { "code": null, "e": 26203, "s": 26175, "text": "\n19 May, 2017" }, { "code": null, "e": 26305, "s": 26203, "text": "Prerequisites : Input/Output from external file in C/C++, Java and Python for Competitive Programming" }, { "code": null, "e": 26550, "s": 26305, ...
Dynamic Frequency Scaling and Dynamic Voltage Scaling - GeeksforGeeks
01 Nov, 2019 ‘Frequency’ in this context refers to the clock frequency or the frequency of operation of a CPU. So the term Dynamic Frequency Scaling refers to the change of the clock frequency of the CPU during runtime. Now the above definition would instantly give rise to the question, Why do we need to do that? The answer to this question lies at the trade off between Performance and Power Consumption. We know that the performance of a processor depends on 2 metrics, these are: CPU Response TimeThroughput of the CPU CPU Response Time Throughput of the CPU Performance metric is used for the determination of the performance of a Computer depends upon the application of the computer system. For example in case of Personal Computing Systems the Response Time is very important and often is the sole basis for the determination of the performance of the computer.Whereas in case of Servers the throughput i.e. is the amount of work done in a given amount of time is much more important. But, for the purpose of this article when we say ‘Performance’ we will be concerning ourselves only with the Response Time. On one hand we can increase the clock frequency of the CPU to reduce its response time and improve its performance but after a certain limit we need to also increase the voltage input to the CPU to maintain its stability at the high clock frequencies which in turn increases the Power Consumption and Heat Dissipation of the CPU, thereby shortening its lifespan. On the other hand we can reduce the clock frequency of the CPU below the standard values allowing us to undervolt the CPU and hence reduce the amount of Power Consumption by the CPU, but this has a negative impact on the CPU performance. Performance Clock Frequency Power Consumption Clock Frequency Now, Dynamic Frequency Scaling is a technique to balance the performance and Power Consumption. It refers to a continual variation of the clock frequency to optimize performance and Power Consumption of a CPU. Now the manner in which the CPU frequency is scaled is determined by the frequency scaling algorithm used and the present CPU load. These frequency scaling algorithms are part of the Kernel Code. Some of the most common Frequency Scaling Algorithms used in the Linux Kernel are: Performance:This Frequency Scaling Algorithm statically fixes the frequency of the CPU to its highest possible value. This increases the Power Consumption by the CPU Powersave:This Frequency Scaling Algorithm Statically fixes the frequency of the CPU to its lowest possible value. This takes it toll on the performance of the system. Conservative:This Frequency Scaling Algorithm adjusts the frequency of the CPU to a certain minimum possible value so as to keep the CPU load below a certain percentage. This algorithm tries to optimize the power consumption while keeping the power consumption. Akanksha_Rai Computer Organization & Architecture Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Direct Access Media (DMA) Controller in Computer Architecture Architecture of 8085 microprocessor Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard) Pin diagram of 8086 microprocessor Difference between Hardwired and Micro-programmed Control Unit | Set 2 I2C Communication Protocol Memory mapped I/O and Isolated I/O Computer Architecture | Flynn's taxonomy Computer Organization | Different Instruction Cycles Introduction of Control Unit and its Design
[ { "code": null, "e": 26135, "s": 26107, "text": "\n01 Nov, 2019" }, { "code": null, "e": 26342, "s": 26135, "text": "‘Frequency’ in this context refers to the clock frequency or the frequency of operation of a CPU. So the term Dynamic Frequency Scaling refers to the change of the...
Count all rows or those that satisfy some condition in Pandas dataframe - GeeksforGeeks
10 Jul, 2020 Let’s see how to count number of all rows in a Dataframe or rows that satisfy a condition in Pandas. 1) Count all rows in a Pandas Dataframe using Dataframe.shape. Dataframe.shape returns tuple of shape (Rows, columns) of dataframe/series. Let’s create a pandas dataframe. # import pandas library as pdimport pandas as pd # List of Tuplesstudents = [('Ankit', 22, 'Up', 'Geu'), ('Ankita', 31, 'Delhi', 'Gehu'), ('Rahul', 16, 'Tokyo', 'Abes'), ('Simran', 41, 'Delhi', 'Gehu'), ('Shaurya', 33, 'Delhi', 'Geu'), ('Harshita', 35, 'Mumbai', 'Bhu' ), ('Swapnil', 35, 'Mp', 'Geu'), ('Priya', 35, 'Uk', 'Geu'), ('Jeet', 35, 'Guj', 'Gehu'), ('Ananya', 35, 'Up', 'Bhu') ] # Create a DataFrame object from# list of tuples with columns# and indices.details = pd.DataFrame(students, columns =['Name', 'Age', 'Place', 'College'], index =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k']) details Output: Code: Count all rows # import pandas library as pdimport pandas as pd # List of Tuplesstudents = [('Ankit', 22, 'Up', 'Geu'), ('Ankita', 31, 'Delhi', 'Gehu'), ('Rahul', 16, 'Tokyo', 'Abes'), ('Simran', 41, 'Delhi', 'Gehu'), ('Shaurya', 33, 'Delhi', 'Geu'), ('Harshita', 35, 'Mumbai', 'Bhu' ), ('Swapnil', 35, 'Mp', 'Geu'), ('Priya', 35, 'Uk', 'Geu'), ('Jeet', 35, 'Guj', 'Gehu'), ('Ananya', 35, 'Up', 'Bhu') ] # Create a DataFrame object from# list of tuples with columns# and indices.details = pd.DataFrame(students, columns =['Name', 'Age', 'Place', 'College'], index =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k']) # 0th index of tuple returned by shape# attribute give the number# of rows in a given dataframenum_rows = details.shape[0] print('Number of Rows in given dataframe : ', num_rows) Output: Number of Rows in given dataframe : 10 2) Count all rows in a Pandas Dataframe using Dataframe.index. Dataframe.index attribute gives a sequence of index or row labels. Code: import pandas as pd # List of Tuplesstudents = [('Ankit', 22, 'Up', 'Geu'), ('Ankita', 31, 'Delhi', 'Gehu'), ('Rahul', 16, 'Tokyo', 'Abes'), ('Simran', 41, 'Delhi', 'Gehu'), ('Shaurya', 33, 'Delhi', 'Geu'), ('Harshita', 35, 'Mumbai', 'Bhu' ), ('Swapnil', 35, 'Mp', 'Geu'), ('Priya', 35, 'Uk', 'Geu'), ('Jeet', 35, 'Guj', 'Gehu'), ('Ananya', 35, 'Up', 'Bhu') ] # Create a DataFrame object from# list of tuples with columns# and indices.details = pd.DataFrame(students, columns =['Name', 'Age', 'Place', 'College'], index =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k']) # count number of rows in given dataframe # by finding the length of indicesnum_rows = len(details.index) print('Number of Rows in given dataframe : ', num_rows) Output: Number of Rows in given dataframe : 10 3) Count rows in a Pandas Dataframe that satisfies a condition using Dataframe.apply(). Dataframe.apply(), apply function to all the rows of a dataframe to find out if elements of rows satisfies a condition or not, Based on the result it returns a bool series. Code: # import pandas library as pdimport pandas as pd # List of Tuplesstudents = [('Ankit', 22, 'Up', 'Geu'), ('Ankita', 31, 'Delhi', 'Gehu'), ('Rahul', 16, 'Tokyo', 'Abes'), ('Simran', 41, 'Delhi', 'Gehu'), ('Shaurya', 33, 'Delhi', 'Geu'), ('Harshita', 35, 'Mumbai', 'Bhu' ), ('Swapnil', 35, 'Mp', 'Geu'), ('Priya', 35, 'Uk', 'Geu'), ('Jeet', 35, 'Guj', 'Gehu'), ('Ananya', 35, 'Up', 'Bhu') ] # Create a DataFrame object from# list of tuples with columns# and indices.details = pd.DataFrame(students, columns =['Name', 'Age', 'Place', 'College'], index =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k']) # Get a bool series representing which row# satisfies the condition i.e. True for# row in which 'College' is 'Geu'details = details.apply(lambda x : True if x['College'] == "Geu" else False, axis = 1) # Count number of True in the seriesnum_rows = len(details[details == True].index) print('Number of Rows in dataframe in which College is Geu : ', num_rows ) Output: Number of Rows in dataframe in which College is Geu : 4 Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python OOPs Concepts How to Install PIP on Windows ? Bar Plot in Matplotlib Defaultdict in Python Python Classes and Objects Deque in Python Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python - Ways to remove duplicates from list Class method vs Static method in Python
[ { "code": null, "e": 24212, "s": 24184, "text": "\n10 Jul, 2020" }, { "code": null, "e": 24313, "s": 24212, "text": "Let’s see how to count number of all rows in a Dataframe or rows that satisfy a condition in Pandas." }, { "code": null, "e": 24376, "s": 24313, ...
Rfviz: An Interactive Visualization Package for Interpreting Random Forests in R | by Chris Kuchar | Towards Data Science
First, I would just say I am in no way deserving of any credit for this package. That credit deservedly goes to Dr. Leo Breiman and Dr. Adele Cutler, the original creators of this wildly popular and successful algorithm. I am just the lucky student who got to work with Dr. Cutler in my graduate program. Dr. Breiman and Dr. Cutler originally created plots in Java that allow you to visualize and interpret Random Forests. You can look at the original plots and style here: www.stat.berkeley.edu I was fortunate enough to go to Utah State University starting in 2017, where Dr. Cutler was a professor in the Statistics Department. I wanted to do my graduate work in Machine Learning and asked her to be my graduate advisor. She agreed and showed me potential projects. At this point in time I didn’t know she had helped create the Random Forests algorithm. It actually wasn’t until I was about halfway done with the project that I found out from another faculty member. And when I approached her and asked her why she hadn’t told me, she replied with something along the lines of, “Oh well I don’t really like to toot my own horn.” I hope this tells you how down to earth and how kind of a person she is. Anyways, one of the potential projects she showed me was translating some Java plots for interactive visualization and interpretation of Random Forests into R. I chose this project and finished the translation into R in 2018 and published the package to CRAN as Rfviz. Recently, I have been using it in my job and was able to gain, in my opinion, deeper insights beyond what is available through methods such as the Shapley method or Overall Variable Importance Plots. I thought that other people should be know more about the benefits I am experiencing from Dr. Breiman and Dr. Cutler’s work. This is what inspired this article. Random forests (Breiman (2001)) fit a number of trees (typically 500 or more) to regression or classification data. Each tree is fit to a bootstrap sample of the data, so some observations are not included in the fit of each tree (these are called out of bag observations for the tree). Independently at each node of each tree, a relatively small number of predictor variables (called mtry) is randomly chosen and these variables are used to find the best split. The trees are grown deep and not pruned. To predict for a new observation, the observation is passed down all the trees and the predictions are averaged (regression) or voted (classification). A local importance score is obtained for each observation in the data set, for each variable. To obtain the local importance score for observation i and variable j, randomly permute variable j for each of the trees in which observation i is out of bag, and compare the error for the variable-jpermuted data to actual error. The average difference in the errors across all trees for which observation i is out of bag is its local importance score. The (overall) variable importance score for variable j is the average value of its local importance scores over all observations. Proximities are the proportion of time two observations end up in the same terminal node when both observations are out of bag. The proximity scores are obtained for all combinations of pairs of observations, giving a symmetric proximity matrix. Note: It is recommended to use 9 or 10 times more trees when dealing with proximities, since it the the proprotion of when two observations are both out of bag. This is to ensure each observation is able to be compared with the subsequent observations. Parallel coordinate plots are used for plotting observations on a handful of variables. The variables can be discrete or continuous, or even categorical. Each variable has its own axis and these are represented as equally-spaced parallel vertical lines. Usually, the axes extend from the minimum to the maximum of the observed data values although other definitions are possible. A given observation is plotted by connecting its observed value on each of the variables using a piecewise linear function. Static parallel coordinate plots are not particularly good for discovering relationships between variables because the display depends strongly on the order of the variables in the plot. In addition, they suffer very badly from overplotting for large data sets. However, by brushing the plot (highlighting subsets of observations in a contrasting color) parallel coordinate plots can be useful in investigating unusual groups of observations and relating the groups to high/low values of the variables. The predictor variables are plotted in a parallel coordinate plot. The observations are colored according to their value of the response variable. Brushing on this plot allows investigators to examine the input data interactively and look for unusual observations, outliers, or any obvious patterns between the predictors and the response. Often this plot is used in conjunction with the local importance plot, which allows users to focus more heavily on the predictors that are important for a given group of observations. The local importance scores of each observation are plotted in a parallel coordinate plot. Brushing observations with high local importance can allow the user to look at the corresponding variable on the raw input parallel coordinate plot and observe whether the variable has high or low values, allowing an interpretation such as ‘for this group the most important variable is variable j’. This plot allows the user to select groups of observations that appear to be similar and brush them, with the corresponding observations showing up in the two parallel coordinate plots. In classification, for example, if the user brushes a group of observations that are from class 1, they can then examine the local importance parallel coordinate plot. Variables that are important for classifying the group correctly will be highlighted and any variables that have high importance can then be studied in the raw input parallel coordinate plot, to see whether high or low values of the important variable(s) are associated with the group. The data used here is the breast cancer dataset from the library OneR. It is originally from the UCI machine learning repository here. library(OneR)library(rfviz)library(tidyverse)data(breastcancer)bc[is.na(bc)] <- -3data_x <- bc[,-10]data_y <- bc$Classhead(breastcancer) #The prep function. This runs default randomForest() and prepares it for the plotting function.rfprep <- rf_prep(data_x, data_y) Our use case: Let’s say we look at the variable importance plots within Random Forests. varImpPlot(rfprep$rf) Looking at some of the top important variables, we can see that according to Mean Decrease in Gini “Uniformity of Cell Size” and “Uniformity of Cell Shape” are the two most important predictors. But what values of these are most important and to which class? Let’s pull up the visualization tool and dig in to one. #Pull up the visualization toolbcrf <- rf_viz(rfprep, input=TRUE, imp=TRUE, cmd=TRUE) We can see that the three plots are there, along with a “loon inspector” to interact with the plots. Each one of the parallel coordinate plots have a separate scale for each column of data, which is why there is no y-axis ticks or labels. The scales are relative to the max and min of that column. The proximities plot is an XYZ scatterplot. Mainly it is to show in space, how the different classes are grouped within the trees. First, let’s see what color correlates with each class. Within the “loon inspector” on the right, inside the “select” section, click on one of the colors under the subsection “by color”. Let’s click on blue first. Within screenshot 5 you can see the result. We can see that all the data that correlates with the blue class is now highlighted. What class does this correlate with? Back in R, run: bc[bcrf$imp['selected'],'Class'] I know it is rudimentary, but it’s all I have figured out so far to identify the classes quickly and easily. I haven’t figured out how to label the colors on the inspector. Now we know that blue is malignant or class 1, and gray is benign or class 0. Now click anywhere on the visualization tool and will be deselected. We now know that blue is class 1 or those with malignant cancer. Now let’s focus on the “Uniformity of Cell Shape” column, the second most important variable to the Mean Decrease in Gini Overall Importance Plot. Take a look at the Local Importance Scores plot, and the “Uniformity of Cell Shape” column on Screenshot 7. Visually, the values of the local importance scores seem tend to trend higher for class 1/malignant than class 0/benign. Now here is where the deep interpretation and understanding can come. On the Local Importance Scores plot, using your mouse, click and drag up on the column for “Uniformity of Cell Shape” near where you think the separation between the two classes or colors of lines happens. Here is what I selected within Screenshot 8. Within R, run: bc[bcrf$imp['selected'],'Uniformity of Cell Shape']c1 <- bc[bcrf$imp['selected'],]summary(c1$`Uniformity of Cell Shape`)table(c1$Class) Now do the same for the portion of data we did not select within the “Uniformity of Cell Shape” column on the Local Importance Score plot. Here is what I selected in Screenshot 10. And again in R, run: bc[bcrf$imp['selected'],'Uniformity of Cell Shape']c2 <- bc[bcrf$imp['selected'],]summary(c2$`Uniformity of Cell Shape`)table(c2$Class) Now let’s look at the results. Of what we first selected, 198/236 (~84%) were from class 1/malignant. The values of “Uniformity of Cell Shape” have a 1st Quartile of 4, Median of 6, and 3rd Quartile of 9. For the second grouping, 423/466 (91%) were from class 0/benign. The values of “Uniformity of Cell Shape” have a 1st Quartile of 1, Median of 1, and 3rd quartile of 2. From this, we can conclude that for the second most important variable to the prediction, higher values of “Uniformity of Cell Shape”, with a 1st Quartile of 4, Median of 6, and 3rd Quartile of 9, were generally important to a classification of class 1/malignant for Random Forests. I say “generally” because some of class 0/benign were included in that data we selected. On the other hand, lower values of “Uniformity of Cell Shape” with a 1st Quartile of 1, Median of 1, and 3rd quartile of 2 were generally important to class 0 for Random Forests. Even more, we can look at the exact data and save it as objects within R for even more manipulation. For instance, let’s say we didn’t want any of the values of the other class to show up in the summary data for “Uniformity of Cell Shape” for each selection of data. summary(c1$`Uniformity of Cell Shape`[c1$Class!='benign'])summary(c2$`Uniformity of Cell Shape`[c2$Class!='benign']) So what does Rfviz allow us to do? Rfviz allows us deeper interaction and interpretation of Random Forests. We can visualize and interact with the data, quickly see the differences between the classes, and see why and how overall important variables are locally important to each class. For a more in depth tutorial of how to interact with the tool, look here. I hope you enjoyed this read, and good luck in your interpretation and inference of Random Forests. References: Breiman, L. 2001. “Random Forests.” Machine Learning. http://www.springerlink.com/index/u0p06167n6173512.pdf. Breiman, L, and A Cutler. 2004. Random Forests. https://www.stat.berkeley.edu/~breiman/RandomForests/cc_graphics.htm. C Beckett, Rfviz: An Interactive Visualization Package for Random Forests in R, 2018, https://chrisbeckett8.github.io/Rfviz.
[ { "code": null, "e": 476, "s": 171, "text": "First, I would just say I am in no way deserving of any credit for this package. That credit deservedly goes to Dr. Leo Breiman and Dr. Adele Cutler, the original creators of this wildly popular and successful algorithm. I am just the lucky student who go...
Leveraging BigQuery with Google Analytics Data | by Sumil Mehta | Towards Data Science
Google Analytics is an amazing tool. It enables you to make the data work for you, get a broader picture, and understand your visitors better. The problem comes when you expect more from this ‘reporting’ tool. I will tell you why you should consider leveraging BigQuery (or a similar tool) along with your Google Analytics data. Table of Content: A. Why Leverage BigQuery with Google Analytics Data? B. Query Google Analytics Data with BigQuery I. How does it work? II. Pr-requisites III. Let’s Query 1. Handling Changes over time: Every website gets experiential changes over time. Along with this, the way you store data will also change. Hence, for an apple to apple comparison, you will need to transform the data into a common view. 2. Data Sampling If you are dependent on Google Analytics, you would know that GA samples its data often. As long as you are not molding the data enough or you are using the out of the box reports, GA will give you 100% accurate data. It’s only when you start filtering your data or increase its cardinality, Google Analytics will start sampling the data proportionally to maintain its speed. *Sampling: During Sampling, GA returns you the metrics based on a smaller sample space instead of the whole pool of data. 3. Lack of Data Manipulation and Transformation Once the data is stored in the analytics servers, you won’t be able to modify the data using formulas or other logic. This is significant because there is always a lot of scope for data classification and transformation for a website with a huge audience and multiple content categories. Additionally, there will several scenarios where you will need to clean the data. These scenarios can be - human errors, implementation gone wrong, bots missed by Google Analytics. If you want to know more about identifying bots missed by Google Analytics, read my article on this topic. BigQuery is a cloud based data warehousing tool that lets you store and analyze petabytes of data at lightning speed. For GA 360 users, Google provides you the option to get the daily data dump for website’s sessions into BigQuery. You can use this data to overcome the limitations of Google Analytics. I. How does it work?: Everyday Google Analytics stores its sessions’ data in BigQuery Servers. This session data is a table where each row is dedicated to a user visit while each column represents a different dimension or metric that can be repeated and nested. For a rough idea: Column A: visitor Id or cookie id, Column B: date of the session. The point where it gets complex is when the table stores all the hits(events), page views and custom dimensions in one row. This is what makes BigQuery different from a flat table system. Everyday Google Analytics stores its sessions’ data in BigQuery Servers. This session data is a table where each row is dedicated to a user visit while each column represents a different dimension or metric that can be repeated and nested. For a rough idea: Column A: visitor Id or cookie id, Column B: date of the session. The point where it gets complex is when the table stores all the hits(events), page views and custom dimensions in one row. This is what makes BigQuery different from a flat table system. 2. This table acts as our input. First, we un-nest and un-stitch this complex nested data by flattening it. And then, we stitch it back according to our needs. 3. Being a proper cloud based ETL tool, it provides us great transformation features and returns un-sampled data at great speed. In the following sections, you will get an in-depth knowledge about How Google Analytics stores and calculate all the reports. Expect some creative ideas to pop in your mind to find answers which Google Analytics cannot provide. The following sections will expect basic knowledge of Google Analytics Metrics and some knowledge of SQL. Here is a great article by Benjamin from ‘LovesData’ to revise Google Analytics Metrics Concepts. Another great tutorial for revising SQL concepts by my favorite tutorial site: W3 School. Here is the detailed schema of Google Analytics data stored in BigQuery. I will first start with the high level and basic metrics like Sessions, Users, etc and then gradually move to more deep and complex metrics. There are two ways to calculate the high level metric: The First way is to query the ‘totals’ record in the table; The Second way is to query the flattened table (resolved complex data structure to a flat table) and apply relevant logic. I will take the second approach for all the metrics in this blog. We will be using this particular dataset for learning purpose Users Users The table contains a field named ‘Full Visitor Id’. This is nothing but the cookie ID that is unique for a browser on a machine. So, if you can find a distinct number of these IDs, you can find the number of Users. SelectCount ( Distinct fullVisitorId) as Usersfrom`bigquery-public-data.google_analytics_sample.ga_sessions_20170801` , UNNEST(hits) AS hits 2. Sessions Along with the field ‘Full Visitor Id’, the table contains fields such as ‘visitNumber’ that is the sequence number of a particular session for that user (Full Visitor id). Also, ‘visitStartTime’ denotes the time when the session was started. If we concatenate these terms and find the distinct count, we will get the number of sessions. SelectCount ( DistinctCASEWHEN totals.visits=1 THENCONCAT( fullvisitorid,"-",CAST(visitNumber AS string),"-",CAST(visitStartTime AS string))End)as Sessionsfrom`bigquery-public-data.google_analytics_sample.ga_sessions_20170801` , UNNEST(hits) AS hits 3. Pageviews For calculating the number of pages viewed, we will use the “hit type” field by counting the number of times there was pageview hit/event in the session. SelectSUM(Case when hits.type="PAGE" then 1 else 0 END)as Pageviewsfrom`bigquery-public-data.google_analytics_sample.ga_sessions_20170801` , UNNEST(hits) AS hits 4. Unique PageViews Unique Pageviews are calculated by ignoring the duplicate pageviews for a session. If Page A has 2 pageviews in a session, the unique pageviews of A will only be 1. Hence, we need a combination of Session Identifier and Page Identifier, and take a unique count of this combination. SelectCount ( Distinct CONCAT( fullvisitorid,"-",CAST(visitNumber AS string),"-",CAST(visitStartTime AS string),"-",hits.page.pagePath))as Unique_Pageviewsfrom`bigquery-public-data.google_analytics_sample.ga_sessions_20170801` , UNNEST(hits) AS hits 5. Bounce Rate Bounces are the sessions that had exactly one interaction event. To calculate this, we will calculate total bounces and divide it by the number of sessions. SELECTPage,( ( bounces / sessions ) * 100 ) AS Bounce_Rate,SessionsFROM (SELECThits.page.pagePath AS Page,Count ( DistinctCASEWHEN totals.visits=1 THENCONCAT( fullvisitorid,"-",CAST(visitNumber AS string),"-",CAST(visitStartTime AS string))End)as Sessions,SUM ( totals.bounces ) AS Bouncesfrom`bigquery-public-data.google_analytics_sample.ga_sessions_20170801` , UNNEST(hits) AS hitsGROUP BYPage )ORDER BYSessions DESC 6. Entrances Entrances are calculated by using a field called isEntrance. This field has the value “TRUE” if the hit is the first one of the session. Selecthits.page.pagePath AS Page,SUM(CASEWHEN hits.isEntrance = TRUE and hits.type="PAGE" AND totals.visits=1 THEN 1ELSE 0END) AS Entrances,from`bigquery-public-data.google_analytics_sample.ga_sessions_20170801` , UNNEST(hits) AS hitsgroup by Page 7. Exits Similarly, there is a field dedicated to exits as well. It is set to TRUE if the hit is the last hit of that session. Selecthits.page.pagePath AS Page,SUM(CASEWHEN hits.isExit = TRUE and hits.type="PAGE" AND totals.visits=1 THEN 1ELSE 0END) AS Exits,from`bigquery-public-data.google_analytics_sample.ga_sessions_20170801` , UNNEST(hits) AS hitsgroup by Page 8. Average Session Duration For calculating the engagement metric, Avg. Session Duration, we will first calculate the total duration of each session. This is done by finding the hit time of the interactive hit in that session. This duration is then aggregated for a dimension such as Channel and divided by the number of sessions. Select Channel, SUM(Total_Session_Duration)/Count(Distinct Session) as Avg_Session_Durationfrom(SelectChannel, Session,MAX(hitTIme)as Total_Session_Durationfrom(SelectchannelGrouping as Channel,case when totals.visits=1 then CONCAT( fullvisitorid ,"-",Cast(visitNumber as string),"-",cast(visitStartTime as string)) end as Session,Case when hits.IsInteraction=TRUE then hits.Time/1000 else 0 end as hitTime,from`bigquery-public-data.google_analytics_sample.ga_sessions_20170801` , UNNEST(hits) AS hits ) group by channel, session)group by Channel 9. Average Time on Page Calculating the average time on a Page is similar to calculating avg. session duration. The major difference is that we aggregate the timestamps of the last interactive hits of the particular page instead of sessions’. select Page, SUM(TIMEOnPage) as TimeOnPage, SUM(Exits) as Exits, SUM(Pageviews) as Pageviews, safe_divide(SUM(TIMEOnPage),(SUM(Pageviews)-Sum(Exits))) as Avg_Time_On_Pagefrom(SELECT Sessions, Page, Pageviews, Case when exit =TRUE then LastInteraction-hitTime else LEAD(hitTime) OVER (PARTITION BY Sessions ORDER BY hitseq) - hitTime end as TimeOnPage, ExitsFROM ( SELECT CASE WHEN totals.visits=1 THEN CONCAT( fullvisitorid,"-",CAST(visitNumber AS string),"-",CAST(visitStartTime AS string)) END AS Sessions, hits.Page.pagePath AS Page, hits.IsExit AS exit, Case when hits.Isexit =TRUE then 1 else 0 end As Exits, hits.hitNUmber as hitSeq, hits.Type AS hitType, hits.time/1000 AS hitTime, CASE WHEN type="PAGE" AND totals.visits=1 THEN 1 ELSE 0 END AS PageViews, MAX( IF (hits.isInteraction =TRUE , hits.time / 1000, 0)) OVER (PARTITION BY fullVisitorId, visitStartTime) AS LastInteraction, from `dm-corp-marketing-001.137933647.ga_sessions_20200803` , UNNEST(hits) AS hits order by Sessions,hitSeq )WHERE hitType='PAGE' ) group by Page order by Pageviews desc 10. Event Based Goal If you want to calculate the total completions of an event based goal, you need to count the number of sessions where that event occurred. The below example counts goal completion for Event Category: Lead Generation and Event Action: Brochure Download. I am using a regex filter instead of ‘equal to’ operator; you can use either in this case. SelectCount( distinctCASE WHEN REGEXP_CONTAINS(hits.eventInfo.eventAction,r'^Brochure Download$') AND REGEXP_CONTAINS(hits.eventInfo.eventCategory,r'^Lead Generation')THEN CONCAT( fullvisitorid,"-", CAST(visitStartTime AS string) ) end)as Goal_Lead_Generationfrom`bigquery-public-data.google_analytics_sample.ga_sessions_20170801` , UNNEST(hits) AS hits 11. Nth() Page Path If you want to see the most common Nth() pages such as the most common 1st page (Landing Page), most common 2nd Page (page after Landing Page) and so on, then this piece of code is for you. You manipulate this code to see different page flows up to Nth() level and Top Page Path levels, and also see these ‘data views’ for particular behavior like conversions, device types etc. SELECT second_page_path, count (distinct SessionIdentity) as Sessions FROM ( SELECT CASE WHEN totals.visits=1 THEN CONCAT( fullvisitorid,"-",CAST(visitNumber AS string),"-",CAST(visitStartTime AS string)) END AS SessionIdentity, CASE WHEN hits.isEntrance=TRUE THEN hits.page.pagePath END AS Landing_Page, CASE WHEN hits.isEntrance = TRUE THEN LEAD( hits.page.pagePath,1) OVER (PARTITION BY fullVisitorId, visitNumber ORDER BY hits.type) ELSE NULL END AS second_page_path, CASE WHEN hits.isEntrance = TRUE THEN LEAD( hits.page.pagePath,2) OVER (PARTITION BY fullVisitorId, visitNumber ORDER BY hits.type) ELSE NULL END AS third_page_path, CASE WHEN hits.isEntrance = TRUE THEN LEAD( hits.page.pagePath,3) OVER (PARTITION BY fullVisitorId, visitNumber ORDER BY hits.type) ELSE NULL END AS fourth_page_path, CASE WHEN hits.isEntrance = TRUE THEN LEAD( hits.page.pagePath,4) OVER (PARTITION BY fullVisitorId, visitNumber ORDER BY hits.type) ELSE NULL END AS fifth_page_path, from`bigquery-public-data.google_analytics_sample.ga_sessions_20170801` , UNNEST(hits) AS hits ORDER BY SessionIdentity, Landing_Page) WHERE SessionIdentity IS NOT NULL AND landing_page IS NOT NULL GROUP BY second_page_path ORDER BY Sessions Desc I will conclude by saying BigQuery is a great tool to leverage with GA data. It provides you the freedom of seeing the data in ways that are not possible to see via Google Analytics. Know the Author: www.sumilmehta.in
[ { "code": null, "e": 315, "s": 172, "text": "Google Analytics is an amazing tool. It enables you to make the data work for you, get a broader picture, and understand your visitors better." }, { "code": null, "e": 501, "s": 315, "text": "The problem comes when you expect more from...
BabelJS - Working with Babel and Webpack
Webpack is a module bundler which packs all modules with dependencies – js, styles, images, etc. into static assets .js, .css, .jpg , .png, etc. Webpack comes with presets which help for compilation into the required form. For example, react preset that helps to get the final output in react form, es2015 or env preset that helps to compile the code in ES5 or 6 or 7, etc. We have used babel 6 in the project setup. In case you want to switch to babel7, install the required packages of babel using @babel/babel-package-name. Here, we will discuss project setup using babel and webpack. Create a folder called and open the same in visual studio IDE. To create the project setup, run npm initbabelwebpack as follows − Here is the package.json created after npm init − Now, we will install the necessary packages we need to work with babel and webpack. npm install --save-dev webpack npm install --save-dev webpack-dev-server npm install --save-dev babel-core npm install --save-dev babel-loader npm install --save-dev babel-preset-env Here is the Package.json after installation − Now, we will create a webpack.config.js file, which will have all the details to bundle the js files. These files will be compiled it into es5 using babel. To run webpack using server, we use webpack-server. Following are the details added to it − We have added the publish command which will start the webpack-dev-server and will update the path where the final files are stored. Right now the path that we are going to use to update the final files is the /dev folder. To use webpack, we need to run the following command − npm run publish First we need to create the webpack.config.js files. These will have the configuration details for webpack to work. The details in the file are as follows − var path = require('path'); module.exports = { entry: { app: './src/main.js' }, output: { path: path.resolve(__dirname, 'dev'), filename: 'main_bundle.js' }, mode:'development', module: { rules: [ { test: /\.js$/, include: path.resolve(__dirname, 'src'), loader: 'babel-loader', query: { presets: ['env'] } } ] } }; The structure of the file is as shown above. It starts with theh path, which gives the current path details. var path = require('path'); //gives the current path Next is the module.exports object, which has properties entry, output and module. The entry is the start point. Here, we need to give the main js files that has to be compiled. entry: { app: './src/main.js' }, path.resolve(_dirname, ‘src/main.js’) -- will look for the src folder in the directory and main.js in that folder. output: { path: path.resolve(__dirname, 'dev'), filename: 'main_bundle.js' }, Output is an object with path and filename details. Path will hold the folder in which the compiled file will be kept and filename will tell the name of final file to be used in your .html file. module: { rules: [ { test: /\.js$/, include: path.resolve(__dirname, 'src'), loader: 'babel-loader', query: { presets: ['env'] } } ] } Module is an object with details of the rules. It has the following properties − Module is an object with details of the rules. It has the following properties − test include loader query Test will hold details of all the js files ending with .js. It has the pattern, which will look for .js at the end in the entry point given. Test will hold details of all the js files ending with .js. It has the pattern, which will look for .js at the end in the entry point given. Include instructs the folder in use on the files to be looked at. Include instructs the folder in use on the files to be looked at. Loader uses babel-loader for compiling codes. Loader uses babel-loader for compiling codes. Query has property presets, which is an array with value env – es5 or es6 or es7. Query has property presets, which is an array with value env – es5 or es6 or es7. Create folder src and main.js in it; write your js code in ES6. Later, run the command to see it getting compiled to es5 using webpack and babel. src/main.js let add = (a,b) => { return a+b; }; let c = add(10, 20); console.log(c); Run the command − npm run pack The compiled file looks as follows − dev/main_bundle.js !function(e) { var t = {}; function r(n) { if(t[n])return t[n].exports;var o = t[n] = {i:n,l:!1,exports:{}}; return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports } r.m = e,r.c = t,r.d = function(e,t,n) { r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n}) }, r.r = function(e) { "undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0}) }, r.t = function(e,t) { if(1&t&&(e = r(e)),8&t)return e; if(4&t&&"object"==typeof e&&e&&e.__esModule)return e; var n = Object.create(null); if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t) {return e[t]}.bind(null,o)); return n }, r.n = function(e) { var t = e&&e.__esModule?function() {return e.default}:function() {return e}; return r.d(t,"a",t),t }, r.o = function(e,t) {return Object.prototype.hasOwnProperty.call(e,t)}, r.p = "",r(r.s = 0) }([function(e,t,r) {"use strict";var n = function(e,t) {return e+t}(10,20);console.log(n)}]); !function(e) { var t = {}; function r(n) { if(t[n])return t[n].exports; var o = t[n] = {i:n,l:!1,exports:{}}; return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports } r.m = e,r.c = t,r.d = function(e,t,n) { r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n}) }, r.r = function(e) { "undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0}) }, r.t = function(e,t) { if(1&t&&(e=r(e)), 8&t)return e; if(4&t&&"object"==typeof e&&e&&e.__esModule)return e; var n = Object.create(null); if( r.r(n), Object.defineProperty(n,"default",{enumerable:!0,value:e}), 2&t&&"string"!=typeof e ) for(var o in e)r.d(n,o,function(t) {return e[t]}.bind(null,o)); return n }, r.n = function(e) { var t = e&&e.__esModule?function() {return e.default}:function() {return e}; return r.d(t,"a",t),t }, r.o = function(e,t) { return Object.prototype.hasOwnProperty.call(e,t) }, r.p = "",r(r.s = 0) }([function(e,t,r) { "use strict"; var n = function(e,t) {return e+t}(10,20); console.log(n) }]); The code is compiled as shown above. Webpack adds some code which is required internally and the code from main.js is seen at the end. We have consoled the value as shown above. Add the final js file in .html file as follows − <html> <head></head> <body> <script type="text/javascript" src="dev/main_bundle.js"></script> </body> </html> Run the command − npm run publish To check the output, we can open the file in − http://localhost:8080/ We get the console value as shown above. Now let us try to compile to a single file using webpack and babel. We will use webpack to bundle multiple js files into a single file. Babel will be used to compile the es6 code to es5. Now, we have 2 js files in the src/ folder - main.js and Person.js as follows − person.js export class Person { constructor(fname, lname, age, address) { this.fname = fname; this.lname = lname; this.age = age; this.address = address; } get fullname() { return this.fname +"-"+this.lname; } } We have used export to use the details of the Person class. main.js import {Person} from './person' var a = new Person("Siya", "Kapoor", "15", "Mumbai"); var persondet = a.fullname; console.log(persondet); In main.js, we have imported Person from the file path. Note − We do not have to include person.js but just the name of the file. We have created an object of Person class and consoled the details as shown above. Webpack will combine person.js and main.js and update in dev/main_bundle.js as one file. Run the command npm run publish to check the output in the browser − Print Add Notes Bookmark this page
[ { "code": null, "e": 2622, "s": 2095, "text": "Webpack is a module bundler which packs all modules with dependencies – js, styles, images, etc. into static assets .js, .css, .jpg , .png, etc. Webpack comes with presets which help for compilation into the required form. For example, react preset that...
IDE | GeeksforGeeks | A computer science portal for geeks
Edit the code and Run to see changes
[]
Create a Mobile Toggle Navigation Menu using HTML, CSS and JavaScript - GeeksforGeeks
06 Sep, 2021 To create a Mobile Toggle Navigation Menu you need HTML, CSS, and JavaScript. If you want to attach the icons with the menu then you need a font-awesome CDN link. This article is divided into two sections: Creating Structure and Designing Structure. Glimpse of complete Navigation: Creating Structure: In this section, we will create a basic site structure and also attach the CDN link of the Font-Awesome for the icons which will be used as a menu icon. CDN links for the Icons from the Font Awesome: <link rel=”stylesheet” href=”https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css”> HTML code to make the structure: HTML <!DOCTYPE html><html> <head> <title>Mobile Navigation Bar</title> <meta name="viewport" content="width=device-width, initial-scale=1"></head> <body> <div class="menu-list"> <!-- Logo and navigation menu --> <div class="geeks"> <a href="#" class="">GeeksforGeeks</a> <div id="menus"> <a href="#">Language</a> <a href="#">Practice</a> <a href="#">Interview</a> <a href="#">Puzzle</a> </div> <!-- Bar icon for navigation --> <a href="javascript:void(0);" class="icon" onclick="geeksforgeeks()"> <i onclick="myFunction(this)" class="fa fa-plus-circle"> </i> </a> </div> </div></body> </html> Designing Structure: In the previous section, we have created the structure of the basic website where we are going to use the menu icon. In this section, we will design the structure for the navigation bar. CSS code of structure: HTML <style> /* Navigation bar styling */ .menu-list { max-width: 300px; margin: auto; height: 500px; color: white; background-color: green; border-radius: 10px; } /* Logo, navigation menu styling */ .geeks { overflow: hidden; background-color: #111; position: relative; } /* styling navigation menu */ .geeks #menus { display: none; } /* Link specific styling */ .geeks a { text-decoration: none; color: white; padding: 14px 16px; font-size: 16px; display: block; } /* Navigation toggle menu styling */ .geeks a.icon { display: block; position: absolute; right: 0; top: 0; } /* hover effect on navigation logo and menu */ .geeks a:hover { background-color: #ddd; color: black; } </style> JavaScript code for the animation menu: Javascript <script> // Function to toggle the bar function geeksforgeeks() { var x = document.getElementById("menus"); if (x.style.display === "block") { x.style.display = "none"; } else { x.style.display = "block"; } }</script> <script> // Function to toggle the plus menu into minus function myFunction(x) { x.classList.toggle("fa-minus-circle"); }</script> Combine the HTML, CSS, and JavaScript code: This is the final code after combining the above sections. It will the mobile navigation animated menu. Example: HTML <!DOCTYPE html><html> <head> <title>Mobile Navigation Bar</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> /* Navigation bar styling */ .menu-list { max-width: 300px; margin: auto; height: 500px; color: white; background-color: green; border-radius: 10px; } /* logo, navigation menu styling */ .geeks { overflow: hidden; background-color: #111; position: relative; } /* styling navigation menu */ .geeks #menus { display: none; } /* link specific styling */ .geeks a { text-decoration: none; color: white; padding: 14px 16px; font-size: 16px; display: block; } /* navigation toggle menu styling */ .geeks a.icon { display: block; position: absolute; right: 0; top: 0; } /* hover effect on navigation logo and menu */ .geeks a:hover { background-color: #ddd; color: black; } </style></head> <body> <div class="menu-list"> <!-- Logo and navigation menu --> <div class="geeks"> <a href="#" class="">GeeksforGeeks</a> <div id="menus"> <a href="#">Language</a> <a href="#">Practice</a> <a href="#">Interview</a> <a href="#">Puzzle</a> </div> <!-- Bar icon for navigation --> <a href="javascript:void(0);" class="icon" onclick="geeksforgeeks()"> <i onclick="myFunction(this)" class="fa fa-plus-circle"> </i> </a> </div> </div> <script> // Function to toggle the bar function geeksforgeeks() { var x = document.getElementById("menus"); if (x.style.display === "block") { x.style.display = "none"; } else { x.style.display = "block"; } } </script> <script> // Function to toggle the plus menu into minus function myFunction(x) { x.classList.toggle("fa-minus-circle"); } </script></body> </html> Output: arorakashish0911 CSS-Properties HTML-Tags javascript-functions CSS HTML JavaScript Web Technologies Web technologies Questions 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 create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) 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 Insert Form Data into Database using PHP ?
[ { "code": null, "e": 37890, "s": 37862, "text": "\n06 Sep, 2021" }, { "code": null, "e": 38140, "s": 37890, "text": "To create a Mobile Toggle Navigation Menu you need HTML, CSS, and JavaScript. If you want to attach the icons with the menu then you need a font-awesome CDN link. ...
MySQL CREATE DATABASE Statement
The CREATE DATABASE statement is used to create a new SQL database. The following SQL statement creates a database called "testDB": Tip: Make sure you have admin privilege before creating any database. Once a database is created, you can check it in the list of databases with the following SQL command: SHOW DATABASES; Write the correct SQL statement to create a new database called testDB. ; Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 68, "s": 0, "text": "The CREATE DATABASE statement is used to create a new SQL database." }, { "code": null, "e": 132, "s": 68, "text": "The following SQL statement creates a database called \"testDB\":" }, { "code": null, "e": 322, "s": 132, ...
Building a Face Recognition System Using Scikit Learn in Python | by Dr. Varshita Sher | Towards Data Science
Face recognition is the task of comparing an unknown individual’s face to images in a database of stored records. The mapping could be one–to–one or one–to–many, depending on whether we are running face verification or face identification. In this tutorial, we are interested in building a facial identification system that will verify if an image, generally known as probe image, exists within a pre-existing database of faces, generally known as the evaluation set. There are four main steps involved in building such a system: Available face detection models include MTCNN, FaceNet, Dlib, etc. OpenCV library provides all the tools we need for this step. Since programs can’t work with jpg or png files directly, we need some way of translating images to numbers. In this tutorial, we will be using the Insightface model for creating a multi-dimensional (512-d) embedding for a face such that it encapsulates useful semantic information pertaining to the face. To tackle all three steps using a single library, we will be using insightface. In particular, we will be working with Insightface’s ArcFace model. InsightFace is an open-sourced deep face analysis model for face recognition, face detection and face align-ment tasks. Once we have translated each unique face into a vector, comparing faces essentials boils down to comparing the corresponding embeddings. We will be making use of these embeddings to train a sci-kit learn model. P.S. If you’d like to follow along, the code is available on Github. Create a virtual environment (optional): python3 -m venv face_search_env Activate this environment: source face_search_env/bin/activate Necessary installations within this environment: pip install mxnet==1.8.0.post0pip install -U insightface==0.2.1pip install onnx==1.10.1pip install onnxruntime==1.8.1 More importantly, once you are done with pip installing insightface: - Download the antelope model release from onedrive. (It contains two pre-trained models for detection and recognition).- Put it under ~/.insightface/models/, so there're onnx models at ~/.insightface/models/antelope/*.onnx. This is how it should look like if the setup was done correctly: and if you look inside the antelope directory, you’ll find the two onnx models for face detection and recognition: Note: Since the latest release of insightface 0.4.1 last week, the installation was not as straightforward as I would have hoped (at least for me). Hence, I will be using 0.2.1 for this tutorial. In the future, I’ll update the code on Github accordingly. Please see the instructions here if you’re stuck. We will be working with the Yale Faces dataset available on Kaggle, containing approximately 165 grayscale images of 15 individuals (i.e. 11 unique images per identity). The images are composed of a wide variety of expressions, poses, and illumination configurations. Once you have the dataset, go ahead and unzip it inside a newly createddata directory within your project (see the project directory structure on Github). If you’d like to follow along, the Jupyter Notebook can be found on Github. import osimport pickleimport numpy as npfrom PIL import Imagefrom typing import Listfrom tqdm import tqdmfrom insightface.app import FaceAnalysisfrom sklearn.neighbors import NearestNeighbors Once insightface is installed, we must call app=FaceAnalysis(name="model_name")to load the models. Since we stored our onnx models inside the antelope directory: app = FaceAnalysis(name="antelope")app.prepare(ctx_id=0, det_size=(640, 640)) Generating an embedding for an image is quite straightforward with the insightface model. For instance: # Generating embeddings for an imageimg_emb_results = app.get(np.asarray(img))img_emb = img_emb_results[0].embeddingimg_emb.shape------------OUTPUT---------------(512,) Prior to using this dataset, we must fix the extensions for the files in the directory such that file names end with .gif. (or .jpg , .png, etc). For instance, the following code snippet will change the filename subject01.glasses to subject01_glasses.gif. Next, we will split the data into the evaluation and probe sets: 90% or 10 images per subject will become part of the evaluation set and the remaining 10% or 1 image per subject will be used in the probe set. To avoid sampling bias, the probe image for each subject will be randomly chosen using a helper function called create_probe_eval_set() . It takes as input a list containing the (file names for the) 11 images belonging to a particular subject and returns two lists of lengths 1 and 10. The former contains the filename to be used for the probe set while the latter contains file names for the evaluation set. Both the lists returned by the create_probe_eval_set() are sequentially fed to a helper function called generate_embs(). For each filename in the list, it reads the grayscale image, converts it to RGB, calculates the corresponding embeddings, and finally returns the embeddings along with the image labels (scraped from the filename). Now that we have a framework for generating embeddings, let’s go ahead and create embeddings for both probe and evaluation set using generate_embs(). Few things to consider: The files returned by os.listdir()are in completely random order, hence sorting on line 3 is important. Why do we need sorted filenames? Remember create_probe_eval_set() on line 11 requires all files belonging to a particular subject in any single iteration. [Optional] We could have replaced the create_probe_eval_set() function, get rid of the forloop, and simplified a few lines in the above code snippet if we used the stratified train_test_splitfunctionality provided by sklearn. For this tutorial, however, I prioritized clarity over code simplicity. Oftentimes, insightface is unable to detect a face and subsequently generates an empty embedding for it. That explains why some of the entries in probe_setor eval_set list might be empty. It is important that we filter them out and keep only non-empty values. To do so, we create another helper function called filter_empty_embs(): It takes as input the image set (either probe_set or eval_set ) and removes those elements for which insightface could not generate an embedding (see Line 6). Following this, it also updates the labels (either probe_labelsor eval_labels) (see Line 7) such that both sets and labels have the same length. Finally, we can obtain the 512-d embeddings for only the good indices in both evaluation set and probe set: assert len(evaluation_embs) == len(evaluation_labels)assert len(probe_embs) == len(probe_labels) With both sets at our disposal, we are now ready to build our face identification system using a popular unsupervised learning method implemented in the Sklearn library. We train the Nearest neighbor model using .fit() with evaluation embeddings as X. This is a neat technique for unsupervised nearest neighbors learning. The nearest neighbour method allows us to find a predefined number of training samples closest in distance to a new point. Note: The distance can, in general, be any metric measure such as Euclidean, Manhattan, Cosine, Minkowski, etc. Because we are implementing an unsupervised learning method, observe that we do not pass any labels, i.e. evaluation_label to the fit method. All we are doing here is mapping out the face embeddings in the evaluation set into a latent space. Why??, you ask. Simple answer: By storing the training set in memory ahead of time, we are able to speed up the search for its nearest neighbors during inference time. How does it do this? Simple answer: Storing the tree in an optimized manner in memory is quite useful, especially when the training set is large and searching for a new point’s neighbors becomes computationally expensive. Neighbors-based methods are known as non-generalizing machine learning methods, since they simply “remember” all of its training data (possibly transformed into a fast indexing structure such as a Ball Tree or KD Tree). [Source] Note: See this Stackoverflow discussion if you are still not convinced! For each new probe image, we can find whether it is present in the evaluation set by searching for its top k neighbors using nn.neighbours()method. For instance, # Example inference on test imagedists, inds = nn.kneighbors(X = probe_img_emb.reshape(1,-1), n_neighbors = 3, return_distances = True ) If the labels at the returned indices (inds) in the evaluation set are a perfect match for the probe image’s original/true label, then we know we have found our face in the verification system. We have wrapped the aforementioned logic into the print_ID_results() method. It takes as input the probe image path, the evaluation set labels, and the verbose flag to specify if detailed results should be displayed. Few important things to note here: inds contain the indices of the nearest neighbors in the evaluation_labels set (line 6). For instance, inds = [[2,0,11]]means label at index=2 in evaluation_labels is found to be nearest to the probe image, followed by the label at index = 0. Since for any image, nn.neighborswill return a non-empty response, we must only consider those results as a face ID match if the distance returned is less than or equal to 0.6 (line 12). (P.S. The choice of 0.6 is completely arbitrary).For example, continuing with the above example where inds = [[2,0, 11]]and let's saydists = [[0.4, 0.6, 0.9]], we will only consider the labels at index=2 and index = 0 (in evaluation_labels) as a true face match because the dist for the last neighbor is too large for it to be a genuine match. As a quick sanity check, let’s see the system’s response when we input a baby’s face as a probe image. As expected, it reveals no matching faces found! However, we set verbose as True, because of which we get to see the labels and distances for its bogus nearest neighbors in the database, all of which appear to be quite large (>0.8). One of the ways to test whether this system is any good is to see how many relevant results are present in the top k neighbors. A relevant result is one where the true label matches the predicted label. This metric is generally referred to as precision at k, where k is predetermined. For instance, pick an image (or rather an embedding ) from the probe set with a true label as ‘subject01’. If the top two pred_labels returned by nn.neighborsfor this image are [‘subject01’, ‘subject01’], it means the precision at k (p@k) with k=2 is 100%. Similarly, if only one of the values in pred_labels was equal to ‘subject05’, p@k would be 50%, and so on... dists, inds = nn.kneighbors(X=probe_embs_example.reshape(1, -1), n_neighbors=2, return_distance=True)pred_labels = [evaluation_labels[i] for i in inds[0] ]pred_labels----- OUTPUT ------['002', '002'] Let’s go ahead and calculate the average p@k value across the entire probe set: Awesome! 90% Not too shabby but definitely could be improved (but that’s for another time)... Kudos to you for following this through! Hopefully, this warm introduction to face recognition, an active area of research in computer vision, was enough to get you started. As always, if there’s an easier way to do some of the things I mentioned in this article, please do let me know. Until next time :)
[ { "code": null, "e": 411, "s": 171, "text": "Face recognition is the task of comparing an unknown individual’s face to images in a database of stored records. The mapping could be one–to–one or one–to–many, depending on whether we are running face verification or face identification." }, { "...
SAP HANA - SQL Sequences
A sequence is a set of integers 1, 2, 3, that are generated in order on demand. Sequences are frequently used in databases because many applications require each row in a table to contain a unique value, and sequences provide an easy way to generate them. The simplest way in MySQL to use sequences is to define a column as AUTO_INCREMENT and leave rest of the things to MySQL to take care. Try out the following example. This will create table and after that it will insert few rows in this table where it is not required to give record ID because it is auto-incremented by MySQL. mysql> CREATE TABLE INSECT -> ( -> id INT UNSIGNED NOT NULL AUTO_INCREMENT, -> PRIMARY KEY (id), -> name VARCHAR(30) NOT NULL, # type of insect -> date DATE NOT NULL, # date collected -> origin VARCHAR(30) NOT NULL # where collected ); Query OK, 0 rows affected (0.02 sec) mysql> INSERT INTO INSECT (id,name,date,origin) VALUES -> (NULL,'housefly','2001-09-10','kitchen'), -> (NULL,'millipede','2001-09-10','driveway'), -> (NULL,'grasshopper','2001-09-10','front yard'); Query OK, 3 rows affected (0.02 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> SELECT * FROM INSECT ORDER BY id; +----+-------------+------------+------------+ | id | name | date | origin | +----+-------------+------------+------------+ | 1 | housefly | 2001-09-10 | kitchen | | 2 | millipede | 2001-09-10 | driveway | | 3 | grasshopper | 2001-09-10 | front yard | +----+-------------+------------+------------+ 3 rows in set (0.00 sec) LAST_INSERT_ID( ) is a SQL function, so you can use it from within any client that understands how to issue SQL statements. Otherwise, PERL and PHP scripts provide exclusive functions to retrieve auto-incremented value of last record. Use the mysql_insertid attribute to obtain the AUTO_INCREMENT value generated by a query. This attribute is accessed through either a database handle or a statement handle, depending on how you issue the query. The following example references it through the database handle − $dbh->do ("INSERT INTO INSECT (name,date,origin) VALUES('moth','2001-09-14','windowsill')"); my $seq = $dbh->{mysql_insertid}; After issuing a query that generates an AUTO_INCREMENT value, retrieve the value by calling mysql_insert_id( ) − mysql_query ("INSERT INTO INSECT (name,date,origin) VALUES('moth','2001-09-14','windowsill')", $conn_id); $seq = mysql_insert_id ($conn_id); There may be a case when you have deleted many records from a table and you want to re-sequence all the records. This can be done by using a simple trick but you should be very careful to do so if your table is having join, with other table. If you determine that resequencing an AUTO_INCREMENT column is unavoidable, the way to do it is to drop the column from the table, then add it again. The following example shows how to renumber the id values in the insect table using this technique − mysql> ALTER TABLE INSECT DROP id; mysql> ALTER TABLE insect -> ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT FIRST, -> ADD PRIMARY KEY (id); By default, MySQL will start sequence from 1 but you can specify any other number as well at the time of table creation. Following is the example where MySQL will start sequence from 100. mysql> CREATE TABLE INSECT -> ( -> id INT UNSIGNED NOT NULL AUTO_INCREMENT = 100, -> PRIMARY KEY (id), -> name VARCHAR(30) NOT NULL, # type of insect -> date DATE NOT NULL, # date collected -> origin VARCHAR(30) NOT NULL # where collected ); Alternatively, you can create the table and then set the initial sequence value with ALTER TABLE. 25 Lectures 6 hours Sanjo Thomas 26 Lectures 2 hours Neha Gupta 30 Lectures 2.5 hours Sumit Agarwal 30 Lectures 4 hours Sumit Agarwal 14 Lectures 1.5 hours Neha Malik 13 Lectures 1.5 hours Neha Malik Print Add Notes Bookmark this page
[ { "code": null, "e": 3363, "s": 3107, "text": "A sequence is a set of integers 1, 2, 3, that are generated in order on demand. Sequences are frequently used in databases because many applications require each row in a table to contain a unique value, and sequences provide an easy way to generate the...