title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Array to BST | Practice | GeeksforGeeks
Given a sorted array. Convert it into a Height balanced Binary Search Tree (BST). Find the preorder traversal of height balanced BST. If there exist many such balanced BST consider the tree whose preorder is lexicographically smallest. Height balanced BST means a binary tree in which the depth of the left subtree and the right subtree of every node never differ by more than 1. Example 1: Input: nums = {1, 2, 3, 4} Output: {2, 1, 3, 4} Explanation: The preorder traversal of the following BST formed is {2, 1, 3, 4}: 2 / \ 1 3 \ 4 Example 2: Input: nums = {1,2,3,4,5,6,7} Ouput: {4,2,1,3,6,5,7} Explanation: The preorder traversal of the following BST formed is {4,2,1,3,6,5,7} : 4 / \ 2 6 / \ / \ 1 3 5 7 Your Task: You don't need to read or print anything. Your task is to complete the function sortedArrayToBST() which takes the sorted array nums as input paramater and returns the preorder traversal of height balanced BST. If there exist many such balanced BST consider the tree whose preorder is lexicographically smallest. Expected Time Complexity: O(n) Expected Space Complexity: O(n) Constraints: 1 ≤ |nums| ≤ 104 -104 ≤ nums[i] ≤ 104 0 singhkrish14141 week ago class Node: def __init__(self, value): self.data = value self.left = None self.right = None class Solution: def sortedArrayToBST_helper(self, array): if not array: return None mid =(len(array)-1)//2 node = Node(array[mid]) node.left = self.sortedArrayToBST_helper(array[:mid]) node.right = self.sortedArrayToBST_helper(array[mid+1:]) return node def pre_order_traversal(self, root, mapper=[]): if root is None: return map_ = mapper map_.append(root.data) self.pre_order_traversal(root.left, map_) self.pre_order_traversal(root.right, map_) return map_ def sortedArrayToBST(self, array): root = self.sortedArrayToBST_helper(array) return self.pre_order_traversal(root) Input 2 -8 4 my output 1 -2 -5 -2 1 1 5 7 -8 4 correct output -8 4 when I ran my code with the set of value in custom input it return the output -8 4 but when I submit the code I am getting different output, can anyone tell me what's wrong in my code. 0 amishasahu3282 weeks ago class Solution { public: void convertToBST(vector<int> &nums, int start, int end, vector<int> &preorder) { if(start > end) return; int mid = (start + end) >> 1; preorder.push_back(nums[mid]); convertToBST(nums, start, mid-1, preorder); convertToBST(nums, mid+1, end, preorder); } vector<int> sortedArrayToBST(vector<int>& nums) { // Code here vector<int> preorder; convertToBST(nums, 0, nums.size()-1, preorder); return preorder; } }; 0 adityagagtiwari3 weeks ago Hello fellas ! Can anyone tell me why cant we make idx variable used below as a normal int type. I know that the value stored in int datatype gets corrupted across methods but why does this dont apply to other int variables(low and mid) below!! class Solution { public int[] sortedArrayToBST(int[] nums) { // Code here int[] bst = new int[nums.length]; int[] idx = new int[1]; makeATree(0,nums.length-1,nums,bst,idx); return bst; } public void makeATree(int low,int high,int[] nums,int[] bst,int[] k) { if(low>high) return; int mid = (high+low)/2; bst[k[0]]=nums[mid]; k[0]++; makeATree(low,mid-1,nums,bst,k); makeATree(mid+1,high,nums,bst,k); } } 0 tanashah This comment was deleted. +7 sarthakjagetiya10011 month ago Total Time Taken: 1.2/2.1 C++ void preorder(vector<int> nums, int s, int e, vector<int> &ans){ if(s>e){ return; } int mid= (s+e)/2; ans.push_back(nums[mid]); preorder(nums, s, mid-1, ans); preorder(nums, mid+1, e, ans); } vector<int> sortedArrayToBST(vector<int>& nums) { vector<int> ans; int n=nums.size(); preorder(nums, 0, n-1, ans); return ans; } +1 lindan1232 months ago vector<int> vec; void help(vector<int>& nums,int i,int j) { if(i>j)return; int mid = (i+j)/2; vec.push_back(nums[mid]); help(nums,i,mid-1); help(nums,mid+1,j); } vector<int> sortedArrayToBST(vector<int>& nums) { help(nums,0,nums.size()-1); return vec; } Time Taken : 0.2sec Cpp +4 ninja_112 months ago Hint : This is not BST as some of its test cases have duplicate value. +2 badgujarsachin833 months ago void preorder(vector<int> &nums,int i,int j,vector<int> &v){ if(i<=j){ int mid=(i+j)/2; v.push_back(nums[mid]); preorder(nums,i,mid-1,v); preorder(nums,mid+1,j,v); } } vector<int> sortedArrayToBST(vector<int>& nums) { // Code here vector<int> v; int i=0,j=nums.size()-1; preorder(nums,i,j,v); return v; } 0 krishnagautam58994 months ago struct Node{ int data; struct Node *left; struct Node *right; Node(int x){ data=x; left=NULL; right=NULL; }}; void solve(vector<int> &nums, vector<int> &ans , int l, int h) { if(l>h) return; int mid = (l+h) / 2; int temp = nums[mid]; ans.push_back(temp); solve(nums,ans,l,mid-1); solve(nums,ans,mid+1,h); } vector<int> sortedArrayToBST(vector<int>& nums) { vector<int>ans; int l = 0; int h = nums.size()-1; solve(nums,ans,l,h); return ans; } -1 jmonu1327 months ago void bstbuild(vector<int> nums,vector<int> &v,int si,int ei) { if(si<=ei) { int mid=(si+ei)/2; v.push_back(nums[mid]); bstbuild(nums,v,si,mid-1); bstbuild(nums,v,mid+1,ei); } } vector<int> sortedArrayToBST(vector<int>& nums) { // Code here vector<int> v; int si=0,ei=nums.size()-1; bstbuild(nums,v,si,ei); return v; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 618, "s": 238, "text": "Given a sorted array. Convert it into a Height balanced Binary Search Tree (BST). Find the preorder traversal of height balanced BST. If there exist many such balanced BST consider the tree whose preorder is lexicographically smallest.\nHeight balanced BST means a binary tree in which the depth of the left subtree and the right subtree of every node never differ by more than 1." }, { "code": null, "e": 629, "s": 618, "text": "Example 1:" }, { "code": null, "e": 843, "s": 629, "text": "Input: nums = {1, 2, 3, 4}\nOutput: {2, 1, 3, 4}\nExplanation: \nThe preorder traversal of the following \nBST formed is {2, 1, 3, 4}:\n 2\n / \\\n 1 3\n \\\n 4\n" }, { "code": null, "e": 856, "s": 845, "text": "Example 2:" }, { "code": null, "e": 1058, "s": 856, "text": "Input: nums = {1,2,3,4,5,6,7}\nOuput: {4,2,1,3,6,5,7}\nExplanation: \nThe preorder traversal of the following\nBST formed is {4,2,1,3,6,5,7} :\n 4\n / \\\n 2 6\n / \\ / \\\n 1 3 5 7\n" }, { "code": null, "e": 1384, "s": 1060, "text": "Your Task:\nYou don't need to read or print anything. Your task is to complete the function sortedArrayToBST() which takes the sorted array nums as input paramater and returns the preorder traversal of height balanced BST. If there exist many such balanced BST consider the tree whose preorder is lexicographically smallest." }, { "code": null, "e": 1447, "s": 1384, "text": "Expected Time Complexity: O(n)\nExpected Space Complexity: O(n)" }, { "code": null, "e": 1500, "s": 1447, "text": "Constraints:\n1 ≤ |nums| ≤ 104\n-104 ≤ nums[i] ≤ 104\n " }, { "code": null, "e": 1502, "s": 1500, "text": "0" }, { "code": null, "e": 1527, "s": 1502, "text": "singhkrish14141 week ago" }, { "code": null, "e": 2348, "s": 1527, "text": "class Node:\n def __init__(self, value):\n self.data = value\n self.left = None\n self.right = None\nclass Solution:\n def sortedArrayToBST_helper(self, array):\n if not array:\n return None\n mid =(len(array)-1)//2\n node = Node(array[mid])\n node.left = self.sortedArrayToBST_helper(array[:mid])\n node.right = self.sortedArrayToBST_helper(array[mid+1:])\n return node\n def pre_order_traversal(self, root, mapper=[]):\n if root is None:\n return\n map_ = mapper\n map_.append(root.data)\n self.pre_order_traversal(root.left, map_)\n self.pre_order_traversal(root.right, map_)\n return map_\n def sortedArrayToBST(self, array):\n root = self.sortedArrayToBST_helper(array)\n return self.pre_order_traversal(root)" }, { "code": null, "e": 2354, "s": 2348, "text": "Input" }, { "code": null, "e": 2357, "s": 2354, "text": "2 " }, { "code": null, "e": 2362, "s": 2357, "text": "-8 4" }, { "code": null, "e": 2374, "s": 2364, "text": "my output" }, { "code": null, "e": 2398, "s": 2374, "text": "1 -2 -5 -2 1 1 5 7 -8 4" }, { "code": null, "e": 2415, "s": 2400, "text": "correct output" }, { "code": null, "e": 2420, "s": 2415, "text": "-8 4" }, { "code": null, "e": 2607, "s": 2422, "text": "when I ran my code with the set of value in custom input it return the output -8 4 but when I submit the code I am getting different output, can anyone tell me what's wrong in my code." }, { "code": null, "e": 2613, "s": 2611, "text": "0" }, { "code": null, "e": 2638, "s": 2613, "text": "amishasahu3282 weeks ago" }, { "code": null, "e": 3166, "s": 2638, "text": "class Solution {\npublic:\n void convertToBST(vector<int> &nums, int start, int end, vector<int> &preorder)\n {\n if(start > end) return;\n int mid = (start + end) >> 1;\n preorder.push_back(nums[mid]);\n convertToBST(nums, start, mid-1, preorder);\n convertToBST(nums, mid+1, end, preorder);\n }\n vector<int> sortedArrayToBST(vector<int>& nums) {\n // Code here\n vector<int> preorder;\n convertToBST(nums, 0, nums.size()-1, preorder);\n return preorder;\n }\n};\n" }, { "code": null, "e": 3168, "s": 3166, "text": "0" }, { "code": null, "e": 3195, "s": 3168, "text": "adityagagtiwari3 weeks ago" }, { "code": null, "e": 3210, "s": 3195, "text": "Hello fellas !" }, { "code": null, "e": 3292, "s": 3210, "text": "Can anyone tell me why cant we make idx variable used below as a normal int type." }, { "code": null, "e": 3440, "s": 3292, "text": "I know that the value stored in int datatype gets corrupted across methods but why does this dont apply to other int variables(low and mid) below!!" }, { "code": null, "e": 3956, "s": 3442, "text": "class Solution\n{\n public int[] sortedArrayToBST(int[] nums)\n {\n // Code here \n int[] bst = new int[nums.length];\n int[] idx = new int[1];\n makeATree(0,nums.length-1,nums,bst,idx);\n return bst;\n }\n public void makeATree(int low,int high,int[] nums,int[] bst,int[] k)\n {\n if(low>high)\n return;\n \n int mid = (high+low)/2;\n bst[k[0]]=nums[mid];\n k[0]++;\n makeATree(low,mid-1,nums,bst,k);\n makeATree(mid+1,high,nums,bst,k);\n }\n}" }, { "code": null, "e": 3958, "s": 3956, "text": "0" }, { "code": null, "e": 3967, "s": 3958, "text": "tanashah" }, { "code": null, "e": 3993, "s": 3967, "text": "This comment was deleted." }, { "code": null, "e": 3996, "s": 3993, "text": "+7" }, { "code": null, "e": 4027, "s": 3996, "text": "sarthakjagetiya10011 month ago" }, { "code": null, "e": 4054, "s": 4027, "text": "Total Time Taken: 1.2/2.1" }, { "code": null, "e": 4058, "s": 4054, "text": "C++" }, { "code": null, "e": 4483, "s": 4058, "text": "void preorder(vector<int> nums, int s, int e, vector<int> &ans){\n if(s>e){\n return;\n }\n int mid= (s+e)/2;\n ans.push_back(nums[mid]);\n preorder(nums, s, mid-1, ans);\n preorder(nums, mid+1, e, ans);\n }\n vector<int> sortedArrayToBST(vector<int>& nums) {\n vector<int> ans;\n int n=nums.size();\n preorder(nums, 0, n-1, ans);\n return ans;\n }" }, { "code": null, "e": 4486, "s": 4483, "text": "+1" }, { "code": null, "e": 4508, "s": 4486, "text": "lindan1232 months ago" }, { "code": null, "e": 4811, "s": 4508, "text": "vector<int> vec;\nvoid help(vector<int>& nums,int i,int j)\n{\n if(i>j)return;\n \n int mid = (i+j)/2;\n vec.push_back(nums[mid]);\n help(nums,i,mid-1);\n help(nums,mid+1,j);\n}\n vector<int> sortedArrayToBST(vector<int>& nums) {\n help(nums,0,nums.size()-1);\n return vec;\n }" }, { "code": null, "e": 4831, "s": 4811, "text": "Time Taken : 0.2sec" }, { "code": null, "e": 4835, "s": 4831, "text": "Cpp" }, { "code": null, "e": 4838, "s": 4835, "text": "+4" }, { "code": null, "e": 4859, "s": 4838, "text": "ninja_112 months ago" }, { "code": null, "e": 4930, "s": 4859, "text": "Hint : This is not BST as some of its test cases have duplicate value." }, { "code": null, "e": 4933, "s": 4930, "text": "+2" }, { "code": null, "e": 4962, "s": 4933, "text": "badgujarsachin833 months ago" }, { "code": null, "e": 5383, "s": 4962, "text": "void preorder(vector<int> &nums,int i,int j,vector<int> &v){\n if(i<=j){\n int mid=(i+j)/2;\n v.push_back(nums[mid]);\n preorder(nums,i,mid-1,v);\n preorder(nums,mid+1,j,v);\n }\n }\n vector<int> sortedArrayToBST(vector<int>& nums) {\n // Code here\n vector<int> v;\n int i=0,j=nums.size()-1;\n preorder(nums,i,j,v);\n return v;\n }" }, { "code": null, "e": 5385, "s": 5383, "text": "0" }, { "code": null, "e": 5415, "s": 5385, "text": "krishnagautam58994 months ago" }, { "code": null, "e": 5559, "s": 5415, "text": "struct Node{ int data; struct Node *left; struct Node *right; Node(int x){ data=x; left=NULL; right=NULL; }};" }, { "code": null, "e": 5995, "s": 5559, "text": " void solve(vector<int> &nums, vector<int> &ans , int l, int h) { if(l>h) return; int mid = (l+h) / 2; int temp = nums[mid]; ans.push_back(temp); solve(nums,ans,l,mid-1); solve(nums,ans,mid+1,h); } vector<int> sortedArrayToBST(vector<int>& nums) { vector<int>ans; int l = 0; int h = nums.size()-1; solve(nums,ans,l,h); return ans; }" }, { "code": null, "e": 5998, "s": 5995, "text": "-1" }, { "code": null, "e": 6019, "s": 5998, "text": "jmonu1327 months ago" }, { "code": null, "e": 6426, "s": 6019, "text": " void bstbuild(vector<int> nums,vector<int> &v,int si,int ei) { if(si<=ei) { int mid=(si+ei)/2; v.push_back(nums[mid]); bstbuild(nums,v,si,mid-1); bstbuild(nums,v,mid+1,ei); } } vector<int> sortedArrayToBST(vector<int>& nums) { // Code here vector<int> v; int si=0,ei=nums.size()-1; bstbuild(nums,v,si,ei); return v; }" }, { "code": null, "e": 6572, "s": 6426, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 6608, "s": 6572, "text": " Login to access your submissions. " }, { "code": null, "e": 6618, "s": 6608, "text": "\nProblem\n" }, { "code": null, "e": 6628, "s": 6618, "text": "\nContest\n" }, { "code": null, "e": 6691, "s": 6628, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6839, "s": 6691, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 7047, "s": 6839, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 7153, "s": 7047, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Rendering OpenAI Gym Envs on Binder and Google Colab | by David R. Pugh | Towards Data Science
I am currently using my COVID-19 imposed quarantine to expand my deep learning skills by completing the Deep Reinforcement Learning Nanodegree from Udacity. Almost immediately I ran into the tedious problem of getting my simulations to render properly when training on remote servers. In particular, getting OpenAI Gym environments to render properly in remote servers such as those supporting popular free compute facilities such as Google Colab and Binder turned out to be more challenging than I expected. In this post, I lay out my solution in the hopes that I might save others time and effort to work it out independently. If you wish to use Google Colab, then this section is for you! Otherwise, you can skip to the next section for the Binder Preamble. First, you will need to install the necessary X11 dependencies, in particular Xvfb, which is an X server that can run on machines with no display hardware and no physical input devices. You can install system dependencies inside your Colab notebook by prepending the install command with an exclamation mark (!)which will run the command inside its own Bash shell. !apt-get install -y xvfb x11-utils Now that you have installed Xvfb, you need to install a Python wrapper pyvirtualdisplay in order to interact with Xvfb virtual displays from within Python. You also need to install the Python bindings for OpenGL: PyOpenGL and PyOpenGL-accelerate. The former is the actual Python bindings, the latter is an optional set of C (Cython) extensions providing acceleration of common operations in PyOpenGL 3.x. !pip install pyvirtualdisplay==0.2.* \ PyOpenGL==3.1.* \ PyOpenGL-accelerate==3.1.* Next, you need to install the OpenAI Gym package. Note that depending on which Gym environment you are interested in working with you may need to add additional dependencies. Since I am going to simulate the LunarLander-v2 environment in my demo below I need to install the box2d extra which enables Gym environments that depend on the Box2D physics simulator. !pip install gym[box2d]==0.17.* For simplicity, I have gathered all the software installation steps into a single code block that you can cut and paste into your notebook. %%bash# install required system dependenciesapt-get install -y xvfb x11-utils# install required python dependenciespip install gym[box2d]==0.17.* \ pyvirtualdisplay==0.2.* \ PyOpenGL==3.1.* \ PyOpenGL-accelerate==3.1.* Now that all the required software is installed you are ready to create a virtual display (i.e., a display that runs in the background) which the OpenAI Gym Envs can connect to for rendering purposes. You can actually check that there is no display at present by confirming that the value of the DISPLAY environment variable has not yet been set. !echo $DISPLAY The code in the cell below creates a virtual display in the background that your Gym Envs can connect to for rendering. You can adjust the size of the virtual buffer as you like but you must set visible=False when working with Xvfb. This code only needs to be run once in your notebook to start the display. After running the code above in your notebook you can echo out the value of the DISPLAY environment variable again to confirm that you now have a display running. !echo $DISPLAY # should now be set to some value For convenience, I have gathered the above steps into two cells that you can copy and paste into the top of you Google Colab notebooks. If you wish to use Binder, then this section is for you! Unlike Google Colab, with Binder you can bake all the required dependencies (including the X11 system dependencies!) into the Docker image on which the Binder instance is based using Binder config files. These config files can either live in the root directory of your Git repo or in a binder sub-directory (my preferred choice). The first config file that needs to be defined is the apt.txt file which is used to install system dependencies. You can just create an appropriately named file and then list the dependencies you want to install (one per line). After a bit of trial and error, I hit on the following winning combination. freeglut3-devxvfbx11-utils The second and config file is the standard environment.yml file used to define a Conda environment. If you are unfamiliar with Conda, then I suggest that you check out my recent articles on Getting started with Conda and Managing project-specific environments with Conda. name: null channels: - conda-forge - defaults dependencies: - gym-box2d=0.17 - jupyterlab=2.0 - matplotlib=3.2 - pip=20.0 - pip: - -r file:requirements.txt - python=3.7 - pyvirtualdisplay=0.2 The final required config file is the requirements.txt file used by Conda to install any additional Python dependencies that are not available via Conda channels using pip. PyOpenGL==3.1.*PyOpenGL-accelerate==3.1.* If you are interested in learning more about Binder, then check out the documentation for BinderHub which is the underlying technology behind the Binder project. Next, you need to create a virtual display in the background which the Gym Envs can connect to for rendering purposes. You can check that there is no display at present by confirming that the value of the DISPLAY environment variable has not yet been set. !echo $DISPLAY The code in the cell below creates a virtual display in the background that your Gym Envs can connect to for rendering. You can adjust the size of the virtual buffer as you like but you must set visible=False when working with Xvfb. This code only needs to be run once per session to start the display. After running the cell above you can echo out the value of the DISPLAY environment variable again to confirm that you now have a display running. !echo $DISPLAY Just to prove that the above setup works as advertised I will run a short simulation. First I define an Agent that chooses an action randomly from the set of possible actions and then define a function that can be used to create such agents. Then I wrap up the code to simulate a single episode of an OpenAI Gym environment. Note that the implementation assumes that the provided environment supports rgb_array rendering (which not all Gym environments support!). Currently there appears to be a non-trivial amount of flickering during the simulation. Not entirely sure what is causing this undesirable behavior. If you have any idea how to improve this, please leave a comment below. I will be sure to update this post accordingly if I find a good fix.
[ { "code": null, "e": 456, "s": 171, "text": "I am currently using my COVID-19 imposed quarantine to expand my deep learning skills by completing the Deep Reinforcement Learning Nanodegree from Udacity. Almost immediately I ran into the tedious problem of getting my simulations to render properly when training on remote servers." }, { "code": null, "e": 800, "s": 456, "text": "In particular, getting OpenAI Gym environments to render properly in remote servers such as those supporting popular free compute facilities such as Google Colab and Binder turned out to be more challenging than I expected. In this post, I lay out my solution in the hopes that I might save others time and effort to work it out independently." }, { "code": null, "e": 932, "s": 800, "text": "If you wish to use Google Colab, then this section is for you! Otherwise, you can skip to the next section for the Binder Preamble." }, { "code": null, "e": 1297, "s": 932, "text": "First, you will need to install the necessary X11 dependencies, in particular Xvfb, which is an X server that can run on machines with no display hardware and no physical input devices. You can install system dependencies inside your Colab notebook by prepending the install command with an exclamation mark (!)which will run the command inside its own Bash shell." }, { "code": null, "e": 1332, "s": 1297, "text": "!apt-get install -y xvfb x11-utils" }, { "code": null, "e": 1737, "s": 1332, "text": "Now that you have installed Xvfb, you need to install a Python wrapper pyvirtualdisplay in order to interact with Xvfb virtual displays from within Python. You also need to install the Python bindings for OpenGL: PyOpenGL and PyOpenGL-accelerate. The former is the actual Python bindings, the latter is an optional set of C (Cython) extensions providing acceleration of common operations in PyOpenGL 3.x." }, { "code": null, "e": 1845, "s": 1737, "text": "!pip install pyvirtualdisplay==0.2.* \\ PyOpenGL==3.1.* \\ PyOpenGL-accelerate==3.1.*" }, { "code": null, "e": 2206, "s": 1845, "text": "Next, you need to install the OpenAI Gym package. Note that depending on which Gym environment you are interested in working with you may need to add additional dependencies. Since I am going to simulate the LunarLander-v2 environment in my demo below I need to install the box2d extra which enables Gym environments that depend on the Box2D physics simulator." }, { "code": null, "e": 2238, "s": 2206, "text": "!pip install gym[box2d]==0.17.*" }, { "code": null, "e": 2378, "s": 2238, "text": "For simplicity, I have gathered all the software installation steps into a single code block that you can cut and paste into your notebook." }, { "code": null, "e": 2630, "s": 2378, "text": "%%bash# install required system dependenciesapt-get install -y xvfb x11-utils# install required python dependenciespip install gym[box2d]==0.17.* \\ pyvirtualdisplay==0.2.* \\ PyOpenGL==3.1.* \\ PyOpenGL-accelerate==3.1.*" }, { "code": null, "e": 2977, "s": 2630, "text": "Now that all the required software is installed you are ready to create a virtual display (i.e., a display that runs in the background) which the OpenAI Gym Envs can connect to for rendering purposes. You can actually check that there is no display at present by confirming that the value of the DISPLAY environment variable has not yet been set." }, { "code": null, "e": 2992, "s": 2977, "text": "!echo $DISPLAY" }, { "code": null, "e": 3225, "s": 2992, "text": "The code in the cell below creates a virtual display in the background that your Gym Envs can connect to for rendering. You can adjust the size of the virtual buffer as you like but you must set visible=False when working with Xvfb." }, { "code": null, "e": 3300, "s": 3225, "text": "This code only needs to be run once in your notebook to start the display." }, { "code": null, "e": 3463, "s": 3300, "text": "After running the code above in your notebook you can echo out the value of the DISPLAY environment variable again to confirm that you now have a display running." }, { "code": null, "e": 3512, "s": 3463, "text": "!echo $DISPLAY # should now be set to some value" }, { "code": null, "e": 3648, "s": 3512, "text": "For convenience, I have gathered the above steps into two cells that you can copy and paste into the top of you Google Colab notebooks." }, { "code": null, "e": 3705, "s": 3648, "text": "If you wish to use Binder, then this section is for you!" }, { "code": null, "e": 4035, "s": 3705, "text": "Unlike Google Colab, with Binder you can bake all the required dependencies (including the X11 system dependencies!) into the Docker image on which the Binder instance is based using Binder config files. These config files can either live in the root directory of your Git repo or in a binder sub-directory (my preferred choice)." }, { "code": null, "e": 4339, "s": 4035, "text": "The first config file that needs to be defined is the apt.txt file which is used to install system dependencies. You can just create an appropriately named file and then list the dependencies you want to install (one per line). After a bit of trial and error, I hit on the following winning combination." }, { "code": null, "e": 4366, "s": 4339, "text": "freeglut3-devxvfbx11-utils" }, { "code": null, "e": 4638, "s": 4366, "text": "The second and config file is the standard environment.yml file used to define a Conda environment. If you are unfamiliar with Conda, then I suggest that you check out my recent articles on Getting started with Conda and Managing project-specific environments with Conda." }, { "code": null, "e": 4842, "s": 4638, "text": "name: null channels: - conda-forge - defaults dependencies: - gym-box2d=0.17 - jupyterlab=2.0 - matplotlib=3.2 - pip=20.0 - pip: - -r file:requirements.txt - python=3.7 - pyvirtualdisplay=0.2" }, { "code": null, "e": 5015, "s": 4842, "text": "The final required config file is the requirements.txt file used by Conda to install any additional Python dependencies that are not available via Conda channels using pip." }, { "code": null, "e": 5057, "s": 5015, "text": "PyOpenGL==3.1.*PyOpenGL-accelerate==3.1.*" }, { "code": null, "e": 5219, "s": 5057, "text": "If you are interested in learning more about Binder, then check out the documentation for BinderHub which is the underlying technology behind the Binder project." }, { "code": null, "e": 5475, "s": 5219, "text": "Next, you need to create a virtual display in the background which the Gym Envs can connect to for rendering purposes. You can check that there is no display at present by confirming that the value of the DISPLAY environment variable has not yet been set." }, { "code": null, "e": 5490, "s": 5475, "text": "!echo $DISPLAY" }, { "code": null, "e": 5723, "s": 5490, "text": "The code in the cell below creates a virtual display in the background that your Gym Envs can connect to for rendering. You can adjust the size of the virtual buffer as you like but you must set visible=False when working with Xvfb." }, { "code": null, "e": 5793, "s": 5723, "text": "This code only needs to be run once per session to start the display." }, { "code": null, "e": 5939, "s": 5793, "text": "After running the cell above you can echo out the value of the DISPLAY environment variable again to confirm that you now have a display running." }, { "code": null, "e": 5954, "s": 5939, "text": "!echo $DISPLAY" }, { "code": null, "e": 6418, "s": 5954, "text": "Just to prove that the above setup works as advertised I will run a short simulation. First I define an Agent that chooses an action randomly from the set of possible actions and then define a function that can be used to create such agents. Then I wrap up the code to simulate a single episode of an OpenAI Gym environment. Note that the implementation assumes that the provided environment supports rgb_array rendering (which not all Gym environments support!)." } ]
Run a Python program from PHP
In PHP, the ‘shell_exec’ function can be used. It can be executed via the shell and the result can be returned as a string. It returns an error if NULL is passed from the command line or returns no output at all. Below is a code demonstration of the same − <?php $command_exec = escapeshellcmd('path-to-.py-file'); $str_output = shell_exec($command_exec); echo $str_output; ?> The right privileges need to be given so that the python script is successfully executed. Note − While working on a Unix type of platform, PHP code is executed as a web user. Hence, the web user should be given the necessary rights to the directories and sub-directories.
[ { "code": null, "e": 1275, "s": 1062, "text": "In PHP, the ‘shell_exec’ function can be used. It can be executed via the shell and the result can be returned as a string. It returns an error if NULL is passed from the command line or returns no output at all." }, { "code": null, "e": 1319, "s": 1275, "text": "Below is a code demonstration of the same −" }, { "code": null, "e": 1448, "s": 1319, "text": "<?php\n $command_exec = escapeshellcmd('path-to-.py-file');\n $str_output = shell_exec($command_exec);\n echo $str_output;\n?>" }, { "code": null, "e": 1538, "s": 1448, "text": "The right privileges need to be given so that the python script is successfully executed." }, { "code": null, "e": 1720, "s": 1538, "text": "Note − While working on a Unix type of platform, PHP code is executed as a web user. Hence, the web user should be given the necessary rights to the directories and sub-directories." } ]
Serving html pages from node.js
So far we sent html code directly from the send(0 function in response object. For sending larger code, we definitely require to have a separate file for html code. sendFile() function− Response object gives a sendFile() function to return a html file to client. How to provide path to html file in sendFile() ? We import the path core module of node.js. const path = require(‘path’); path has a join function . __dirname is a global variable which holds the actual path to project main folder. path.join(__dirname, ‘views’, ‘add-user.html’); This will refer to the actual file location of add-user html code. App.js const http = require('http'); const express = require('express'); const bodyParser = require('body-parser'); const route = require('./routes'); const app = express(); app.use(bodyParser.urlencoded({extended: false})); app.use('/test',route); app.use((req, res,next)=>{ res.status(404).send('<h1> Page not found </h1>'); }); const server = http.createServer(app); server.listen(3000); route.js const path = require('path'); const express = require('express'); const router = express.Router(); router.get('/add-username', (req, res,next)=>{ // res.send('<form action="/test/post-username" method="POST"> <input type="text" name="username"> <button type="submit"> Send </button> </form>'); res.sendFile(path.join(__dirname, 'views', 'add- user.html')); }); router.post('/post-username', (req, res, next)=>{ console.log('data: ', req.body.username); res.send('<h1>'+req.body.username+'</h1>'); }); module.exports = router; add-user.html <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form action="/test/post-username" method="POST"> <input type="text" name="username"> <button type="submit"> Send </button> </form> </body> </html> On running app: npm start Browser output: localhost:3000/test/add-username With the use of path module, it will work on any type of operating system without error. Every OS has different way of handling path, so path module takes care of it.
[ { "code": null, "e": 1227, "s": 1062, "text": "So far we sent html code directly from the send(0 function in response object. For sending larger code, we definitely require to have a separate file for html code." }, { "code": null, "e": 1248, "s": 1227, "text": "sendFile() function−" }, { "code": null, "e": 1325, "s": 1248, "text": "Response object gives a sendFile() function to return a html file to client." }, { "code": null, "e": 1374, "s": 1325, "text": "How to provide path to html file in sendFile() ?" }, { "code": null, "e": 1417, "s": 1374, "text": "We import the path core module of node.js." }, { "code": null, "e": 1447, "s": 1417, "text": "const path = require(‘path’);" }, { "code": null, "e": 1557, "s": 1447, "text": "path has a join function . __dirname is a global variable which holds the actual path to project main folder." }, { "code": null, "e": 1672, "s": 1557, "text": "path.join(__dirname, ‘views’, ‘add-user.html’); This will refer to the actual file location of add-user html code." }, { "code": null, "e": 1679, "s": 1672, "text": "App.js" }, { "code": null, "e": 2066, "s": 1679, "text": "const http = require('http');\nconst express = require('express');\nconst bodyParser = require('body-parser');\nconst route = require('./routes');\nconst app = express();\napp.use(bodyParser.urlencoded({extended: false}));\napp.use('/test',route);\napp.use((req, res,next)=>{\n res.status(404).send('<h1> Page not found </h1>');\n});\nconst server = http.createServer(app);\nserver.listen(3000);" }, { "code": null, "e": 2075, "s": 2066, "text": "route.js" }, { "code": null, "e": 2615, "s": 2075, "text": "const path = require('path');\nconst express = require('express');\nconst router = express.Router();\nrouter.get('/add-username', (req, res,next)=>{\n // res.send('<form action=\"/test/post-username\" method=\"POST\"> <input type=\"text\" name=\"username\"> <button type=\"submit\"> Send </button> </form>'); res.sendFile(path.join(__dirname, 'views', 'add- user.html'));\n});\nrouter.post('/post-username', (req, res, next)=>{\n console.log('data: ', req.body.username);\n res.send('<h1>'+req.body.username+'</h1>');\n});\nmodule.exports = router;" }, { "code": null, "e": 2629, "s": 2615, "text": "add-user.html" }, { "code": null, "e": 2967, "s": 2629, "text": "<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Document</title>\n</head>\n <body>\n <form action=\"/test/post-username\" method=\"POST\">\n <input type=\"text\" name=\"username\">\n <button type=\"submit\"> Send </button>\n </form>\n</body>\n</html>" }, { "code": null, "e": 2993, "s": 2967, "text": "On running app: npm start" }, { "code": null, "e": 3042, "s": 2993, "text": "Browser output: localhost:3000/test/add-username" }, { "code": null, "e": 3209, "s": 3042, "text": "With the use of path module, it will work on any type of operating system without error. Every OS has different way of handling path, so path module takes care of it." } ]
Q-Learning Algorithm: From Explanation to Implementation | by Amrani Amine | Towards Data Science
In my today’s medium post, I will teach you how to implement the Q-Learning algorithm. But before that, I will first explain the idea behind Q-Learning and its limitation. Please be sure to have some Reinforcement Learning (RL) basics. Otherwise, please check my previous post about the intuition and the key math behind RL. Well, let’s recall some definitions and equations that we need for implementing the Q-Learning algorithm. In RL, we have an environment that we want to learn. For doing that, we build an agent who will interact with the environment through a trial-error process. At each time step t, the agent is at a certain state s_t and chooses an action a_t to perform. The environment runs the selected action and returns a reward to the agent. The higher is the reward, the better is the action. The environment also tells the agent whether he is done or not. So an episode can be represented as a sequence of state-action-reward. The goal of the agent is to maximize the total rewards he will get from the environment. The function to maximize is called the expected discounted return function that we denote as G. To do so, the agent needs to find an optimal policy π which is a probability distribution of a given state over actions. Under the optimal policy, the Bellman Optimality Equation is satisfied: where q is the Action-Value function or Q-Value function. All these functions are explained in my previous post. In the Q-Learning algorithm, the goal is to learn iteratively the optimal Q-value function using the Bellman Optimality Equation. To do so, we store all the Q-values in a table that we will update at each time step using the Q-Learning iteration: where α is the learning rate, an important hyperparameter that we need to tune since it controls the convergence. Now, we would start implementing the Q-Learning algorithm. But, we need to talk about the exploration-exploitation trade-off. But Why? In the beginning, the agent has no idea about the environment. He is more likely to explore new things than to exploit his knowledge because...he has no knowledge. Through time steps, the agent will get more and more information about how the environment works and then, he is more likely to exploit his knowledge than exploring new things. If we skip this important step, the Q-Value function will converge to a local minimum which in most of the time, is far from the optimal Q-value function. To handle this, we will have a threshold which will decay every episode using exponential decay formula. By doing that, at every time step t, we will sample a variable uniformly over [0,1]. If the variable is smaller than the threshold, the agent will explore the environment. Otherwise, he will exploit his knowledge. where N_0 is the initial value and λ, a constant called decay constant. Below is an example of the exponential decay: Alright, now we can start coding. Here, we will use the FrozenLake environment of the gym python library which provides many environments including Atari games and CartPole. FrozenLake environment consists of a 4 by 4 grid representing a surface. The agent always starts from the state 0, [0,0] in the grid, and his goal is to reach the state 16, [4,4] in the grid. On his way, he could find some frozen surfaces or fall in a hole. If he falls, the episode is ended. When the agent reaches the goal, the reward is equal to one. Otherwise, it is equal to 0. First, we import the needed libraries. Numpy for accessing and updating the Q-table and gym to use the FrozenLake environment. import numpy as npimport gym Then, we instantiate our environment and get its sizes. env = gym.make("FrozenLake-v0")n_observations = env.observation_space.nn_actions = env.action_space.n We need to create and initialize the Q-table to 0. #Initialize the Q-table to 0Q_table = np.zeros((n_observations,n_actions))print(Q_table) We define the different parameters and hyperparameters we talked about earlier in this post To evaluate the agent training, we will store the total rewards he gets from the environment after each episode in a list that we will use after the training is finished. Now let’s go to the main loop where all the process will happen Please read all the comments to follow the algorithm. Once our agent is trained, we will test his performance using the rewards per episode list. We will do that by evaluating his performance every 1000 episodes. As we can notice, the performance of the agent is very bad in the beginning but he improved his efficiency through training. Q-learning algorithm is a very efficient way for an agent to learn how the environment works. Otherwise, in the case where the state space, the action space or both of them are continuous, it would be impossible to store all the Q-values because it would need a huge amount of memory. The agent would also need many more episodes to learn about the environment. As a solution, we can use a Deep Neural Network (DNN) to approximate the Q-Value function since DNNs are known for their efficiency to approximate functions. We talk about Deep Q-Networks and this will be the topic of my next post. I hope you understood the Q-Learning algorithm and enjoyed this post.
[ { "code": null, "e": 497, "s": 172, "text": "In my today’s medium post, I will teach you how to implement the Q-Learning algorithm. But before that, I will first explain the idea behind Q-Learning and its limitation. Please be sure to have some Reinforcement Learning (RL) basics. Otherwise, please check my previous post about the intuition and the key math behind RL." }, { "code": null, "e": 603, "s": 497, "text": "Well, let’s recall some definitions and equations that we need for implementing the Q-Learning algorithm." }, { "code": null, "e": 1118, "s": 603, "text": "In RL, we have an environment that we want to learn. For doing that, we build an agent who will interact with the environment through a trial-error process. At each time step t, the agent is at a certain state s_t and chooses an action a_t to perform. The environment runs the selected action and returns a reward to the agent. The higher is the reward, the better is the action. The environment also tells the agent whether he is done or not. So an episode can be represented as a sequence of state-action-reward." }, { "code": null, "e": 1303, "s": 1118, "text": "The goal of the agent is to maximize the total rewards he will get from the environment. The function to maximize is called the expected discounted return function that we denote as G." }, { "code": null, "e": 1424, "s": 1303, "text": "To do so, the agent needs to find an optimal policy π which is a probability distribution of a given state over actions." }, { "code": null, "e": 1496, "s": 1424, "text": "Under the optimal policy, the Bellman Optimality Equation is satisfied:" }, { "code": null, "e": 1554, "s": 1496, "text": "where q is the Action-Value function or Q-Value function." }, { "code": null, "e": 1609, "s": 1554, "text": "All these functions are explained in my previous post." }, { "code": null, "e": 1856, "s": 1609, "text": "In the Q-Learning algorithm, the goal is to learn iteratively the optimal Q-value function using the Bellman Optimality Equation. To do so, we store all the Q-values in a table that we will update at each time step using the Q-Learning iteration:" }, { "code": null, "e": 1970, "s": 1856, "text": "where α is the learning rate, an important hyperparameter that we need to tune since it controls the convergence." }, { "code": null, "e": 2920, "s": 1970, "text": "Now, we would start implementing the Q-Learning algorithm. But, we need to talk about the exploration-exploitation trade-off. But Why? In the beginning, the agent has no idea about the environment. He is more likely to explore new things than to exploit his knowledge because...he has no knowledge. Through time steps, the agent will get more and more information about how the environment works and then, he is more likely to exploit his knowledge than exploring new things. If we skip this important step, the Q-Value function will converge to a local minimum which in most of the time, is far from the optimal Q-value function. To handle this, we will have a threshold which will decay every episode using exponential decay formula. By doing that, at every time step t, we will sample a variable uniformly over [0,1]. If the variable is smaller than the threshold, the agent will explore the environment. Otherwise, he will exploit his knowledge." }, { "code": null, "e": 2992, "s": 2920, "text": "where N_0 is the initial value and λ, a constant called decay constant." }, { "code": null, "e": 3038, "s": 2992, "text": "Below is an example of the exponential decay:" }, { "code": null, "e": 3212, "s": 3038, "text": "Alright, now we can start coding. Here, we will use the FrozenLake environment of the gym python library which provides many environments including Atari games and CartPole." }, { "code": null, "e": 3595, "s": 3212, "text": "FrozenLake environment consists of a 4 by 4 grid representing a surface. The agent always starts from the state 0, [0,0] in the grid, and his goal is to reach the state 16, [4,4] in the grid. On his way, he could find some frozen surfaces or fall in a hole. If he falls, the episode is ended. When the agent reaches the goal, the reward is equal to one. Otherwise, it is equal to 0." }, { "code": null, "e": 3722, "s": 3595, "text": "First, we import the needed libraries. Numpy for accessing and updating the Q-table and gym to use the FrozenLake environment." }, { "code": null, "e": 3751, "s": 3722, "text": "import numpy as npimport gym" }, { "code": null, "e": 3807, "s": 3751, "text": "Then, we instantiate our environment and get its sizes." }, { "code": null, "e": 3909, "s": 3807, "text": "env = gym.make(\"FrozenLake-v0\")n_observations = env.observation_space.nn_actions = env.action_space.n" }, { "code": null, "e": 3960, "s": 3909, "text": "We need to create and initialize the Q-table to 0." }, { "code": null, "e": 4049, "s": 3960, "text": "#Initialize the Q-table to 0Q_table = np.zeros((n_observations,n_actions))print(Q_table)" }, { "code": null, "e": 4141, "s": 4049, "text": "We define the different parameters and hyperparameters we talked about earlier in this post" }, { "code": null, "e": 4312, "s": 4141, "text": "To evaluate the agent training, we will store the total rewards he gets from the environment after each episode in a list that we will use after the training is finished." }, { "code": null, "e": 4376, "s": 4312, "text": "Now let’s go to the main loop where all the process will happen" }, { "code": null, "e": 4430, "s": 4376, "text": "Please read all the comments to follow the algorithm." }, { "code": null, "e": 4589, "s": 4430, "text": "Once our agent is trained, we will test his performance using the rewards per episode list. We will do that by evaluating his performance every 1000 episodes." }, { "code": null, "e": 4714, "s": 4589, "text": "As we can notice, the performance of the agent is very bad in the beginning but he improved his efficiency through training." }, { "code": null, "e": 5308, "s": 4714, "text": "Q-learning algorithm is a very efficient way for an agent to learn how the environment works. Otherwise, in the case where the state space, the action space or both of them are continuous, it would be impossible to store all the Q-values because it would need a huge amount of memory. The agent would also need many more episodes to learn about the environment. As a solution, we can use a Deep Neural Network (DNN) to approximate the Q-Value function since DNNs are known for their efficiency to approximate functions. We talk about Deep Q-Networks and this will be the topic of my next post." } ]
HTML - Layouts
A webpage layout is very important to give better look to your website. It takes considerable time to design a website's layout with great look and feel. Now-a-days, all modern websites are using CSS and JavaScript based framework to come up with responsive and dynamic websites but you can create a good layout using simple HTML tables or division tags in combination with other formatting tags. This chapter will give you few examples on how to create a simple but working layout for your webpage using pure HTML and its attributes. The simplest and most popular way of creating layouts is using HTML <table> tag. These tables are arranged in columns and rows, so you can utilize these rows and columns in whatever way you like. For example, the following HTML layout example is achieved using a table with 3 rows and 2 columns but the header and footer column spans both columns using the colspan attribute − <!DOCTYPE html> <html> <head> <title>HTML Layout using Tables</title> </head> <body> <table width = "100%" border = "0"> <tr> <td colspan = "2" bgcolor = "#b5dcb3"> <h1>This is Web Page Main title</h1> </td> </tr> <tr valign = "top"> <td bgcolor = "#aaa" width = "50"> <b>Main Menu</b><br /> HTML<br /> PHP<br /> PERL... </td> <td bgcolor = "#eee" width = "100" height = "200"> Technical and Managerial Tutorials </td> </tr> <tr> <td colspan = "2" bgcolor = "#b5dcb3"> <center> Copyright © 2007 Tutorialspoint.com </center> </td> </tr> </table> </body> </html> This will produce the following result − You can design your webpage to put your web content in multiple pages. You can keep your content in middle column and you can use left column to use menu and right column can be used to put advertisement or some other stuff. This layout will be very similar to what we have at our website tutorialspoint.com. Here is an example to create three column layout − <!DOCTYPE html> <html> <head> <title>Three Column HTML Layout</title> </head> <body> <table width = "100%" border = "0"> <tr valign = "top"> <td bgcolor = "#aaa" width = "20%"> <b>Main Menu</b><br /> HTML<br /> PHP<br /> PERL... </td> <td bgcolor = "#b5dcb3" height = "200" width = "60%"> Technical and Managerial Tutorials </td> <td bgcolor = "#aaa" width = "20%"> <b>Right Menu</b><br /> HTML<br /> PHP<br /> PERL... </td> </tr> <table> </body> </html> This will produce the following result − The <div> element is a block level element used for grouping HTML elements. While the <div> tag is a block-level element, the HTML <span> element is used for grouping elements at an inline level. Although we can achieve pretty nice layouts with HTML tables, but tables weren't really designed as a layout tool. Tables are more suited to presenting tabular data. Note − This example makes use of Cascading Style Sheet (CSS), so before understanding this example you need to have a better understanding on how CSS works. Here we will try to achieve same result using <div> tag along with CSS, whatever you have achieved using <table> tag in previous example. <!DOCTYPE html> <html> <head> <title>HTML Layouts using DIV, SPAN</title> </head> <body> <div style = "width:100%"> <div style = "background-color:#b5dcb3; width:100%"> <h1>This is Web Page Main title</h1> </div> <div style = "background-color:#aaa; height:200px; width:100px; float:left;"> <div><b>Main Menu</b></div> HTML<br /> PHP<br /> PERL... </div> <div style = "background-color:#eee; height:200px; width:350px; float:left;" > <p>Technical and Managerial Tutorials</p> </div> <div style = "background-color:#aaa; height:200px; width:100px; float:right;"> <div><b>Right Menu</b></div> HTML<br /> PHP<br /> PERL... </div> <div style = "background-color:#b5dcb3; clear:both"> <center> Copyright © 2007 Tutorialspoint.com </center> </div> </div> </body> </html> This will produce the following result − Technical and Managerial Tutorials You can create better layout using DIV, SPAN along with CSS. For more information on CSS, please refer to CSS Tutorial. 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2528, "s": 2374, "text": "A webpage layout is very important to give better look to your website. It takes considerable time to design a website's layout with great look and feel." }, { "code": null, "e": 2909, "s": 2528, "text": "Now-a-days, all modern websites are using CSS and JavaScript based framework to come up with responsive and dynamic websites but you can create a good layout using simple HTML tables or division tags in combination with other formatting tags. This chapter will give you few examples on how to create a simple but working layout for your webpage using pure HTML and its attributes." }, { "code": null, "e": 3105, "s": 2909, "text": "The simplest and most popular way of creating layouts is using HTML <table> tag. These tables are arranged in columns and rows, so you can utilize these rows and columns in whatever way you like." }, { "code": null, "e": 3286, "s": 3105, "text": "For example, the following HTML layout example is achieved using a table with 3 rows and 2 columns but the header and footer column spans both columns using the colspan attribute −" }, { "code": null, "e": 4201, "s": 3286, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML Layout using Tables</title>\n </head>\n\n <body>\n <table width = \"100%\" border = \"0\">\n \n <tr>\n <td colspan = \"2\" bgcolor = \"#b5dcb3\">\n <h1>This is Web Page Main title</h1>\n </td>\n </tr>\n <tr valign = \"top\">\n <td bgcolor = \"#aaa\" width = \"50\">\n <b>Main Menu</b><br />\n HTML<br />\n PHP<br />\n PERL...\n </td>\n \n <td bgcolor = \"#eee\" width = \"100\" height = \"200\">\n Technical and Managerial Tutorials\n </td>\n </tr>\n <tr>\n <td colspan = \"2\" bgcolor = \"#b5dcb3\">\n <center>\n Copyright © 2007 Tutorialspoint.com\n </center>\n </td>\n </tr>\n \n </table>\n </body>\n\n</html>" }, { "code": null, "e": 4242, "s": 4201, "text": "This will produce the following result −" }, { "code": null, "e": 4551, "s": 4242, "text": "You can design your webpage to put your web content in multiple pages. You can keep your content in middle column and you can use left column to use menu and right column can be used to put advertisement or some other stuff. This layout will be very similar to what we have at our website tutorialspoint.com." }, { "code": null, "e": 4602, "s": 4551, "text": "Here is an example to create three column layout −" }, { "code": null, "e": 5345, "s": 4602, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Three Column HTML Layout</title>\n </head>\n\n <body>\n <table width = \"100%\" border = \"0\">\n \n <tr valign = \"top\">\n <td bgcolor = \"#aaa\" width = \"20%\">\n <b>Main Menu</b><br />\n HTML<br />\n PHP<br />\n PERL...\n </td>\n\t\t\t\t\n <td bgcolor = \"#b5dcb3\" height = \"200\" width = \"60%\">\n Technical and Managerial Tutorials\n </td>\n\t\t\t\t\n <td bgcolor = \"#aaa\" width = \"20%\">\n <b>Right Menu</b><br />\n HTML<br />\n PHP<br />\n PERL...\n </td>\n </tr>\n \n <table>\n </body>\n\n</html>" }, { "code": null, "e": 5386, "s": 5345, "text": "This will produce the following result −" }, { "code": null, "e": 5582, "s": 5386, "text": "The <div> element is a block level element used for grouping HTML elements. While the <div> tag is a block-level element, the HTML <span> element is used for grouping elements at an inline level." }, { "code": null, "e": 5748, "s": 5582, "text": "Although we can achieve pretty nice layouts with HTML tables, but tables weren't really designed as a layout tool. Tables are more suited to presenting tabular data." }, { "code": null, "e": 5905, "s": 5748, "text": "Note − This example makes use of Cascading Style Sheet (CSS), so before understanding this example you need to have a better understanding on how CSS works." }, { "code": null, "e": 6043, "s": 5905, "text": "Here we will try to achieve same result using <div> tag along with CSS, whatever you have achieved using <table> tag in previous example." }, { "code": null, "e": 7112, "s": 6043, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML Layouts using DIV, SPAN</title>\n </head>\n\n <body>\n <div style = \"width:100%\">\n\t\t\n <div style = \"background-color:#b5dcb3; width:100%\">\n <h1>This is Web Page Main title</h1>\n </div>\n\t\t\t\n <div style = \"background-color:#aaa; height:200px; width:100px; float:left;\">\n <div><b>Main Menu</b></div>\n HTML<br />\n PHP<br />\n PERL...\n </div>\n\t\t\t\n <div style = \"background-color:#eee; height:200px; width:350px; float:left;\" >\n <p>Technical and Managerial Tutorials</p>\n </div>\n\t\t\n <div style = \"background-color:#aaa; height:200px; width:100px; float:right;\">\n <div><b>Right Menu</b></div>\n HTML<br />\n PHP<br />\n PERL...\n </div>\n\t\t\t\n <div style = \"background-color:#b5dcb3; clear:both\">\n <center>\n Copyright © 2007 Tutorialspoint.com\n </center>\n </div>\n\t\t\t\n </div>\n </body>\n\n</html>" }, { "code": null, "e": 7153, "s": 7112, "text": "This will produce the following result −" }, { "code": null, "e": 7188, "s": 7153, "text": "Technical and Managerial Tutorials" }, { "code": null, "e": 7308, "s": 7188, "text": "You can create better layout using DIV, SPAN along with CSS. For more information on CSS, please refer to CSS Tutorial." }, { "code": null, "e": 7341, "s": 7308, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 7355, "s": 7341, "text": " Anadi Sharma" }, { "code": null, "e": 7390, "s": 7355, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7404, "s": 7390, "text": " Anadi Sharma" }, { "code": null, "e": 7439, "s": 7404, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7456, "s": 7439, "text": " Frahaan Hussain" }, { "code": null, "e": 7491, "s": 7456, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7522, "s": 7491, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 7555, "s": 7522, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 7586, "s": 7555, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 7621, "s": 7586, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7652, "s": 7621, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 7659, "s": 7652, "text": " Print" }, { "code": null, "e": 7670, "s": 7659, "text": " Add Notes" } ]
Loop through array and edit string JavaScript
Let’s say, we have to write a function, say translate() that accepts a string as the first argument and any number of words after that. The string will actually contain n $ signs like this − This $0 is more $1 just a $2. Then there will be 3 strings which will replace the corresponding places. For example − If the function call is like this − translate(‘This $0 is more $1 just a $2.’, ‘game’, ‘than’, ‘game’); The output of the function should be − This game is more than just a game. This functionality is more or less like the template injecting in JavaScript. Therefore, let’s write the code for this function − We will use the String.prototype.replace() method here. We know that if we use a regex pattern to match all occurrences and use a function as the second parameter, it gets executed for each match. We will do exactly the same here. The code for doing this will be − const str = 'This $0 is more $1 just a $2'; const translate = (str, ...texts) => { const regex = /\$(\d+)/gi; return str.replace(regex, (item, index) => { return texts[index]; }); }; console.log(translate(str, 'game', 'just', 'game')); The output in the console will be − This game is more just just a game
[ { "code": null, "e": 1198, "s": 1062, "text": "Let’s say, we have to write a function, say translate() that accepts a string as the first argument\nand any number of words after that." }, { "code": null, "e": 1253, "s": 1198, "text": "The string will actually contain n $ signs like this −" }, { "code": null, "e": 1357, "s": 1253, "text": "This $0 is more $1 just a $2.\nThen there will be 3 strings which will replace the corresponding places." }, { "code": null, "e": 1371, "s": 1357, "text": "For example −" }, { "code": null, "e": 1407, "s": 1371, "text": "If the function call is like this −" }, { "code": null, "e": 1475, "s": 1407, "text": "translate(‘This $0 is more $1 just a $2.’, ‘game’, ‘than’, ‘game’);" }, { "code": null, "e": 1514, "s": 1475, "text": "The output of the function should be −" }, { "code": null, "e": 1550, "s": 1514, "text": "This game is more than just a game." }, { "code": null, "e": 1628, "s": 1550, "text": "This functionality is more or less like the template injecting in JavaScript." }, { "code": null, "e": 1680, "s": 1628, "text": "Therefore, let’s write the code for this function −" }, { "code": null, "e": 1911, "s": 1680, "text": "We will use the String.prototype.replace() method here. We know that if we use a regex pattern\nto match all occurrences and use a function as the second parameter, it gets executed for each\nmatch. We will do exactly the same here." }, { "code": null, "e": 1945, "s": 1911, "text": "The code for doing this will be −" }, { "code": null, "e": 2196, "s": 1945, "text": "const str = 'This $0 is more $1 just a $2';\nconst translate = (str, ...texts) => {\n const regex = /\\$(\\d+)/gi;\n return str.replace(regex, (item, index) => {\n return texts[index];\n });\n};\nconsole.log(translate(str, 'game', 'just', 'game'));" }, { "code": null, "e": 2232, "s": 2196, "text": "The output in the console will be −" }, { "code": null, "e": 2267, "s": 2232, "text": "This game is more just just a game" } ]
Query API’s with Json Output in Python | by Alexandra Yanina | Towards Data Science
If you are a Data Science beginner, you will often work in courses and tutorials with .csv files that are easy to read into Pandas dataframes. In practice, however, you often need to access API’s and get data in Json format. This data often contains nested lists and dictionaries. So today I will explain how to query an API with JSON output and process this data to read it into a pandas dataframe. As an example I decided to use the cat facts API. This API contains funny information on the one hand, but on the other hand it is also relatively simple structured so it is well suited for beginners. With the Cat Facts API we can learn how to query the API in Python and how to convert the JSON output into a pandas dataframe. To follow this guide, basic Python knowledge as well as knowledge of the pandas package is required. The knowledge of what an API is, is assumed. First you need to look at the API documentation and find out the URL of the API interface and the endpoints. Then we need the specification what type of facts we want to get returned. In this example we query the Endpoint: GET /facts/random The base URL of all endpoints is https://cat-fact.herokuapp.com. More information about the Fact endpoint can be found at this URL Here you will also find information about the query parameters and how an API response will look like and how it will be structured. There are even sample queries available. We query this endpoint to retrieve the individual facts, with their ID, the user who uploaded the fact, and the creation date. Now let’s start creating the query in Python: import requestsimport pandas as pdimport jsonimport pprintimport seaborn as snsimport matplotlib.pyplot as plt First we have to import the necessary packages. In this tutorial we use requests to access the API via HTTP request. Pandas to read the JSON data into a DataFrame and do an explorative analysis. Seaborn and matplotlib are used to visualize the data. base_url = "https://cat-fact.herokuapp.com"facts = "/facts/random?animal_type=cat&amount=500" Now we save the base URL and the used endpoint in variables. first_response = requests.get(base_url+facts)response_list=first_response.json() To get the data as Json output you can use the requests package. To do this we call the request.get method with the base URL and the endpoint and store the returned values in the variable first_response. The Json output can then be parsed with the .json() method and stored in a list. Printing response_list shows us the structure of the obtained data: [{'used': False, 'source': 'api', 'type': 'cat', 'deleted': False, '_id': '591f97e88dec2e14e3c20b06', '__v': 0, 'text': 'A female Amur leopard gives birth to one to four cubs in each litter.', 'updatedAt': '2020-08-23T20:20:01.611Z', 'createdAt': '2018-05-16T20:20:03.145Z', 'status': {'verified': True, 'sentCount': 1}, 'user': '5a9ac18c7478810ea6c06381'}, {'used': False, 'source': 'user', 'type': 'cat', 'deleted': False, '_id': '5c87d03dec1e5c0aa37e0a6b', 'user': '5a9ac18c7478810ea6c06381', 'text': 'On October 24, 1963, a tuxedo cat named Félicette entered outer space aboard a French Véronique AG1 rocket and made feline history. Félicette returned from the 15-minute trip in once piece and earned the praise of French scientists, who said she made "a valuable contribution to research.".', 'createdAt': '2019-03-12T15:29:01.505Z', 'updatedAt': '2020-08-23T20:20:01.611Z', '__v': 0, 'status': {'verified': True, 'sentCount': 1}}, {'used': False, 'source': 'api', 'type': 'cat', 'deleted': False, '_id': '591f98783b90f7150a19c1b5', '__v': 0, 'text': "Cats have 32 muscles that control the outer ear (compared to human's 6 muscles each). A cat can rotate its ears independently 180 degrees, and can turn in the direction of sound 10 times faster than those of the best watchdog.", 'updatedAt': '2020-08-23T20:20:01.611Z', 'createdAt': '2018-01-04T01:10:54.673Z', 'status': {'verified': True, 'sentCount': 1}, 'user': '5a9ac18c7478810ea6c06381'}...] Now that we have the data in a list with sublists and dictionaries, we have to iterate through them and append the individual values of the respective keys to a new list called data. Getting the values from the subdictionaries requires using the .get method of the dictionary object. There are possibly innumerable ways to perform this step. This is one possible way to get the values from the sub-dictionaries. data=[]for response in response_list: data.append({ "used": response.get('used'), "source": response.get('source'), "text": response.get('text'), "updatedAt": response.get('updatedAt'), "createdAt": response.get('createdAt'), "user": response.get('user') }) Then we will simply transform our list into a pandas data frame with the pd.Dataframe method. catfacts_df=pd.DataFrame(data)catfacts_df.head() Now that we have successfully imported the data into a pandas dataframe, we can access more data via the API. It would be interesting to know which user has added the catfacts. To do this, we have to retrieve the endpoint “GET /facts?” again and merge the dataframes about the users with the catfacts_df data. Here you have to watch out that you dont get duplicate user values. We only want to use a list with the username and the user id, and use these information to join the two dataframes. But by obtaining data from the endpoint facts, we have to drop duplicate rows based on the user id. By doing that we get a list where every user is included once. We must also note that it is necessary to check whether a data point is complete and does not have missing values. We do this with an if-condition. This way we insert only complete data points into the list, otherwise the code would return an error. After creating a DataFrame with the data and dropping duplicate values based on the “user” column, we also reset the index. user_facts="/facts?"user_response=requests.get(base_url+user_facts)user_list=user_response.json()users=[]for response in user_list.values(): for user in response: if user.get('user'): users.append({ "user": user.get('user').get('_id'), "firstname":user.get('user').get('name').get('first'), "lastname":user.get('user').get('name').get('last')})userfacts_df= pd.DataFrame(users)userfacts_df = userfacts_df.drop_duplicates(subset = ["user"])userfacts_df.reset_index(inplace=True,drop=True)userfacts_df.tail() Printing the DataFrame shows that there are 83 unique catfact submitters. Now is the next important step to merge both data frames in one. For this we use the .merge method and specifiy that it should be merged on the left dataset (catfacts_df) on the column “user”. df=catfacts_df.merge(userfacts_df, how='left', on= "user") After joining both data frames it is important to confirm that the merge was correct. Before we continue with the visualization, it makes sense to insert the already written code into a clearly arranged function. Here we can also set the parameter “amount” to get a certain amount of catfacts. def get_cat_facts(amount): base_url="https://cat-fact.herokuapp.com" # get cat facts response=requests.get(base_url+ "/facts/random?animal_type=cat&amount=" + str(amount)) response_json=response.json() data=[] for response in response_json: data.append({ "used": response.get('used'), "source": response.get('source'), "text": response.get('text'), "updatedAt": response.get('updatedAt'), "createdAt": response.get('createdAt'), "user": response.get('user')}) #create catdf catfacts_df=pd.DataFrame(data) # get user data user_response=requests.get(base_url+ "/facts?") user_json=user_response.json() users=[] for response in user_json.values(): for user in response: if user.get('user'):users.append({ "user": user.get('user').get('_id'), "firstname":user.get('user').get('name').get('first'), "lastname":user.get('user').get('name').get('last')}) #create userdf userfacts_df=pd.DataFrame(users) userfacts_df = userfacts_df.drop_duplicates(subset = ["user"]) #joining both datframes df=catfacts_df.merge(userfacts_df, how='left', on= "user") return dfcat_facts_df = get_cat_facts(amount=500) In the last step we can visualize the data. Here I simply visualized how many facts a user has submitted. # catfacts per useragg_user_df=cat_facts_df.groupby(['user', 'firstname', 'lastname']).agg({ "text": 'count'})top_ten=agg_user_df.nlargest(10, 'text')bar_plot=sns.barplot(x = 'lastname', y = 'text', data = top_ten, palette = 'hls', capsize = 0.05, saturation = 8, errcolor = 'gray', errwidth = 2, ci = 'sd' )bar_plot.set_title('Facts by User')bar_plot.set_ylabel('Amount Cat Facts')bar_plot.set_xlabel('Lastname')plt.xticks(rotation=45)plt.show() In the GitHub repository you can get the whole code. I hope you enjoyed this Tutorial and I hope it will help you when working with APIs.
[ { "code": null, "e": 453, "s": 172, "text": "If you are a Data Science beginner, you will often work in courses and tutorials with .csv files that are easy to read into Pandas dataframes. In practice, however, you often need to access API’s and get data in Json format. This data often contains nested lists and dictionaries." }, { "code": null, "e": 900, "s": 453, "text": "So today I will explain how to query an API with JSON output and process this data to read it into a pandas dataframe. As an example I decided to use the cat facts API. This API contains funny information on the one hand, but on the other hand it is also relatively simple structured so it is well suited for beginners. With the Cat Facts API we can learn how to query the API in Python and how to convert the JSON output into a pandas dataframe." }, { "code": null, "e": 1046, "s": 900, "text": "To follow this guide, basic Python knowledge as well as knowledge of the pandas package is required. The knowledge of what an API is, is assumed." }, { "code": null, "e": 1269, "s": 1046, "text": "First you need to look at the API documentation and find out the URL of the API interface and the endpoints. Then we need the specification what type of facts we want to get returned. In this example we query the Endpoint:" }, { "code": null, "e": 1287, "s": 1269, "text": "GET /facts/random" }, { "code": null, "e": 1352, "s": 1287, "text": "The base URL of all endpoints is https://cat-fact.herokuapp.com." }, { "code": null, "e": 1719, "s": 1352, "text": "More information about the Fact endpoint can be found at this URL Here you will also find information about the query parameters and how an API response will look like and how it will be structured. There are even sample queries available. We query this endpoint to retrieve the individual facts, with their ID, the user who uploaded the fact, and the creation date." }, { "code": null, "e": 1765, "s": 1719, "text": "Now let’s start creating the query in Python:" }, { "code": null, "e": 1876, "s": 1765, "text": "import requestsimport pandas as pdimport jsonimport pprintimport seaborn as snsimport matplotlib.pyplot as plt" }, { "code": null, "e": 2126, "s": 1876, "text": "First we have to import the necessary packages. In this tutorial we use requests to access the API via HTTP request. Pandas to read the JSON data into a DataFrame and do an explorative analysis. Seaborn and matplotlib are used to visualize the data." }, { "code": null, "e": 2220, "s": 2126, "text": "base_url = \"https://cat-fact.herokuapp.com\"facts = \"/facts/random?animal_type=cat&amount=500\"" }, { "code": null, "e": 2281, "s": 2220, "text": "Now we save the base URL and the used endpoint in variables." }, { "code": null, "e": 2362, "s": 2281, "text": "first_response = requests.get(base_url+facts)response_list=first_response.json()" }, { "code": null, "e": 2715, "s": 2362, "text": "To get the data as Json output you can use the requests package. To do this we call the request.get method with the base URL and the endpoint and store the returned values in the variable first_response. The Json output can then be parsed with the .json() method and stored in a list. Printing response_list shows us the structure of the obtained data:" }, { "code": null, "e": 4202, "s": 2715, "text": "[{'used': False, 'source': 'api', 'type': 'cat', 'deleted': False, '_id': '591f97e88dec2e14e3c20b06', '__v': 0, 'text': 'A female Amur leopard gives birth to one to four cubs in each litter.', 'updatedAt': '2020-08-23T20:20:01.611Z', 'createdAt': '2018-05-16T20:20:03.145Z', 'status': {'verified': True, 'sentCount': 1}, 'user': '5a9ac18c7478810ea6c06381'}, {'used': False, 'source': 'user', 'type': 'cat', 'deleted': False, '_id': '5c87d03dec1e5c0aa37e0a6b', 'user': '5a9ac18c7478810ea6c06381', 'text': 'On October 24, 1963, a tuxedo cat named Félicette entered outer space aboard a French Véronique AG1 rocket and made feline history. Félicette returned from the 15-minute trip in once piece and earned the praise of French scientists, who said she made \"a valuable contribution to research.\".', 'createdAt': '2019-03-12T15:29:01.505Z', 'updatedAt': '2020-08-23T20:20:01.611Z', '__v': 0, 'status': {'verified': True, 'sentCount': 1}}, {'used': False, 'source': 'api', 'type': 'cat', 'deleted': False, '_id': '591f98783b90f7150a19c1b5', '__v': 0, 'text': \"Cats have 32 muscles that control the outer ear (compared to human's 6 muscles each). A cat can rotate its ears independently 180 degrees, and can turn in the direction of sound 10 times faster than those of the best watchdog.\", 'updatedAt': '2020-08-23T20:20:01.611Z', 'createdAt': '2018-01-04T01:10:54.673Z', 'status': {'verified': True, 'sentCount': 1}, 'user': '5a9ac18c7478810ea6c06381'}...]" }, { "code": null, "e": 4486, "s": 4202, "text": "Now that we have the data in a list with sublists and dictionaries, we have to iterate through them and append the individual values of the respective keys to a new list called data. Getting the values from the subdictionaries requires using the .get method of the dictionary object." }, { "code": null, "e": 4614, "s": 4486, "text": "There are possibly innumerable ways to perform this step. This is one possible way to get the values from the sub-dictionaries." }, { "code": null, "e": 4930, "s": 4614, "text": "data=[]for response in response_list: data.append({ \"used\": response.get('used'), \"source\": response.get('source'), \"text\": response.get('text'), \"updatedAt\": response.get('updatedAt'), \"createdAt\": response.get('createdAt'), \"user\": response.get('user') })" }, { "code": null, "e": 5024, "s": 4930, "text": "Then we will simply transform our list into a pandas data frame with the pd.Dataframe method." }, { "code": null, "e": 5073, "s": 5024, "text": "catfacts_df=pd.DataFrame(data)catfacts_df.head()" }, { "code": null, "e": 5730, "s": 5073, "text": "Now that we have successfully imported the data into a pandas dataframe, we can access more data via the API. It would be interesting to know which user has added the catfacts. To do this, we have to retrieve the endpoint “GET /facts?” again and merge the dataframes about the users with the catfacts_df data. Here you have to watch out that you dont get duplicate user values. We only want to use a list with the username and the user id, and use these information to join the two dataframes. But by obtaining data from the endpoint facts, we have to drop duplicate rows based on the user id. By doing that we get a list where every user is included once." }, { "code": null, "e": 6104, "s": 5730, "text": "We must also note that it is necessary to check whether a data point is complete and does not have missing values. We do this with an if-condition. This way we insert only complete data points into the list, otherwise the code would return an error. After creating a DataFrame with the data and dropping duplicate values based on the “user” column, we also reset the index." }, { "code": null, "e": 6672, "s": 6104, "text": "user_facts=\"/facts?\"user_response=requests.get(base_url+user_facts)user_list=user_response.json()users=[]for response in user_list.values(): for user in response: if user.get('user'): users.append({ \"user\": user.get('user').get('_id'), \"firstname\":user.get('user').get('name').get('first'), \"lastname\":user.get('user').get('name').get('last')})userfacts_df= pd.DataFrame(users)userfacts_df = userfacts_df.drop_duplicates(subset = [\"user\"])userfacts_df.reset_index(inplace=True,drop=True)userfacts_df.tail()" }, { "code": null, "e": 6746, "s": 6672, "text": "Printing the DataFrame shows that there are 83 unique catfact submitters." }, { "code": null, "e": 6939, "s": 6746, "text": "Now is the next important step to merge both data frames in one. For this we use the .merge method and specifiy that it should be merged on the left dataset (catfacts_df) on the column “user”." }, { "code": null, "e": 6998, "s": 6939, "text": "df=catfacts_df.merge(userfacts_df, how='left', on= \"user\")" }, { "code": null, "e": 7084, "s": 6998, "text": "After joining both data frames it is important to confirm that the merge was correct." }, { "code": null, "e": 7292, "s": 7084, "text": "Before we continue with the visualization, it makes sense to insert the already written code into a clearly arranged function. Here we can also set the parameter “amount” to get a certain amount of catfacts." }, { "code": null, "e": 8626, "s": 7292, "text": "def get_cat_facts(amount): base_url=\"https://cat-fact.herokuapp.com\" # get cat facts response=requests.get(base_url+ \"/facts/random?animal_type=cat&amount=\" + str(amount)) response_json=response.json() data=[] for response in response_json: data.append({ \"used\": response.get('used'), \"source\": response.get('source'), \"text\": response.get('text'), \"updatedAt\": response.get('updatedAt'), \"createdAt\": response.get('createdAt'), \"user\": response.get('user')}) #create catdf catfacts_df=pd.DataFrame(data) # get user data user_response=requests.get(base_url+ \"/facts?\") user_json=user_response.json() users=[] for response in user_json.values(): for user in response: if user.get('user'):users.append({ \"user\": user.get('user').get('_id'), \"firstname\":user.get('user').get('name').get('first'), \"lastname\":user.get('user').get('name').get('last')}) #create userdf userfacts_df=pd.DataFrame(users) userfacts_df = userfacts_df.drop_duplicates(subset = [\"user\"]) #joining both datframes df=catfacts_df.merge(userfacts_df, how='left', on= \"user\") return dfcat_facts_df = get_cat_facts(amount=500)" }, { "code": null, "e": 8732, "s": 8626, "text": "In the last step we can visualize the data. Here I simply visualized how many facts a user has submitted." }, { "code": null, "e": 9290, "s": 8732, "text": "# catfacts per useragg_user_df=cat_facts_df.groupby(['user', 'firstname', 'lastname']).agg({ \"text\": 'count'})top_ten=agg_user_df.nlargest(10, 'text')bar_plot=sns.barplot(x = 'lastname', y = 'text', data = top_ten, palette = 'hls', capsize = 0.05, saturation = 8, errcolor = 'gray', errwidth = 2, ci = 'sd' )bar_plot.set_title('Facts by User')bar_plot.set_ylabel('Amount Cat Facts')bar_plot.set_xlabel('Lastname')plt.xticks(rotation=45)plt.show()" } ]
Find the count of EMPTY or NULL columns in a MySQL table?
Let us first create a table − mysql> create table DemoTable781 ( Name varchar(100) ); Query OK, 0 rows affected (0.66 sec) Insert some records in the table using insert command − mysql> insert into DemoTable781 values(''); Query OK, 1 row affected (0.29 sec) mysql> insert into DemoTable781 values('Chris'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable781 values(''); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable781 values(null); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable781 values(null); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable781 values(''); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable781 values(null); Query OK, 1 row affected (0.28 sec) Display all records from the table using select statement − mysql> select *from DemoTable781; This will produce the following output - +-------+ | Name | +-------+ | | | Chris | | | | NULL | | NULL | | | | NULL | +-------+ 7 rows in set (0.00 sec) Here is the query to find the count of EMPTY or NULL columns in a MySQL table − mysql> (select SUM(CASE when Name IS NULL THEN 1 ELSE 0 END) AS NullCountAndEmptyCount from DemoTable781) UNION ALL (select SUM(CASE when Name='' THEN 1 ELSE 0 END) AS NullCountAndEmptyCount from DemoTable781); This will produce the following output - +------------------------+ | NullCountAndEmptyCount | +------------------------+ | 3 | | 3 | +------------------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table −" }, { "code": null, "e": 1188, "s": 1092, "text": "mysql> create table DemoTable781 (\n Name varchar(100)\n);\nQuery OK, 0 rows affected (0.66 sec)" }, { "code": null, "e": 1244, "s": 1188, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1815, "s": 1244, "text": "mysql> insert into DemoTable781 values('');\nQuery OK, 1 row affected (0.29 sec)\nmysql> insert into DemoTable781 values('Chris');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable781 values('');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable781 values(null);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable781 values(null);\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable781 values('');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable781 values(null);\nQuery OK, 1 row affected (0.28 sec)" }, { "code": null, "e": 1875, "s": 1815, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1909, "s": 1875, "text": "mysql> select *from DemoTable781;" }, { "code": null, "e": 1950, "s": 1909, "text": "This will produce the following output -" }, { "code": null, "e": 2085, "s": 1950, "text": "+-------+\n| Name |\n+-------+\n| |\n| Chris |\n| |\n| NULL |\n| NULL |\n| |\n| NULL |\n+-------+\n7 rows in set (0.00 sec)" }, { "code": null, "e": 2165, "s": 2085, "text": "Here is the query to find the count of EMPTY or NULL columns in a MySQL table −" }, { "code": null, "e": 2376, "s": 2165, "text": "mysql> (select SUM(CASE when Name IS NULL THEN 1 ELSE 0 END) AS NullCountAndEmptyCount from DemoTable781)\nUNION ALL\n(select SUM(CASE when Name='' THEN 1 ELSE 0 END) AS NullCountAndEmptyCount from DemoTable781);" }, { "code": null, "e": 2417, "s": 2376, "text": "This will produce the following output -" }, { "code": null, "e": 2604, "s": 2417, "text": "+------------------------+\n| NullCountAndEmptyCount |\n+------------------------+\n| 3 |\n| 3 |\n+------------------------+\n2 rows in set (0.00 sec)" } ]
Find the cordinates of the fourth vertex of a rectangle with given 3 vertices in Python
Suppose we have a grid of size Q * P, this grid contains exactly three asterisk '*' and every other cell there is dot '.', where '*' is for a vertex of a rectangle. We have to find the coordinates of the missing vertex. Here we will consider 1-based indexing. So, if the input is like grid = [ ".*.", "...", "*.*" ], then the output will be [1, 3], this is the missing coordinate. To solve this, we will follow these steps − p := number of rows p := number of rows q := number of columns q := number of columns row := make a map for all row number, and associated value is 0 row := make a map for all row number, and associated value is 0 col := make a map for all column number, and associated value is 0 col := make a map for all column number, and associated value is 0 for i in range 0 to p, dofor j in range 0 to q, doif grid[i, j] is same as '*', thenrow[i] := row[i] + 1col[j] := col[j] + 1for each k,v in row, doif v is same as 1, thenx_coord := k;for each k,v in col, doif v is same as 1, theny_coord := k; for i in range 0 to p, do for j in range 0 to q, doif grid[i, j] is same as '*', thenrow[i] := row[i] + 1col[j] := col[j] + 1 for j in range 0 to q, do if grid[i, j] is same as '*', thenrow[i] := row[i] + 1col[j] := col[j] + 1 if grid[i, j] is same as '*', then row[i] := row[i] + 1 row[i] := row[i] + 1 col[j] := col[j] + 1 col[j] := col[j] + 1 for each k,v in row, doif v is same as 1, thenx_coord := k; for each k,v in row, do if v is same as 1, thenx_coord := k; if v is same as 1, then x_coord := k; x_coord := k; for each k,v in col, doif v is same as 1, theny_coord := k; for each k,v in col, do if v is same as 1, theny_coord := k; if v is same as 1, then y_coord := k; y_coord := k; return(x_coord + 1, y_coord + 1) return(x_coord + 1, y_coord + 1) Let us see the following implementation to get better understanding − Live Demo def get_missing_vertex(grid) : p = len(grid) q = len(grid[0]) row = dict.fromkeys(range(p), 0) col = dict.fromkeys(range(q), 0) for i in range(p) : for j in range(q) : if (grid[i][j] == '*') : row[i] += 1 col[j] += 1 for k,v in row.items() : if (v == 1) : x_coord = k; for k,v in col.items() : if (v == 1) : y_coord = k; return (x_coord + 1, y_coord + 1) grid = [".*.", "...", "*.*"] print(get_missing_vertex(grid)) [".*.", "...", "*.*"] (1, 3)
[ { "code": null, "e": 1322, "s": 1062, "text": "Suppose we have a grid of size Q * P, this grid contains exactly three asterisk '*' and every other cell there is dot '.', where '*' is for a vertex of a rectangle. We have to find the coordinates of the missing vertex. Here we will consider 1-based indexing." }, { "code": null, "e": 1443, "s": 1322, "text": "So, if the input is like grid = [ \".*.\", \"...\", \"*.*\" ], then the output will be [1, 3], this is the missing coordinate." }, { "code": null, "e": 1487, "s": 1443, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1507, "s": 1487, "text": "p := number of rows" }, { "code": null, "e": 1527, "s": 1507, "text": "p := number of rows" }, { "code": null, "e": 1550, "s": 1527, "text": "q := number of columns" }, { "code": null, "e": 1573, "s": 1550, "text": "q := number of columns" }, { "code": null, "e": 1637, "s": 1573, "text": "row := make a map for all row number, and associated value is 0" }, { "code": null, "e": 1701, "s": 1637, "text": "row := make a map for all row number, and associated value is 0" }, { "code": null, "e": 1768, "s": 1701, "text": "col := make a map for all column number, and associated value is 0" }, { "code": null, "e": 1835, "s": 1768, "text": "col := make a map for all column number, and associated value is 0" }, { "code": null, "e": 2078, "s": 1835, "text": "for i in range 0 to p, dofor j in range 0 to q, doif grid[i, j] is same as '*', thenrow[i] := row[i] + 1col[j] := col[j] + 1for each k,v in row, doif v is same as 1, thenx_coord := k;for each k,v in col, doif v is same as 1, theny_coord := k;" }, { "code": null, "e": 2104, "s": 2078, "text": "for i in range 0 to p, do" }, { "code": null, "e": 2204, "s": 2104, "text": "for j in range 0 to q, doif grid[i, j] is same as '*', thenrow[i] := row[i] + 1col[j] := col[j] + 1" }, { "code": null, "e": 2230, "s": 2204, "text": "for j in range 0 to q, do" }, { "code": null, "e": 2305, "s": 2230, "text": "if grid[i, j] is same as '*', thenrow[i] := row[i] + 1col[j] := col[j] + 1" }, { "code": null, "e": 2340, "s": 2305, "text": "if grid[i, j] is same as '*', then" }, { "code": null, "e": 2361, "s": 2340, "text": "row[i] := row[i] + 1" }, { "code": null, "e": 2382, "s": 2361, "text": "row[i] := row[i] + 1" }, { "code": null, "e": 2403, "s": 2382, "text": "col[j] := col[j] + 1" }, { "code": null, "e": 2424, "s": 2403, "text": "col[j] := col[j] + 1" }, { "code": null, "e": 2484, "s": 2424, "text": "for each k,v in row, doif v is same as 1, thenx_coord := k;" }, { "code": null, "e": 2508, "s": 2484, "text": "for each k,v in row, do" }, { "code": null, "e": 2545, "s": 2508, "text": "if v is same as 1, thenx_coord := k;" }, { "code": null, "e": 2569, "s": 2545, "text": "if v is same as 1, then" }, { "code": null, "e": 2583, "s": 2569, "text": "x_coord := k;" }, { "code": null, "e": 2597, "s": 2583, "text": "x_coord := k;" }, { "code": null, "e": 2657, "s": 2597, "text": "for each k,v in col, doif v is same as 1, theny_coord := k;" }, { "code": null, "e": 2681, "s": 2657, "text": "for each k,v in col, do" }, { "code": null, "e": 2718, "s": 2681, "text": "if v is same as 1, theny_coord := k;" }, { "code": null, "e": 2742, "s": 2718, "text": "if v is same as 1, then" }, { "code": null, "e": 2756, "s": 2742, "text": "y_coord := k;" }, { "code": null, "e": 2770, "s": 2756, "text": "y_coord := k;" }, { "code": null, "e": 2803, "s": 2770, "text": "return(x_coord + 1, y_coord + 1)" }, { "code": null, "e": 2836, "s": 2803, "text": "return(x_coord + 1, y_coord + 1)" }, { "code": null, "e": 2906, "s": 2836, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2917, "s": 2906, "text": " Live Demo" }, { "code": null, "e": 3426, "s": 2917, "text": "def get_missing_vertex(grid) :\n p = len(grid)\n q = len(grid[0])\n row = dict.fromkeys(range(p), 0)\n col = dict.fromkeys(range(q), 0)\n for i in range(p) :\n for j in range(q) :\n if (grid[i][j] == '*') :\n row[i] += 1\n col[j] += 1\n for k,v in row.items() :\n if (v == 1) :\n x_coord = k;\n for k,v in col.items() :\n if (v == 1) :\n y_coord = k;\n return (x_coord + 1, y_coord + 1)\ngrid = [\".*.\", \"...\", \"*.*\"]\nprint(get_missing_vertex(grid))" }, { "code": null, "e": 3448, "s": 3426, "text": "[\".*.\", \"...\", \"*.*\"]" }, { "code": null, "e": 3455, "s": 3448, "text": "(1, 3)" } ]
Node.js Date.parse() API - GeeksforGeeks
12 Mar, 2021 The date-and-time.Date.parse() is a minimalist collection of functions for manipulating JS date and time module which is used to parse the date according to a certain pattern. Required Module: Install the module by npm or used it locally. By using npm. npm install date-and-time --save By using CDN link. <script src="/path/to/date-and-time.min.js"></script> Syntax: parse(dateString, arg) Parameters: This method takes the following arguments as parameters: dateString: It is the string object of the date arg: It is the required date format. Return Value: This method returns parsed date and time. Example 1: index.js // Node.js program to demonstrate the // Date.parse() method // Importing moduleconst date = require('date-and-time') // Creating object of current date and time // by using Date() const now = new Date('07-03-2021'); // Parsing the date and time// by using date.parse() methodconst value = date.parse(now.toLocaleDateString(),'D/M/YYYY'); // Display the resultconsole.log("parsed date and time : " + value) Run the index.js file using the following command: node index.js Output: parsed date and time : Thu Jan 01 1970 00:00:00 GMT+0530 (India Standard Time) Example 2: index.js // Node.js program to demonstrate the // Date.parse() method // Importing moduleconst date = require('date-and-time') // Parsing the date and time// by using date.parse() methodconst value = date.parse('23:14:05 GMT+0900','HH:mm:ss [GMT]Z'); // Display the resultconsole.log("Parsed date and time : " + value) Run the index.js file using the following command: node index.js Output: Parsed date and time : Thu Jan 01 1970 19:44:05 GMT+0530 (India Standard Time) Reference: https://github.com/knowledgecode/date-and-time NodeJS date-time NodeJS-API Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to build a basic CRUD app with Node.js and ReactJS ? How to connect Node.js with React.js ? Mongoose Populate() Method Express.js req.params Property Mongoose find() Function Top 10 Front End Developer Skills That You Need in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24531, "s": 24503, "text": "\n12 Mar, 2021" }, { "code": null, "e": 24707, "s": 24531, "text": "The date-and-time.Date.parse() is a minimalist collection of functions for manipulating JS date and time module which is used to parse the date according to a certain pattern." }, { "code": null, "e": 24770, "s": 24707, "text": "Required Module: Install the module by npm or used it locally." }, { "code": null, "e": 24784, "s": 24770, "text": "By using npm." }, { "code": null, "e": 24817, "s": 24784, "text": "npm install date-and-time --save" }, { "code": null, "e": 24836, "s": 24817, "text": "By using CDN link." }, { "code": null, "e": 24890, "s": 24836, "text": "<script src=\"/path/to/date-and-time.min.js\"></script>" }, { "code": null, "e": 24898, "s": 24890, "text": "Syntax:" }, { "code": null, "e": 24921, "s": 24898, "text": "parse(dateString, arg)" }, { "code": null, "e": 24990, "s": 24921, "text": "Parameters: This method takes the following arguments as parameters:" }, { "code": null, "e": 25038, "s": 24990, "text": "dateString: It is the string object of the date" }, { "code": null, "e": 25075, "s": 25038, "text": "arg: It is the required date format." }, { "code": null, "e": 25131, "s": 25075, "text": "Return Value: This method returns parsed date and time." }, { "code": null, "e": 25142, "s": 25131, "text": "Example 1:" }, { "code": null, "e": 25151, "s": 25142, "text": "index.js" }, { "code": "// Node.js program to demonstrate the // Date.parse() method // Importing moduleconst date = require('date-and-time') // Creating object of current date and time // by using Date() const now = new Date('07-03-2021'); // Parsing the date and time// by using date.parse() methodconst value = date.parse(now.toLocaleDateString(),'D/M/YYYY'); // Display the resultconsole.log(\"parsed date and time : \" + value)", "e": 25565, "s": 25151, "text": null }, { "code": null, "e": 25616, "s": 25565, "text": "Run the index.js file using the following command:" }, { "code": null, "e": 25630, "s": 25616, "text": "node index.js" }, { "code": null, "e": 25638, "s": 25630, "text": "Output:" }, { "code": null, "e": 25717, "s": 25638, "text": "parsed date and time :\nThu Jan 01 1970 00:00:00 GMT+0530 (India Standard Time)" }, { "code": null, "e": 25728, "s": 25717, "text": "Example 2:" }, { "code": null, "e": 25737, "s": 25728, "text": "index.js" }, { "code": "// Node.js program to demonstrate the // Date.parse() method // Importing moduleconst date = require('date-and-time') // Parsing the date and time// by using date.parse() methodconst value = date.parse('23:14:05 GMT+0900','HH:mm:ss [GMT]Z'); // Display the resultconsole.log(\"Parsed date and time : \" + value)", "e": 26051, "s": 25737, "text": null }, { "code": null, "e": 26102, "s": 26051, "text": "Run the index.js file using the following command:" }, { "code": null, "e": 26116, "s": 26102, "text": "node index.js" }, { "code": null, "e": 26124, "s": 26116, "text": "Output:" }, { "code": null, "e": 26203, "s": 26124, "text": "Parsed date and time :\nThu Jan 01 1970 19:44:05 GMT+0530 (India Standard Time)" }, { "code": null, "e": 26261, "s": 26203, "text": "Reference: https://github.com/knowledgecode/date-and-time" }, { "code": null, "e": 26278, "s": 26261, "text": "NodeJS date-time" }, { "code": null, "e": 26289, "s": 26278, "text": "NodeJS-API" }, { "code": null, "e": 26297, "s": 26289, "text": "Node.js" }, { "code": null, "e": 26314, "s": 26297, "text": "Web Technologies" }, { "code": null, "e": 26412, "s": 26314, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26421, "s": 26412, "text": "Comments" }, { "code": null, "e": 26434, "s": 26421, "text": "Old Comments" }, { "code": null, "e": 26491, "s": 26434, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 26530, "s": 26491, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 26557, "s": 26530, "text": "Mongoose Populate() Method" }, { "code": null, "e": 26588, "s": 26557, "text": "Express.js req.params Property" }, { "code": null, "e": 26613, "s": 26588, "text": "Mongoose find() Function" }, { "code": null, "e": 26669, "s": 26613, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26731, "s": 26669, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26774, "s": 26731, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26824, "s": 26774, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python 3 - os.chmod() Method
The method chmod() changes the mode of path to the passed numeric mode. The mode may take one of the following values or bitwise ORed combinations of them − stat.S_ISUID − Set user ID on execution. stat.S_ISUID − Set user ID on execution. stat.S_ISGID − Set group ID on execution. stat.S_ISGID − Set group ID on execution. stat.S_ENFMT − Record locking enforced. stat.S_ENFMT − Record locking enforced. stat.S_ISVTX − Save text image after execution. stat.S_ISVTX − Save text image after execution. stat.S_IREAD − Read by owner. stat.S_IREAD − Read by owner. stat.S_IWRITE − Write by owner. stat.S_IWRITE − Write by owner. stat.S_IEXEC − Execute by owner. stat.S_IEXEC − Execute by owner. stat.S_IRWXU − Read, write, and execute by owner. stat.S_IRWXU − Read, write, and execute by owner. stat.S_IRUSR − Read by owner. stat.S_IRUSR − Read by owner. stat.S_IWUSR − Write by owner. stat.S_IWUSR − Write by owner. stat.S_IXUSR − Execute by owner. stat.S_IXUSR − Execute by owner. stat.S_IRWXG − Read, write, and execute by group. stat.S_IRWXG − Read, write, and execute by group. stat.S_IRGRP − Read by group. stat.S_IRGRP − Read by group. stat.S_IWGRP − Write by group. stat.S_IWGRP − Write by group. stat.S_IXGRP − Execute by group. stat.S_IXGRP − Execute by group. stat.S_IRWXO − Read, write, and execute by others. stat.S_IRWXO − Read, write, and execute by others. stat.S_IROTH − Read by others. stat.S_IROTH − Read by others. stat.S_IWOTH − Write by others. stat.S_IWOTH − Write by others. stat.S_IXOTH − Execute by others. stat.S_IXOTH − Execute by others. Following is the syntax for chmod() method − os.chmod(path, mode) path − This is the path for which mode would be set. path − This is the path for which mode would be set. mode − This may take one of the above mentioned values or bitwise ORed combinations of them. mode − This may take one of the above mentioned values or bitwise ORed combinations of them. This method does not return any value. Note − Although Windows supports chmod(), you can only set the file’s read-only flag with it (via the stat.S_IWRITE and stat.S_IREAD constants or a corresponding integer value). All other bits are ignored. The following example shows the usage of chmod() method. #!/usr/bin/python3 import os, sys, stat # Assuming /tmp/foo.txt exists, Set a file execute by the group. os.chmod("/tmp/foo.txt", stat.S_IXGRP) # Set a file write by others. os.chmod("/tmp/foo.txt", stat.S_IWOTH) print ("Changed mode successfully!!") When we run the above program, it produces the following result − Changed mode successfully!! 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": 2497, "s": 2340, "text": "The method chmod() changes the mode of path to the passed numeric mode. The mode may take one of the following values or bitwise ORed combinations of them −" }, { "code": null, "e": 2538, "s": 2497, "text": "stat.S_ISUID − Set user ID on execution." }, { "code": null, "e": 2579, "s": 2538, "text": "stat.S_ISUID − Set user ID on execution." }, { "code": null, "e": 2621, "s": 2579, "text": "stat.S_ISGID − Set group ID on execution." }, { "code": null, "e": 2663, "s": 2621, "text": "stat.S_ISGID − Set group ID on execution." }, { "code": null, "e": 2703, "s": 2663, "text": "stat.S_ENFMT − Record locking enforced." }, { "code": null, "e": 2743, "s": 2703, "text": "stat.S_ENFMT − Record locking enforced." }, { "code": null, "e": 2791, "s": 2743, "text": "stat.S_ISVTX − Save text image after execution." }, { "code": null, "e": 2839, "s": 2791, "text": "stat.S_ISVTX − Save text image after execution." }, { "code": null, "e": 2869, "s": 2839, "text": "stat.S_IREAD − Read by owner." }, { "code": null, "e": 2899, "s": 2869, "text": "stat.S_IREAD − Read by owner." }, { "code": null, "e": 2931, "s": 2899, "text": "stat.S_IWRITE − Write by owner." }, { "code": null, "e": 2963, "s": 2931, "text": "stat.S_IWRITE − Write by owner." }, { "code": null, "e": 2996, "s": 2963, "text": "stat.S_IEXEC − Execute by owner." }, { "code": null, "e": 3029, "s": 2996, "text": "stat.S_IEXEC − Execute by owner." }, { "code": null, "e": 3079, "s": 3029, "text": "stat.S_IRWXU − Read, write, and execute by owner." }, { "code": null, "e": 3129, "s": 3079, "text": "stat.S_IRWXU − Read, write, and execute by owner." }, { "code": null, "e": 3159, "s": 3129, "text": "stat.S_IRUSR − Read by owner." }, { "code": null, "e": 3189, "s": 3159, "text": "stat.S_IRUSR − Read by owner." }, { "code": null, "e": 3220, "s": 3189, "text": "stat.S_IWUSR − Write by owner." }, { "code": null, "e": 3251, "s": 3220, "text": "stat.S_IWUSR − Write by owner." }, { "code": null, "e": 3284, "s": 3251, "text": "stat.S_IXUSR − Execute by owner." }, { "code": null, "e": 3317, "s": 3284, "text": "stat.S_IXUSR − Execute by owner." }, { "code": null, "e": 3367, "s": 3317, "text": "stat.S_IRWXG − Read, write, and execute by group." }, { "code": null, "e": 3417, "s": 3367, "text": "stat.S_IRWXG − Read, write, and execute by group." }, { "code": null, "e": 3448, "s": 3417, "text": "stat.S_IRGRP − Read by group. " }, { "code": null, "e": 3479, "s": 3448, "text": "stat.S_IRGRP − Read by group. " }, { "code": null, "e": 3511, "s": 3479, "text": "stat.S_IWGRP − Write by group. " }, { "code": null, "e": 3543, "s": 3511, "text": "stat.S_IWGRP − Write by group. " }, { "code": null, "e": 3576, "s": 3543, "text": "stat.S_IXGRP − Execute by group." }, { "code": null, "e": 3609, "s": 3576, "text": "stat.S_IXGRP − Execute by group." }, { "code": null, "e": 3660, "s": 3609, "text": "stat.S_IRWXO − Read, write, and execute by others." }, { "code": null, "e": 3711, "s": 3660, "text": "stat.S_IRWXO − Read, write, and execute by others." }, { "code": null, "e": 3742, "s": 3711, "text": "stat.S_IROTH − Read by others." }, { "code": null, "e": 3773, "s": 3742, "text": "stat.S_IROTH − Read by others." }, { "code": null, "e": 3805, "s": 3773, "text": "stat.S_IWOTH − Write by others." }, { "code": null, "e": 3837, "s": 3805, "text": "stat.S_IWOTH − Write by others." }, { "code": null, "e": 3871, "s": 3837, "text": "stat.S_IXOTH − Execute by others." }, { "code": null, "e": 3905, "s": 3871, "text": "stat.S_IXOTH − Execute by others." }, { "code": null, "e": 3950, "s": 3905, "text": "Following is the syntax for chmod() method −" }, { "code": null, "e": 3972, "s": 3950, "text": "os.chmod(path, mode)\n" }, { "code": null, "e": 4025, "s": 3972, "text": "path − This is the path for which mode would be set." }, { "code": null, "e": 4078, "s": 4025, "text": "path − This is the path for which mode would be set." }, { "code": null, "e": 4171, "s": 4078, "text": "mode − This may take one of the above mentioned values or bitwise ORed combinations of them." }, { "code": null, "e": 4264, "s": 4171, "text": "mode − This may take one of the above mentioned values or bitwise ORed combinations of them." }, { "code": null, "e": 4303, "s": 4264, "text": "This method does not return any value." }, { "code": null, "e": 4509, "s": 4303, "text": "Note − Although Windows supports chmod(), you can only set the file’s read-only flag with it (via the stat.S_IWRITE and stat.S_IREAD constants or a corresponding integer value). All other bits are ignored." }, { "code": null, "e": 4566, "s": 4509, "text": "The following example shows the usage of chmod() method." }, { "code": null, "e": 4820, "s": 4566, "text": "#!/usr/bin/python3\nimport os, sys, stat\n\n# Assuming /tmp/foo.txt exists, Set a file execute by the group.\nos.chmod(\"/tmp/foo.txt\", stat.S_IXGRP)\n\n# Set a file write by others.\nos.chmod(\"/tmp/foo.txt\", stat.S_IWOTH)\n\nprint (\"Changed mode successfully!!\")" }, { "code": null, "e": 4886, "s": 4820, "text": "When we run the above program, it produces the following result −" }, { "code": null, "e": 4915, "s": 4886, "text": "Changed mode successfully!!\n" }, { "code": null, "e": 4952, "s": 4915, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4968, "s": 4952, "text": " Malhar Lathkar" }, { "code": null, "e": 5001, "s": 4968, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 5020, "s": 5001, "text": " Arnab Chakraborty" }, { "code": null, "e": 5055, "s": 5020, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 5077, "s": 5055, "text": " In28Minutes Official" }, { "code": null, "e": 5111, "s": 5077, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 5139, "s": 5111, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5174, "s": 5139, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 5188, "s": 5174, "text": " Lets Kode It" }, { "code": null, "e": 5221, "s": 5188, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 5238, "s": 5221, "text": " Abhilash Nelson" }, { "code": null, "e": 5245, "s": 5238, "text": " Print" }, { "code": null, "e": 5256, "s": 5245, "text": " Add Notes" } ]
PL/SQL - Nested IF-THEN-ELSE Statements
It is always legal in PL/SQL programming to nest the IF-ELSE statements, which means you can use one IF or ELSE IF statement inside another IF or ELSE IF statement(s). IF( boolean_expression 1)THEN -- executes when the boolean expression 1 is true IF(boolean_expression 2) THEN -- executes when the boolean expression 2 is true sequence-of-statements; END IF; ELSE -- executes when the boolean expression 1 is not true else-statements; END IF; DECLARE a number(3) := 100; b number(3) := 200; BEGIN -- check the boolean condition IF( a = 100 ) THEN -- if condition is true then check the following IF( b = 200 ) THEN -- if condition is true then print the following dbms_output.put_line('Value of a is 100 and b is 200' ); END IF; END IF; dbms_output.put_line('Exact value of a is : ' || a ); dbms_output.put_line('Exact value of b is : ' || b ); END; / When the above code is executed at the SQL prompt, it produces the following result − Value of a is 100 and b is 200 Exact value of a is : 100 Exact value of b is : 200 PL/SQL procedure successfully completed. Print Add Notes Bookmark this page
[ { "code": null, "e": 2233, "s": 2065, "text": "It is always legal in PL/SQL programming to nest the IF-ELSE statements, which means you can use one IF or ELSE IF statement inside another IF or ELSE IF statement(s)." }, { "code": null, "e": 2549, "s": 2233, "text": "IF( boolean_expression 1)THEN \n -- executes when the boolean expression 1 is true \n IF(boolean_expression 2) THEN \n -- executes when the boolean expression 2 is true \n sequence-of-statements; \n END IF; \nELSE \n -- executes when the boolean expression 1 is not true \n else-statements; \nEND IF; \n" }, { "code": null, "e": 3025, "s": 2549, "text": "DECLARE \n a number(3) := 100; \n b number(3) := 200; \nBEGIN \n -- check the boolean condition \n IF( a = 100 ) THEN \n -- if condition is true then check the following \n IF( b = 200 ) THEN \n -- if condition is true then print the following \n dbms_output.put_line('Value of a is 100 and b is 200' ); \n END IF; \n END IF; \n dbms_output.put_line('Exact value of a is : ' || a ); \n dbms_output.put_line('Exact value of b is : ' || b ); \nEND; \n/ " }, { "code": null, "e": 3111, "s": 3025, "text": "When the above code is executed at the SQL prompt, it produces the following result −" }, { "code": null, "e": 3242, "s": 3111, "text": "Value of a is 100 and b is 200 \nExact value of a is : 100 \nExact value of b is : 200 \n\nPL/SQL procedure successfully completed. \n" }, { "code": null, "e": 3249, "s": 3242, "text": " Print" }, { "code": null, "e": 3260, "s": 3249, "text": " Add Notes" } ]
Find the minimum element in a sorted and rotated array - GeeksforGeeks
23 Feb, 2022 A sorted array is rotated at some unknown point, find the minimum element in it. The following solution assumes that all elements are distinct. Examples: Input: {5, 6, 1, 2, 3, 4} Output: 1 Input: {1, 2, 3, 4} Output: 1 Input: {2, 1} Output: 1 A simple solution is to traverse the complete array and find a minimum. This solution requires O(n) time. We can do it in O(Logn) using Binary Search. If we take a closer look at the above examples, we can easily figure out the following pattern: The minimum element is the only element whose previous is greater than it. If there is no previous element, then there is no rotation (the first element is minimum). We check this condition for the middle element by comparing it with (mid-1)’th and (mid+1)’th elements. If the minimum element is not at the middle (neither mid nor mid + 1), then the minimum element lies in either the left half or right half. If the middle element is smaller than the last element, then the minimum element lies in the left halfElse minimum element lies in the right half. If the middle element is smaller than the last element, then the minimum element lies in the left halfElse minimum element lies in the right half. If the middle element is smaller than the last element, then the minimum element lies in the left half Else minimum element lies in the right half. We strongly recommend you to try it yourself before seeing the following implementation. C C++ Java Python3 C# PHP Javascript // C program to find minimum element in a sorted and rotated array#include <stdio.h> int findMin(int arr[], int low, int high){ // This condition is needed to handle the case when array is not // rotated at all if (high < low) return arr[0]; // If there is only one element left if (high == low) return arr[low]; // Find mid int mid = low + (high - low)/2; /*(low + high)/2;*/ // Check if element (mid+1) is minimum element. Consider // the cases like {3, 4, 5, 1, 2} if (mid < high && arr[mid+1] < arr[mid]) return arr[mid+1]; // Check if mid itself is minimum element if (mid > low && arr[mid] < arr[mid - 1]) return arr[mid]; // Decide whether we need to go to left half or right half if (arr[high] > arr[mid]) return findMin(arr, low, mid-1); return findMin(arr, mid+1, high);} // Driver program to test above functionsint main(){ int arr1[] = {5, 6, 1, 2, 3, 4}; int n1 = sizeof(arr1)/sizeof(arr1[0]); printf("The minimum element is %d\n", findMin(arr1, 0, n1-1)); int arr2[] = {1, 2, 3, 4}; int n2 = sizeof(arr2)/sizeof(arr2[0]); printf("The minimum element is %d\n", findMin(arr2, 0, n2-1)); int arr3[] = {1}; int n3 = sizeof(arr3)/sizeof(arr3[0]); printf("The minimum element is %d\n", findMin(arr3, 0, n3-1)); int arr4[] = {1, 2}; int n4 = sizeof(arr4)/sizeof(arr4[0]); printf("The minimum element is %d\n", findMin(arr4, 0, n4-1)); int arr5[] = {2, 1}; int n5 = sizeof(arr5)/sizeof(arr5[0]); printf("The minimum element is %d\n", findMin(arr5, 0, n5-1)); int arr6[] = {5, 6, 7, 1, 2, 3, 4}; int n6 = sizeof(arr6)/sizeof(arr6[0]); printf("The minimum element is %d\n", findMin(arr6, 0, n6-1)); int arr7[] = {1, 2, 3, 4, 5, 6, 7}; int n7 = sizeof(arr7)/sizeof(arr7[0]); printf("The minimum element is %d\n", findMin(arr7, 0, n7-1)); int arr8[] = {2, 3, 4, 5, 6, 7, 8, 1}; int n8 = sizeof(arr8)/sizeof(arr8[0]); printf("The minimum element is %d\n", findMin(arr8, 0, n8-1)); int arr9[] = {3, 4, 5, 1, 2}; int n9 = sizeof(arr9)/sizeof(arr9[0]); printf("The minimum element is %d\n", findMin(arr9, 0, n9-1)); return 0;} // C++ program to find minimum// element in a sorted and rotated array#include <bits/stdc++.h>using namespace std; int findMin(int arr[], int low, int high){ // This condition is needed to // handle the case when array is not // rotated at all if (high < low) return arr[0]; // If there is only one element left if (high == low) return arr[low]; // Find mid int mid = low + (high - low)/2; /*(low + high)/2;*/ // Check if element (mid+1) is minimum element. Consider // the cases like {3, 4, 5, 1, 2} if (mid < high && arr[mid + 1] < arr[mid]) return arr[mid + 1]; // Check if mid itself is minimum element if (mid > low && arr[mid] < arr[mid - 1]) return arr[mid]; // Decide whether we need to go to left half or right half if (arr[high] > arr[mid]) return findMin(arr, low, mid - 1); return findMin(arr, mid + 1, high);} // Driver program to test above functionsint main(){ int arr1[] = {5, 6, 1, 2, 3, 4}; int n1 = sizeof(arr1)/sizeof(arr1[0]); cout << "The minimum element is " << findMin(arr1, 0, n1-1) << endl; int arr2[] = {1, 2, 3, 4}; int n2 = sizeof(arr2)/sizeof(arr2[0]); cout << "The minimum element is " << findMin(arr2, 0, n2-1) << endl; int arr3[] = {1}; int n3 = sizeof(arr3)/sizeof(arr3[0]); cout<<"The minimum element is "<<findMin(arr3, 0, n3-1)<<endl; int arr4[] = {1, 2}; int n4 = sizeof(arr4)/sizeof(arr4[0]); cout<<"The minimum element is "<<findMin(arr4, 0, n4-1)<<endl; int arr5[] = {2, 1}; int n5 = sizeof(arr5)/sizeof(arr5[0]); cout<<"The minimum element is "<<findMin(arr5, 0, n5-1)<<endl; int arr6[] = {5, 6, 7, 1, 2, 3, 4}; int n6 = sizeof(arr6)/sizeof(arr6[0]); cout<<"The minimum element is "<<findMin(arr6, 0, n6-1)<<endl; int arr7[] = {1, 2, 3, 4, 5, 6, 7}; int n7 = sizeof(arr7)/sizeof(arr7[0]); cout << "The minimum element is " << findMin(arr7, 0, n7-1) << endl; int arr8[] = {2, 3, 4, 5, 6, 7, 8, 1}; int n8 = sizeof(arr8)/sizeof(arr8[0]); cout << "The minimum element is " << findMin(arr8, 0, n8-1) << endl; int arr9[] = {3, 4, 5, 1, 2}; int n9 = sizeof(arr9)/sizeof(arr9[0]); cout << "The minimum element is " << findMin(arr9, 0, n9-1) << endl; return 0;} // This is code is contributed by rathbhupendra // Java program to find minimum element in a sorted and rotated arrayimport java.util.*;import java.lang.*;import java.io.*; class Minimum{ static int findMin(int arr[], int low, int high) { // This condition is needed to handle the case when array // is not rotated at all if (high < low) return arr[0]; // If there is only one element left if (high == low) return arr[low]; // Find mid int mid = low + (high - low)/2; /*(low + high)/2;*/ // Check if element (mid+1) is minimum element. Consider // the cases like {3, 4, 5, 1, 2} if (mid < high && arr[mid+1] < arr[mid]) return arr[mid+1]; // Check if mid itself is minimum element if (mid > low && arr[mid] < arr[mid - 1]) return arr[mid]; // Decide whether we need to go to left half or right half if (arr[high] > arr[mid]) return findMin(arr, low, mid-1); return findMin(arr, mid+1, high); } // Driver Program public static void main (String[] args) { int arr1[] = {5, 6, 1, 2, 3, 4}; int n1 = arr1.length; System.out.println("The minimum element is "+ findMin(arr1, 0, n1-1)); int arr2[] = {1, 2, 3, 4}; int n2 = arr2.length; System.out.println("The minimum element is "+ findMin(arr2, 0, n2-1)); int arr3[] = {1}; int n3 = arr3.length; System.out.println("The minimum element is "+ findMin(arr3, 0, n3-1)); int arr4[] = {1, 2}; int n4 = arr4.length; System.out.println("The minimum element is "+ findMin(arr4, 0, n4-1)); int arr5[] = {2, 1}; int n5 = arr5.length; System.out.println("The minimum element is "+ findMin(arr5, 0, n5-1)); int arr6[] = {5, 6, 7, 1, 2, 3, 4}; int n6 = arr6.length; System.out.println("The minimum element is "+ findMin(arr6, 0, n6-1)); int arr7[] = {1, 2, 3, 4, 5, 6, 7}; int n7 = arr7.length; System.out.println("The minimum element is "+ findMin(arr7, 0, n7-1)); int arr8[] = {2, 3, 4, 5, 6, 7, 8, 1}; int n8 = arr8.length; System.out.println("The minimum element is "+ findMin(arr8, 0, n8-1)); int arr9[] = {3, 4, 5, 1, 2}; int n9 = arr9.length; System.out.println("The minimum element is "+ findMin(arr9, 0, n9-1)); }} # Python program to find minimum element# in a sorted and rotated array def findMin(arr, low, high): # This condition is needed to handle the case when array is not # rotated at all if high < low: return arr[0] # If there is only one element left if high == low: return arr[low] # Find mid mid = int((low + high)/2) # Check if element (mid+1) is minimum element. Consider # the cases like [3, 4, 5, 1, 2] if mid < high and arr[mid+1] < arr[mid]: return arr[mid+1] # Check if mid itself is minimum element if mid > low and arr[mid] < arr[mid - 1]: return arr[mid] # Decide whether we need to go to left half or right half if arr[high] > arr[mid]: return findMin(arr, low, mid-1) return findMin(arr, mid+1, high) # Driver program to test above functionsarr1 = [5, 6, 1, 2, 3, 4]n1 = len(arr1)print("The minimum element is " + str(findMin(arr1, 0, n1-1))) arr2 = [1, 2, 3, 4]n2 = len(arr2)print("The minimum element is " + str(findMin(arr2, 0, n2-1))) arr3 = [1]n3 = len(arr3)print("The minimum element is " + str(findMin(arr3, 0, n3-1))) arr4 = [1, 2]n4 = len(arr4)print("The minimum element is " + str(findMin(arr4, 0, n4-1))) arr5 = [2, 1]n5 = len(arr5)print("The minimum element is " + str(findMin(arr5, 0, n5-1))) arr6 = [5, 6, 7, 1, 2, 3, 4]n6 = len(arr6)print("The minimum element is " + str(findMin(arr6, 0, n6-1))) arr7 = [1, 2, 3, 4, 5, 6, 7]n7 = len(arr7)print("The minimum element is " + str(findMin(arr7, 0, n7-1))) arr8 = [2, 3, 4, 5, 6, 7, 8, 1]n8 = len(arr8)print("The minimum element is " + str(findMin(arr8, 0, n8-1))) arr9 = [3, 4, 5, 1, 2]n9 = len(arr9)print("The minimum element is " + str(findMin(arr9, 0, n9-1))) # This code is contributed by Pratik Chhajer // C# program to find minimum element// in a sorted and rotated arrayusing System; class Minimum { static int findMin(int[] arr, int low, int high) { // This condition is needed to handle // the case when array // is not rotated at all if (high < low) return arr[0]; // If there is only one element left if (high == low) return arr[low]; // Find mid // (low + high)/2 int mid = low + (high - low) / 2; // Check if element (mid+1) is minimum element. Consider // the cases like {3, 4, 5, 1, 2} if (mid < high && arr[mid + 1] < arr[mid]) return arr[mid + 1]; // Check if mid itself is minimum element if (mid > low && arr[mid] < arr[mid - 1]) return arr[mid]; // Decide whether we need to go to // left half or right half if (arr[high] > arr[mid]) return findMin(arr, low, mid - 1); return findMin(arr, mid + 1, high); } // Driver Program public static void Main() { int[] arr1 = { 5, 6, 1, 2, 3, 4 }; int n1 = arr1.Length; Console.WriteLine("The minimum element is " + findMin(arr1, 0, n1 - 1)); int[] arr2 = { 1, 2, 3, 4 }; int n2 = arr2.Length; Console.WriteLine("The minimum element is " + findMin(arr2, 0, n2 - 1)); int[] arr3 = { 1 }; int n3 = arr3.Length; Console.WriteLine("The minimum element is " + findMin(arr3, 0, n3 - 1)); int[] arr4 = { 1, 2 }; int n4 = arr4.Length; Console.WriteLine("The minimum element is " + findMin(arr4, 0, n4 - 1)); int[] arr5 = { 2, 1 }; int n5 = arr5.Length; Console.WriteLine("The minimum element is " + findMin(arr5, 0, n5 - 1)); int[] arr6 = { 5, 6, 7, 1, 2, 3, 4 }; int n6 = arr6.Length; Console.WriteLine("The minimum element is " + findMin(arr6, 0, n1 - 1)); int[] arr7 = { 1, 2, 3, 4, 5, 6, 7 }; int n7 = arr7.Length; Console.WriteLine("The minimum element is " + findMin(arr7, 0, n7 - 1)); int[] arr8 = { 2, 3, 4, 5, 6, 7, 8, 1 }; int n8 = arr8.Length; Console.WriteLine("The minimum element is " + findMin(arr8, 0, n8 - 1)); int[] arr9 = { 3, 4, 5, 1, 2 }; int n9 = arr9.Length; Console.WriteLine("The minimum element is " + findMin(arr9, 0, n9 - 1)); }} // This code is contributed by vt_m. <?php// PHP program to find minimum// element in a sorted and// rotated array function findMin($arr, $low, $high){ // This condition is needed // to handle the case when // array is not rotated at all if ($high < $low) return $arr[0]; // If there is only // one element left if ($high == $low) return $arr[$low]; // Find mid $mid = $low + ($high - $low) / 2; /*($low + $high)/2;*/ // Check if element (mid+1) // is minimum element. // Consider the cases like // (3, 4, 5, 1, 2) if ($mid < $high && $arr[$mid + 1] < $arr[$mid]) return $arr[$mid + 1]; // Check if mid itself // is minimum element if ($mid > $low && $arr[$mid] < $arr[$mid - 1]) return $arr[$mid]; // Decide whether we need // to go to left half or // right half if ($arr[$high] > $arr[$mid]) return findMin($arr, $low, $mid - 1); return findMin($arr, $mid + 1, $high);} // Driver Code$arr1 = array(5, 6, 1, 2, 3, 4);$n1 = sizeof($arr1);echo "The minimum element is " . findMin($arr1, 0, $n1 - 1) . "\n"; $arr2 = array(1, 2, 3, 4);$n2 = sizeof($arr2);echo "The minimum element is " . findMin($arr2, 0, $n2 - 1) . "\n"; $arr3 = array(1);$n3 = sizeof($arr3);echo "The minimum element is " . findMin($arr3, 0, $n3 - 1) . "\n"; $arr4 = array(1, 2);$n4 = sizeof($arr4);echo "The minimum element is " . findMin($arr4, 0, $n4 - 1) . "\n"; $arr5 = array(2, 1);$n5 = sizeof($arr5);echo "The minimum element is " . findMin($arr5, 0, $n5 - 1) . "\n"; $arr6 = array(5, 6, 7, 1, 2, 3, 4);$n6 = sizeof($arr6);echo "The minimum element is " . findMin($arr6, 0, $n6 - 1) . "\n"; $arr7 = array(1, 2, 3, 4, 5, 6, 7);$n7 = sizeof($arr7);echo "The minimum element is " . findMin($arr7, 0, $n7 - 1) . "\n"; $arr8 = array(2, 3, 4, 5, 6, 7, 8, 1);$n8 = sizeof($arr8);echo "The minimum element is " . findMin($arr8, 0, $n8 - 1) . "\n"; $arr9 = array(3, 4, 5, 1, 2);$n9 = sizeof($arr9);echo "The minimum element is " . findMin($arr9, 0, $n9 - 1) . "\n"; // This code is contributed by ChitraNayal?> <script> // Javascript program to find minimum element in a sorted and rotated array function findMin(arr,low,high) { // This condition is needed to handle the case when array // is not rotated at all if (high < low) return arr[0]; // If there is only one element left if (high == low) return arr[low]; // Find mid let mid =low + Math.floor((high - low)/2); /*(low + high)/2;*/ // Check if element (mid+1) is minimum element. Consider // the cases like {3, 4, 5, 1, 2} if (mid < high && arr[mid+1] < arr[mid]) return arr[mid+1]; // Check if mid itself is minimum element if (mid > low && arr[mid] < arr[mid - 1]) return arr[mid]; // Decide whether we need to go to left half or right half if (arr[high] > arr[mid]) return findMin(arr, low, mid-1); return findMin(arr, mid+1, high); } // Driver Program let arr1=[5, 6, 1, 2, 3, 4]; let n1 = arr1.length; document.write("The minimum element is "+ findMin(arr1, 0, n1-1)+"<br>"); let arr2=[1, 2, 3, 4]; let n2 = arr2.length; document.write("The minimum element is "+ findMin(arr2, 0, n2-1)+"<br>"); let arr3=[1]; let n3 = arr3.length; document.write("The minimum element is "+ findMin(arr3, 0, n3-1)+"<br>"); let arr4=[1,2]; let n4 = arr4.length; document.write("The minimum element is "+ findMin(arr4, 0, n4-1)+"<br>"); let arr5=[2,1]; let n5 = arr5.length; document.write("The minimum element is "+ findMin(arr5, 0, n5-1)+"<br>"); let arr6=[5, 6, 7, 1, 2, 3, 4]; let n6 = arr6.length; document.write("The minimum element is "+ findMin(arr6, 0, n6-1)+"<br>"); let arr7=[1, 2, 3, 4, 5, 6, 7]; let n7 = arr7.length; document.write("The minimum element is "+ findMin(arr7, 0, n7-1)+"<br>"); let arr8=[2, 3, 4, 5, 6, 7, 8, 1]; let n8 = arr8.length; document.write("The minimum element is "+ findMin(arr8, 0, n8-1)+"<br>"); let arr9=[3, 4, 5, 1, 2]; let n9 = arr9.length; document.write("The minimum element is "+ findMin(arr9, 0, n9-1)+"<br>"); // This code is contributed by avanitrachhadiya2155 </script> Output: The minimum element is 1 The minimum element is 1 The minimum element is 1 The minimum element is 1 The minimum element is 1 The minimum element is 1 The minimum element is 1 The minimum element is 1 The minimum element is 1 How to handle duplicates? The above approach in the worst case(If all the elements are the same) takes O(N).Below is the code to handle duplicates in O(log n) time. C++ Java Python3 C# Javascript // C++ program to find minimum element in a sorted// and rotated array containing duplicate elements.#include <bits/stdc++.h>using namespace std; // Function to find minimum elementint findMin(int arr[], int low, int high){ while(low < high) { int mid = low + (high - low)/2; if (arr[mid] == arr[high]) high--; else if(arr[mid] > arr[high]) low = mid + 1; else high = mid; } return arr[high];} // Driver codeint main(){ int arr1[] = {5, 6, 1, 2, 3, 4}; int n1 = sizeof(arr1)/sizeof(arr1[0]); cout << "The minimum element is " << findMin(arr1, 0, n1-1) << endl; int arr2[] = {1, 2, 3, 4}; int n2 = sizeof(arr2)/sizeof(arr2[0]); cout << "The minimum element is " << findMin(arr2, 0, n2-1) << endl; int arr3[] = {1}; int n3 = sizeof(arr3)/sizeof(arr3[0]); cout<<"The minimum element is "<<findMin(arr3, 0, n3-1)<<endl; int arr4[] = {1, 2}; int n4 = sizeof(arr4)/sizeof(arr4[0]); cout<<"The minimum element is "<<findMin(arr4, 0, n4-1)<<endl; int arr5[] = {2, 1}; int n5 = sizeof(arr5)/sizeof(arr5[0]); cout<<"The minimum element is "<<findMin(arr5, 0, n5-1)<<endl; int arr6[] = {5, 6, 7, 1, 2, 3, 4}; int n6 = sizeof(arr6)/sizeof(arr6[0]); cout<<"The minimum element is "<<findMin(arr6, 0, n6-1)<<endl; int arr7[] = {1, 2, 3, 4, 5, 6, 7}; int n7 = sizeof(arr7)/sizeof(arr7[0]); cout << "The minimum element is " << findMin(arr7, 0, n7-1) << endl; int arr8[] = {2, 3, 4, 5, 6, 7, 8, 1}; int n8 = sizeof(arr8)/sizeof(arr8[0]); cout << "The minimum element is " << findMin(arr8, 0, n8-1) << endl; int arr9[] = {3, 4, 5, 1, 2}; int n9 = sizeof(arr9)/sizeof(arr9[0]); cout << "The minimum element is " << findMin(arr9, 0, n9-1) << endl; return 0;}// This is code is contributed by Saptakatha Adak. // Java program to find minimum element// in a sorted and rotated array containing// duplicate elements.import java.util.*;import java.lang.*; class GFG{ // Function to find minimum elementpublic static int findMin(int arr[], int low, int high){ while(low < high) { int mid = low + (high - low) / 2; if (arr[mid] == arr[high]) high--; else if(arr[mid] > arr[high]) low = mid + 1; else high = mid; } return arr[high];} // Driver codepublic static void main(String args[]){ int arr1[] = { 5, 6, 1, 2, 3, 4 }; int n1 = arr1.length; System.out.println("The minimum element is " + findMin(arr1, 0, n1 - 1)); int arr2[] = { 1, 2, 3, 4 }; int n2 = arr2.length; System.out.println("The minimum element is " + findMin(arr2, 0, n2 - 1)); int arr3[] = {1}; int n3 = arr3.length; System.out.println("The minimum element is " + findMin(arr3, 0, n3 - 1)); int arr4[] = { 1, 2 }; int n4 = arr4.length; System.out.println("The minimum element is " + findMin(arr4, 0, n4 - 1)); int arr5[] = { 2, 1 }; int n5 = arr5.length; System.out.println("The minimum element is " + findMin(arr5, 0, n5 - 1)); int arr6[] = { 5, 6, 7, 1, 2, 3, 4 }; int n6 = arr6.length; System.out.println("The minimum element is " + findMin(arr6, 0, n6 - 1)); int arr7[] = { 1, 2, 3, 4, 5, 6, 7 }; int n7 = arr7.length; System.out.println("The minimum element is " + findMin(arr7, 0, n7 - 1)); int arr8[] = { 2, 3, 4, 5, 6, 7, 8, 1 }; int n8 = arr8.length; System.out.println("The minimum element is " + findMin(arr8, 0, n8 - 1)); int arr9[] = { 3, 4, 5, 1, 2 }; int n9 = arr9.length; System.out.println("The minimum element is " + findMin(arr9, 0, n9 - 1));}} // This is code is contributed by SoumikMondal # Python3 program to find# minimum element in a sorted# and rotated array containing# duplicate elements. # Function to find minimum elementdef findMin(arr, low, high): while (low < high): mid = low + (high - low) // 2; if (arr[mid] == arr[high]): high -= 1; elif (arr[mid] > arr[high]): low = mid + 1; else: high = mid; return arr[high]; # Driver codeif __name__ == '__main__': arr1 = [5, 6, 1, 2, 3, 4]; n1 = len(arr1); print("The minimum element is ", findMin(arr1, 0, n1 - 1)); arr2 = [1, 2, 3, 4]; n2 = len(arr2); print("The minimum element is ", findMin(arr2, 0, n2 - 1)); arr3 = [1]; n3 = len(arr3); print("The minimum element is ", findMin(arr3, 0, n3 - 1)); arr4 = [1, 2]; n4 = len(arr4); print("The minimum element is ", findMin(arr4, 0, n4 - 1)); arr5 = [2, 1]; n5 = len(arr5); print("The minimum element is ", findMin(arr5, 0, n5 - 1)); arr6 = [5, 6, 7, 1, 2, 3, 4]; n6 = len(arr6); print("The minimum element is ", findMin(arr6, 0, n6 - 1)); arr7 = [1, 2, 3, 4, 5, 6, 7]; n7 = len(arr7); print("The minimum element is ", findMin(arr7, 0, n7 - 1)); arr8 = [2, 3, 4, 5, 6, 7, 8, 1]; n8 = len(arr8); print("The minimum element is ", findMin(arr8, 0, n8 - 1)); arr9 = [3, 4, 5, 1, 2]; n9 = len(arr9); print("The minimum element is ", findMin(arr9, 0, n9 - 1)); # This code is contributed by Princi Singh // C# program to find minimum element// in a sorted and rotated array// containing duplicate elements.using System; class GFG{ // Function to find minimum elementpublic static int findMin(int []arr, int low, int high){ while (low < high) { int mid = low + (high - low) / 2; if (arr[mid] == arr[high]) high--; else if (arr[mid] > arr[high]) low = mid + 1; else high = mid; } return arr[high];} // Driver codepublic static void Main(String []args){ int []arr1 = { 5, 6, 1, 2, 3, 4 }; int n1 = arr1.Length; Console.WriteLine("The minimum element is " + findMin(arr1, 0, n1 - 1)); int []arr2 = { 1, 2, 3, 4 }; int n2 = arr2.Length; Console.WriteLine("The minimum element is " + findMin(arr2, 0, n2 - 1)); int []arr3 = {1}; int n3 = arr3.Length; Console.WriteLine("The minimum element is " + findMin(arr3, 0, n3 - 1)); int []arr4 = { 1, 2 }; int n4 = arr4.Length; Console.WriteLine("The minimum element is " + findMin(arr4, 0, n4 - 1)); int []arr5 = { 2, 1 }; int n5 = arr5.Length; Console.WriteLine("The minimum element is " + findMin(arr5, 0, n5 - 1)); int []arr6 = { 5, 6, 7, 1, 2, 3, 4 }; int n6 = arr6.Length; Console.WriteLine("The minimum element is " + findMin(arr6, 0, n6 - 1)); int []arr7 = { 1, 2, 3, 4, 5, 6, 7 }; int n7 = arr7.Length; Console.WriteLine("The minimum element is " + findMin(arr7, 0, n7 - 1)); int []arr8 = { 2, 3, 4, 5, 6, 7, 8, 1 }; int n8 = arr8.Length; Console.WriteLine("The minimum element is " + findMin(arr8, 0, n8 - 1)); int []arr9 = { 3, 4, 5, 1, 2 }; int n9 = arr9.Length; Console.WriteLine("The minimum element is " + findMin(arr9, 0, n9 - 1));}} // This code is contributed by Amit Katiyar <script>// JavaScript program to find minimum element in a sorted// and rotated array containing duplicate elements. // Function to find minimum elementfunction findMin(arr, low, high){ while(low < high) { let mid = Math.floor(low + (high - low)/2); if (arr[mid] == arr[high]) high--; else if(arr[mid] > arr[high]) low = mid + 1; else high = mid; } return arr[high];} var arr1 = [5, 6, 1, 2, 3, 4];var n1 = arr1.length;document.write("The minimum element is " + findMin(arr1, 0, n1-1) + "<br>"); var arr2 = [1, 2, 3, 4];var n2 = arr2.length;document.write("The minimum element is " + findMin(arr2, 0, n2-1) + "<br>"); var arr3 = [1];var n3 = arr3.length;document.write("The minimum element is " + findMin(arr3, 0, n3-1) + "<br>"); var arr4 = [1, 2];var n4 = arr4.length;document.write("The minimum element is " + findMin(arr4, 0, n4-1) + "<br>"); var arr5 = [2, 1];var n5 = arr5.length;document.write("The minimum element is " + findMin(arr5, 0, n5-1) + "<br>"); var arr6 = [5, 6, 7, 1, 2, 3, 4];var n6 = arr6.length;document.write("The minimum element is " + findMin(arr6, 0, n6-1) + "<br>"); var arr7 = [1, 2, 3, 4, 5, 6, 7];var n7 = arr7.length;document.write("The minimum element is " + findMin(arr7, 0, n7-1) + "<br>"); var arr8 = [2, 3, 4, 5, 6, 7, 8, 1];var n8 = arr8.length;document.write("The minimum element is " + findMin(arr8, 0, n8-1) + "<br>"); var arr9 = [3, 4, 5, 1, 2];var n9 = arr9.length;document.write("The minimum element is " + findMin(arr9, 0, n9-1) + "<br>"); // This code is contributed by probinsah</script> Output: The minimum element is 1 The minimum element is 1 The minimum element is 1 The minimum element is 1 The minimum element is 1 The minimum element is 1 The minimum element is 1 The minimum element is 1 The minimum element is 1 YouTubeGeeksforGeeks501K subscribersFind the minimum element in a sorted and rotated array | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:48•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=9k0vT6lx9XA" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. ukasp Sar_123 rathbhupendra shreyashagrawal SaptakathaAdak SoumikMondal anjali_1102 amit143katiyar princi singh avanitrachhadiya2155 probinsah amartyaghoshgfg simmytarika5 Adobe Amazon Binary Search Microsoft Morgan Stanley Samsung Snapdeal Times Internet Arrays Divide and Conquer Searching Morgan Stanley Amazon Microsoft Samsung Snapdeal Adobe Times Internet Arrays Searching Divide and Conquer Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Arrays in C/C++ Program for array rotation Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Merge Sort QuickSort Binary Search Program for Tower of Hanoi Divide and Conquer Algorithm | Introduction
[ { "code": null, "e": 41276, "s": 41248, "text": "\n23 Feb, 2022" }, { "code": null, "e": 41420, "s": 41276, "text": "A sorted array is rotated at some unknown point, find the minimum element in it. The following solution assumes that all elements are distinct." }, { "code": null, "e": 41431, "s": 41420, "text": "Examples: " }, { "code": null, "e": 41523, "s": 41431, "text": "Input: {5, 6, 1, 2, 3, 4}\nOutput: 1\n\nInput: {1, 2, 3, 4}\nOutput: 1\n\nInput: {2, 1}\nOutput: 1" }, { "code": null, "e": 41770, "s": 41523, "text": "A simple solution is to traverse the complete array and find a minimum. This solution requires O(n) time. We can do it in O(Logn) using Binary Search. If we take a closer look at the above examples, we can easily figure out the following pattern:" }, { "code": null, "e": 42040, "s": 41770, "text": "The minimum element is the only element whose previous is greater than it. If there is no previous element, then there is no rotation (the first element is minimum). We check this condition for the middle element by comparing it with (mid-1)’th and (mid+1)’th elements." }, { "code": null, "e": 42327, "s": 42040, "text": "If the minimum element is not at the middle (neither mid nor mid + 1), then the minimum element lies in either the left half or right half. If the middle element is smaller than the last element, then the minimum element lies in the left halfElse minimum element lies in the right half." }, { "code": null, "e": 42474, "s": 42327, "text": "If the middle element is smaller than the last element, then the minimum element lies in the left halfElse minimum element lies in the right half." }, { "code": null, "e": 42577, "s": 42474, "text": "If the middle element is smaller than the last element, then the minimum element lies in the left half" }, { "code": null, "e": 42622, "s": 42577, "text": "Else minimum element lies in the right half." }, { "code": null, "e": 42712, "s": 42622, "text": "We strongly recommend you to try it yourself before seeing the following implementation. " }, { "code": null, "e": 42714, "s": 42712, "text": "C" }, { "code": null, "e": 42718, "s": 42714, "text": "C++" }, { "code": null, "e": 42723, "s": 42718, "text": "Java" }, { "code": null, "e": 42731, "s": 42723, "text": "Python3" }, { "code": null, "e": 42734, "s": 42731, "text": "C#" }, { "code": null, "e": 42738, "s": 42734, "text": "PHP" }, { "code": null, "e": 42749, "s": 42738, "text": "Javascript" }, { "code": "// C program to find minimum element in a sorted and rotated array#include <stdio.h> int findMin(int arr[], int low, int high){ // This condition is needed to handle the case when array is not // rotated at all if (high < low) return arr[0]; // If there is only one element left if (high == low) return arr[low]; // Find mid int mid = low + (high - low)/2; /*(low + high)/2;*/ // Check if element (mid+1) is minimum element. Consider // the cases like {3, 4, 5, 1, 2} if (mid < high && arr[mid+1] < arr[mid]) return arr[mid+1]; // Check if mid itself is minimum element if (mid > low && arr[mid] < arr[mid - 1]) return arr[mid]; // Decide whether we need to go to left half or right half if (arr[high] > arr[mid]) return findMin(arr, low, mid-1); return findMin(arr, mid+1, high);} // Driver program to test above functionsint main(){ int arr1[] = {5, 6, 1, 2, 3, 4}; int n1 = sizeof(arr1)/sizeof(arr1[0]); printf(\"The minimum element is %d\\n\", findMin(arr1, 0, n1-1)); int arr2[] = {1, 2, 3, 4}; int n2 = sizeof(arr2)/sizeof(arr2[0]); printf(\"The minimum element is %d\\n\", findMin(arr2, 0, n2-1)); int arr3[] = {1}; int n3 = sizeof(arr3)/sizeof(arr3[0]); printf(\"The minimum element is %d\\n\", findMin(arr3, 0, n3-1)); int arr4[] = {1, 2}; int n4 = sizeof(arr4)/sizeof(arr4[0]); printf(\"The minimum element is %d\\n\", findMin(arr4, 0, n4-1)); int arr5[] = {2, 1}; int n5 = sizeof(arr5)/sizeof(arr5[0]); printf(\"The minimum element is %d\\n\", findMin(arr5, 0, n5-1)); int arr6[] = {5, 6, 7, 1, 2, 3, 4}; int n6 = sizeof(arr6)/sizeof(arr6[0]); printf(\"The minimum element is %d\\n\", findMin(arr6, 0, n6-1)); int arr7[] = {1, 2, 3, 4, 5, 6, 7}; int n7 = sizeof(arr7)/sizeof(arr7[0]); printf(\"The minimum element is %d\\n\", findMin(arr7, 0, n7-1)); int arr8[] = {2, 3, 4, 5, 6, 7, 8, 1}; int n8 = sizeof(arr8)/sizeof(arr8[0]); printf(\"The minimum element is %d\\n\", findMin(arr8, 0, n8-1)); int arr9[] = {3, 4, 5, 1, 2}; int n9 = sizeof(arr9)/sizeof(arr9[0]); printf(\"The minimum element is %d\\n\", findMin(arr9, 0, n9-1)); return 0;}", "e": 44945, "s": 42749, "text": null }, { "code": "// C++ program to find minimum// element in a sorted and rotated array#include <bits/stdc++.h>using namespace std; int findMin(int arr[], int low, int high){ // This condition is needed to // handle the case when array is not // rotated at all if (high < low) return arr[0]; // If there is only one element left if (high == low) return arr[low]; // Find mid int mid = low + (high - low)/2; /*(low + high)/2;*/ // Check if element (mid+1) is minimum element. Consider // the cases like {3, 4, 5, 1, 2} if (mid < high && arr[mid + 1] < arr[mid]) return arr[mid + 1]; // Check if mid itself is minimum element if (mid > low && arr[mid] < arr[mid - 1]) return arr[mid]; // Decide whether we need to go to left half or right half if (arr[high] > arr[mid]) return findMin(arr, low, mid - 1); return findMin(arr, mid + 1, high);} // Driver program to test above functionsint main(){ int arr1[] = {5, 6, 1, 2, 3, 4}; int n1 = sizeof(arr1)/sizeof(arr1[0]); cout << \"The minimum element is \" << findMin(arr1, 0, n1-1) << endl; int arr2[] = {1, 2, 3, 4}; int n2 = sizeof(arr2)/sizeof(arr2[0]); cout << \"The minimum element is \" << findMin(arr2, 0, n2-1) << endl; int arr3[] = {1}; int n3 = sizeof(arr3)/sizeof(arr3[0]); cout<<\"The minimum element is \"<<findMin(arr3, 0, n3-1)<<endl; int arr4[] = {1, 2}; int n4 = sizeof(arr4)/sizeof(arr4[0]); cout<<\"The minimum element is \"<<findMin(arr4, 0, n4-1)<<endl; int arr5[] = {2, 1}; int n5 = sizeof(arr5)/sizeof(arr5[0]); cout<<\"The minimum element is \"<<findMin(arr5, 0, n5-1)<<endl; int arr6[] = {5, 6, 7, 1, 2, 3, 4}; int n6 = sizeof(arr6)/sizeof(arr6[0]); cout<<\"The minimum element is \"<<findMin(arr6, 0, n6-1)<<endl; int arr7[] = {1, 2, 3, 4, 5, 6, 7}; int n7 = sizeof(arr7)/sizeof(arr7[0]); cout << \"The minimum element is \" << findMin(arr7, 0, n7-1) << endl; int arr8[] = {2, 3, 4, 5, 6, 7, 8, 1}; int n8 = sizeof(arr8)/sizeof(arr8[0]); cout << \"The minimum element is \" << findMin(arr8, 0, n8-1) << endl; int arr9[] = {3, 4, 5, 1, 2}; int n9 = sizeof(arr9)/sizeof(arr9[0]); cout << \"The minimum element is \" << findMin(arr9, 0, n9-1) << endl; return 0;} // This is code is contributed by rathbhupendra", "e": 47245, "s": 44945, "text": null }, { "code": "// Java program to find minimum element in a sorted and rotated arrayimport java.util.*;import java.lang.*;import java.io.*; class Minimum{ static int findMin(int arr[], int low, int high) { // This condition is needed to handle the case when array // is not rotated at all if (high < low) return arr[0]; // If there is only one element left if (high == low) return arr[low]; // Find mid int mid = low + (high - low)/2; /*(low + high)/2;*/ // Check if element (mid+1) is minimum element. Consider // the cases like {3, 4, 5, 1, 2} if (mid < high && arr[mid+1] < arr[mid]) return arr[mid+1]; // Check if mid itself is minimum element if (mid > low && arr[mid] < arr[mid - 1]) return arr[mid]; // Decide whether we need to go to left half or right half if (arr[high] > arr[mid]) return findMin(arr, low, mid-1); return findMin(arr, mid+1, high); } // Driver Program public static void main (String[] args) { int arr1[] = {5, 6, 1, 2, 3, 4}; int n1 = arr1.length; System.out.println(\"The minimum element is \"+ findMin(arr1, 0, n1-1)); int arr2[] = {1, 2, 3, 4}; int n2 = arr2.length; System.out.println(\"The minimum element is \"+ findMin(arr2, 0, n2-1)); int arr3[] = {1}; int n3 = arr3.length; System.out.println(\"The minimum element is \"+ findMin(arr3, 0, n3-1)); int arr4[] = {1, 2}; int n4 = arr4.length; System.out.println(\"The minimum element is \"+ findMin(arr4, 0, n4-1)); int arr5[] = {2, 1}; int n5 = arr5.length; System.out.println(\"The minimum element is \"+ findMin(arr5, 0, n5-1)); int arr6[] = {5, 6, 7, 1, 2, 3, 4}; int n6 = arr6.length; System.out.println(\"The minimum element is \"+ findMin(arr6, 0, n6-1)); int arr7[] = {1, 2, 3, 4, 5, 6, 7}; int n7 = arr7.length; System.out.println(\"The minimum element is \"+ findMin(arr7, 0, n7-1)); int arr8[] = {2, 3, 4, 5, 6, 7, 8, 1}; int n8 = arr8.length; System.out.println(\"The minimum element is \"+ findMin(arr8, 0, n8-1)); int arr9[] = {3, 4, 5, 1, 2}; int n9 = arr9.length; System.out.println(\"The minimum element is \"+ findMin(arr9, 0, n9-1)); }}", "e": 49624, "s": 47245, "text": null }, { "code": "# Python program to find minimum element# in a sorted and rotated array def findMin(arr, low, high): # This condition is needed to handle the case when array is not # rotated at all if high < low: return arr[0] # If there is only one element left if high == low: return arr[low] # Find mid mid = int((low + high)/2) # Check if element (mid+1) is minimum element. Consider # the cases like [3, 4, 5, 1, 2] if mid < high and arr[mid+1] < arr[mid]: return arr[mid+1] # Check if mid itself is minimum element if mid > low and arr[mid] < arr[mid - 1]: return arr[mid] # Decide whether we need to go to left half or right half if arr[high] > arr[mid]: return findMin(arr, low, mid-1) return findMin(arr, mid+1, high) # Driver program to test above functionsarr1 = [5, 6, 1, 2, 3, 4]n1 = len(arr1)print(\"The minimum element is \" + str(findMin(arr1, 0, n1-1))) arr2 = [1, 2, 3, 4]n2 = len(arr2)print(\"The minimum element is \" + str(findMin(arr2, 0, n2-1))) arr3 = [1]n3 = len(arr3)print(\"The minimum element is \" + str(findMin(arr3, 0, n3-1))) arr4 = [1, 2]n4 = len(arr4)print(\"The minimum element is \" + str(findMin(arr4, 0, n4-1))) arr5 = [2, 1]n5 = len(arr5)print(\"The minimum element is \" + str(findMin(arr5, 0, n5-1))) arr6 = [5, 6, 7, 1, 2, 3, 4]n6 = len(arr6)print(\"The minimum element is \" + str(findMin(arr6, 0, n6-1))) arr7 = [1, 2, 3, 4, 5, 6, 7]n7 = len(arr7)print(\"The minimum element is \" + str(findMin(arr7, 0, n7-1))) arr8 = [2, 3, 4, 5, 6, 7, 8, 1]n8 = len(arr8)print(\"The minimum element is \" + str(findMin(arr8, 0, n8-1))) arr9 = [3, 4, 5, 1, 2]n9 = len(arr9)print(\"The minimum element is \" + str(findMin(arr9, 0, n9-1))) # This code is contributed by Pratik Chhajer", "e": 51387, "s": 49624, "text": null }, { "code": "// C# program to find minimum element// in a sorted and rotated arrayusing System; class Minimum { static int findMin(int[] arr, int low, int high) { // This condition is needed to handle // the case when array // is not rotated at all if (high < low) return arr[0]; // If there is only one element left if (high == low) return arr[low]; // Find mid // (low + high)/2 int mid = low + (high - low) / 2; // Check if element (mid+1) is minimum element. Consider // the cases like {3, 4, 5, 1, 2} if (mid < high && arr[mid + 1] < arr[mid]) return arr[mid + 1]; // Check if mid itself is minimum element if (mid > low && arr[mid] < arr[mid - 1]) return arr[mid]; // Decide whether we need to go to // left half or right half if (arr[high] > arr[mid]) return findMin(arr, low, mid - 1); return findMin(arr, mid + 1, high); } // Driver Program public static void Main() { int[] arr1 = { 5, 6, 1, 2, 3, 4 }; int n1 = arr1.Length; Console.WriteLine(\"The minimum element is \" + findMin(arr1, 0, n1 - 1)); int[] arr2 = { 1, 2, 3, 4 }; int n2 = arr2.Length; Console.WriteLine(\"The minimum element is \" + findMin(arr2, 0, n2 - 1)); int[] arr3 = { 1 }; int n3 = arr3.Length; Console.WriteLine(\"The minimum element is \" + findMin(arr3, 0, n3 - 1)); int[] arr4 = { 1, 2 }; int n4 = arr4.Length; Console.WriteLine(\"The minimum element is \" + findMin(arr4, 0, n4 - 1)); int[] arr5 = { 2, 1 }; int n5 = arr5.Length; Console.WriteLine(\"The minimum element is \" + findMin(arr5, 0, n5 - 1)); int[] arr6 = { 5, 6, 7, 1, 2, 3, 4 }; int n6 = arr6.Length; Console.WriteLine(\"The minimum element is \" + findMin(arr6, 0, n1 - 1)); int[] arr7 = { 1, 2, 3, 4, 5, 6, 7 }; int n7 = arr7.Length; Console.WriteLine(\"The minimum element is \" + findMin(arr7, 0, n7 - 1)); int[] arr8 = { 2, 3, 4, 5, 6, 7, 8, 1 }; int n8 = arr8.Length; Console.WriteLine(\"The minimum element is \" + findMin(arr8, 0, n8 - 1)); int[] arr9 = { 3, 4, 5, 1, 2 }; int n9 = arr9.Length; Console.WriteLine(\"The minimum element is \" + findMin(arr9, 0, n9 - 1)); }} // This code is contributed by vt_m.", "e": 54066, "s": 51387, "text": null }, { "code": "<?php// PHP program to find minimum// element in a sorted and// rotated array function findMin($arr, $low, $high){ // This condition is needed // to handle the case when // array is not rotated at all if ($high < $low) return $arr[0]; // If there is only // one element left if ($high == $low) return $arr[$low]; // Find mid $mid = $low + ($high - $low) / 2; /*($low + $high)/2;*/ // Check if element (mid+1) // is minimum element. // Consider the cases like // (3, 4, 5, 1, 2) if ($mid < $high && $arr[$mid + 1] < $arr[$mid]) return $arr[$mid + 1]; // Check if mid itself // is minimum element if ($mid > $low && $arr[$mid] < $arr[$mid - 1]) return $arr[$mid]; // Decide whether we need // to go to left half or // right half if ($arr[$high] > $arr[$mid]) return findMin($arr, $low, $mid - 1); return findMin($arr, $mid + 1, $high);} // Driver Code$arr1 = array(5, 6, 1, 2, 3, 4);$n1 = sizeof($arr1);echo \"The minimum element is \" . findMin($arr1, 0, $n1 - 1) . \"\\n\"; $arr2 = array(1, 2, 3, 4);$n2 = sizeof($arr2);echo \"The minimum element is \" . findMin($arr2, 0, $n2 - 1) . \"\\n\"; $arr3 = array(1);$n3 = sizeof($arr3);echo \"The minimum element is \" . findMin($arr3, 0, $n3 - 1) . \"\\n\"; $arr4 = array(1, 2);$n4 = sizeof($arr4);echo \"The minimum element is \" . findMin($arr4, 0, $n4 - 1) . \"\\n\"; $arr5 = array(2, 1);$n5 = sizeof($arr5);echo \"The minimum element is \" . findMin($arr5, 0, $n5 - 1) . \"\\n\"; $arr6 = array(5, 6, 7, 1, 2, 3, 4);$n6 = sizeof($arr6);echo \"The minimum element is \" . findMin($arr6, 0, $n6 - 1) . \"\\n\"; $arr7 = array(1, 2, 3, 4, 5, 6, 7);$n7 = sizeof($arr7);echo \"The minimum element is \" . findMin($arr7, 0, $n7 - 1) . \"\\n\"; $arr8 = array(2, 3, 4, 5, 6, 7, 8, 1);$n8 = sizeof($arr8);echo \"The minimum element is \" . findMin($arr8, 0, $n8 - 1) . \"\\n\"; $arr9 = array(3, 4, 5, 1, 2);$n9 = sizeof($arr9);echo \"The minimum element is \" . findMin($arr9, 0, $n9 - 1) . \"\\n\"; // This code is contributed by ChitraNayal?>", "e": 56177, "s": 54066, "text": null }, { "code": "<script> // Javascript program to find minimum element in a sorted and rotated array function findMin(arr,low,high) { // This condition is needed to handle the case when array // is not rotated at all if (high < low) return arr[0]; // If there is only one element left if (high == low) return arr[low]; // Find mid let mid =low + Math.floor((high - low)/2); /*(low + high)/2;*/ // Check if element (mid+1) is minimum element. Consider // the cases like {3, 4, 5, 1, 2} if (mid < high && arr[mid+1] < arr[mid]) return arr[mid+1]; // Check if mid itself is minimum element if (mid > low && arr[mid] < arr[mid - 1]) return arr[mid]; // Decide whether we need to go to left half or right half if (arr[high] > arr[mid]) return findMin(arr, low, mid-1); return findMin(arr, mid+1, high); } // Driver Program let arr1=[5, 6, 1, 2, 3, 4]; let n1 = arr1.length; document.write(\"The minimum element is \"+ findMin(arr1, 0, n1-1)+\"<br>\"); let arr2=[1, 2, 3, 4]; let n2 = arr2.length; document.write(\"The minimum element is \"+ findMin(arr2, 0, n2-1)+\"<br>\"); let arr3=[1]; let n3 = arr3.length; document.write(\"The minimum element is \"+ findMin(arr3, 0, n3-1)+\"<br>\"); let arr4=[1,2]; let n4 = arr4.length; document.write(\"The minimum element is \"+ findMin(arr4, 0, n4-1)+\"<br>\"); let arr5=[2,1]; let n5 = arr5.length; document.write(\"The minimum element is \"+ findMin(arr5, 0, n5-1)+\"<br>\"); let arr6=[5, 6, 7, 1, 2, 3, 4]; let n6 = arr6.length; document.write(\"The minimum element is \"+ findMin(arr6, 0, n6-1)+\"<br>\"); let arr7=[1, 2, 3, 4, 5, 6, 7]; let n7 = arr7.length; document.write(\"The minimum element is \"+ findMin(arr7, 0, n7-1)+\"<br>\"); let arr8=[2, 3, 4, 5, 6, 7, 8, 1]; let n8 = arr8.length; document.write(\"The minimum element is \"+ findMin(arr8, 0, n8-1)+\"<br>\"); let arr9=[3, 4, 5, 1, 2]; let n9 = arr9.length; document.write(\"The minimum element is \"+ findMin(arr9, 0, n9-1)+\"<br>\"); // This code is contributed by avanitrachhadiya2155 </script>", "e": 58496, "s": 56177, "text": null }, { "code": null, "e": 58505, "s": 58496, "text": "Output: " }, { "code": null, "e": 58730, "s": 58505, "text": "The minimum element is 1\nThe minimum element is 1\nThe minimum element is 1\nThe minimum element is 1\nThe minimum element is 1\nThe minimum element is 1\nThe minimum element is 1\nThe minimum element is 1\nThe minimum element is 1" }, { "code": null, "e": 58757, "s": 58730, "text": "How to handle duplicates? " }, { "code": null, "e": 58897, "s": 58757, "text": "The above approach in the worst case(If all the elements are the same) takes O(N).Below is the code to handle duplicates in O(log n) time. " }, { "code": null, "e": 58901, "s": 58897, "text": "C++" }, { "code": null, "e": 58906, "s": 58901, "text": "Java" }, { "code": null, "e": 58914, "s": 58906, "text": "Python3" }, { "code": null, "e": 58917, "s": 58914, "text": "C#" }, { "code": null, "e": 58928, "s": 58917, "text": "Javascript" }, { "code": "// C++ program to find minimum element in a sorted// and rotated array containing duplicate elements.#include <bits/stdc++.h>using namespace std; // Function to find minimum elementint findMin(int arr[], int low, int high){ while(low < high) { int mid = low + (high - low)/2; if (arr[mid] == arr[high]) high--; else if(arr[mid] > arr[high]) low = mid + 1; else high = mid; } return arr[high];} // Driver codeint main(){ int arr1[] = {5, 6, 1, 2, 3, 4}; int n1 = sizeof(arr1)/sizeof(arr1[0]); cout << \"The minimum element is \" << findMin(arr1, 0, n1-1) << endl; int arr2[] = {1, 2, 3, 4}; int n2 = sizeof(arr2)/sizeof(arr2[0]); cout << \"The minimum element is \" << findMin(arr2, 0, n2-1) << endl; int arr3[] = {1}; int n3 = sizeof(arr3)/sizeof(arr3[0]); cout<<\"The minimum element is \"<<findMin(arr3, 0, n3-1)<<endl; int arr4[] = {1, 2}; int n4 = sizeof(arr4)/sizeof(arr4[0]); cout<<\"The minimum element is \"<<findMin(arr4, 0, n4-1)<<endl; int arr5[] = {2, 1}; int n5 = sizeof(arr5)/sizeof(arr5[0]); cout<<\"The minimum element is \"<<findMin(arr5, 0, n5-1)<<endl; int arr6[] = {5, 6, 7, 1, 2, 3, 4}; int n6 = sizeof(arr6)/sizeof(arr6[0]); cout<<\"The minimum element is \"<<findMin(arr6, 0, n6-1)<<endl; int arr7[] = {1, 2, 3, 4, 5, 6, 7}; int n7 = sizeof(arr7)/sizeof(arr7[0]); cout << \"The minimum element is \" << findMin(arr7, 0, n7-1) << endl; int arr8[] = {2, 3, 4, 5, 6, 7, 8, 1}; int n8 = sizeof(arr8)/sizeof(arr8[0]); cout << \"The minimum element is \" << findMin(arr8, 0, n8-1) << endl; int arr9[] = {3, 4, 5, 1, 2}; int n9 = sizeof(arr9)/sizeof(arr9[0]); cout << \"The minimum element is \" << findMin(arr9, 0, n9-1) << endl; return 0;}// This is code is contributed by Saptakatha Adak.", "e": 60793, "s": 58928, "text": null }, { "code": "// Java program to find minimum element// in a sorted and rotated array containing// duplicate elements.import java.util.*;import java.lang.*; class GFG{ // Function to find minimum elementpublic static int findMin(int arr[], int low, int high){ while(low < high) { int mid = low + (high - low) / 2; if (arr[mid] == arr[high]) high--; else if(arr[mid] > arr[high]) low = mid + 1; else high = mid; } return arr[high];} // Driver codepublic static void main(String args[]){ int arr1[] = { 5, 6, 1, 2, 3, 4 }; int n1 = arr1.length; System.out.println(\"The minimum element is \" + findMin(arr1, 0, n1 - 1)); int arr2[] = { 1, 2, 3, 4 }; int n2 = arr2.length; System.out.println(\"The minimum element is \" + findMin(arr2, 0, n2 - 1)); int arr3[] = {1}; int n3 = arr3.length; System.out.println(\"The minimum element is \" + findMin(arr3, 0, n3 - 1)); int arr4[] = { 1, 2 }; int n4 = arr4.length; System.out.println(\"The minimum element is \" + findMin(arr4, 0, n4 - 1)); int arr5[] = { 2, 1 }; int n5 = arr5.length; System.out.println(\"The minimum element is \" + findMin(arr5, 0, n5 - 1)); int arr6[] = { 5, 6, 7, 1, 2, 3, 4 }; int n6 = arr6.length; System.out.println(\"The minimum element is \" + findMin(arr6, 0, n6 - 1)); int arr7[] = { 1, 2, 3, 4, 5, 6, 7 }; int n7 = arr7.length; System.out.println(\"The minimum element is \" + findMin(arr7, 0, n7 - 1)); int arr8[] = { 2, 3, 4, 5, 6, 7, 8, 1 }; int n8 = arr8.length; System.out.println(\"The minimum element is \" + findMin(arr8, 0, n8 - 1)); int arr9[] = { 3, 4, 5, 1, 2 }; int n9 = arr9.length; System.out.println(\"The minimum element is \" + findMin(arr9, 0, n9 - 1));}} // This is code is contributed by SoumikMondal", "e": 62857, "s": 60793, "text": null }, { "code": "# Python3 program to find# minimum element in a sorted# and rotated array containing# duplicate elements. # Function to find minimum elementdef findMin(arr, low, high): while (low < high): mid = low + (high - low) // 2; if (arr[mid] == arr[high]): high -= 1; elif (arr[mid] > arr[high]): low = mid + 1; else: high = mid; return arr[high]; # Driver codeif __name__ == '__main__': arr1 = [5, 6, 1, 2, 3, 4]; n1 = len(arr1); print(\"The minimum element is \", findMin(arr1, 0, n1 - 1)); arr2 = [1, 2, 3, 4]; n2 = len(arr2); print(\"The minimum element is \", findMin(arr2, 0, n2 - 1)); arr3 = [1]; n3 = len(arr3); print(\"The minimum element is \", findMin(arr3, 0, n3 - 1)); arr4 = [1, 2]; n4 = len(arr4); print(\"The minimum element is \", findMin(arr4, 0, n4 - 1)); arr5 = [2, 1]; n5 = len(arr5); print(\"The minimum element is \", findMin(arr5, 0, n5 - 1)); arr6 = [5, 6, 7, 1, 2, 3, 4]; n6 = len(arr6); print(\"The minimum element is \", findMin(arr6, 0, n6 - 1)); arr7 = [1, 2, 3, 4, 5, 6, 7]; n7 = len(arr7); print(\"The minimum element is \", findMin(arr7, 0, n7 - 1)); arr8 = [2, 3, 4, 5, 6, 7, 8, 1]; n8 = len(arr8); print(\"The minimum element is \", findMin(arr8, 0, n8 - 1)); arr9 = [3, 4, 5, 1, 2]; n9 = len(arr9); print(\"The minimum element is \", findMin(arr9, 0, n9 - 1)); # This code is contributed by Princi Singh", "e": 64422, "s": 62857, "text": null }, { "code": "// C# program to find minimum element// in a sorted and rotated array// containing duplicate elements.using System; class GFG{ // Function to find minimum elementpublic static int findMin(int []arr, int low, int high){ while (low < high) { int mid = low + (high - low) / 2; if (arr[mid] == arr[high]) high--; else if (arr[mid] > arr[high]) low = mid + 1; else high = mid; } return arr[high];} // Driver codepublic static void Main(String []args){ int []arr1 = { 5, 6, 1, 2, 3, 4 }; int n1 = arr1.Length; Console.WriteLine(\"The minimum element is \" + findMin(arr1, 0, n1 - 1)); int []arr2 = { 1, 2, 3, 4 }; int n2 = arr2.Length; Console.WriteLine(\"The minimum element is \" + findMin(arr2, 0, n2 - 1)); int []arr3 = {1}; int n3 = arr3.Length; Console.WriteLine(\"The minimum element is \" + findMin(arr3, 0, n3 - 1)); int []arr4 = { 1, 2 }; int n4 = arr4.Length; Console.WriteLine(\"The minimum element is \" + findMin(arr4, 0, n4 - 1)); int []arr5 = { 2, 1 }; int n5 = arr5.Length; Console.WriteLine(\"The minimum element is \" + findMin(arr5, 0, n5 - 1)); int []arr6 = { 5, 6, 7, 1, 2, 3, 4 }; int n6 = arr6.Length; Console.WriteLine(\"The minimum element is \" + findMin(arr6, 0, n6 - 1)); int []arr7 = { 1, 2, 3, 4, 5, 6, 7 }; int n7 = arr7.Length; Console.WriteLine(\"The minimum element is \" + findMin(arr7, 0, n7 - 1)); int []arr8 = { 2, 3, 4, 5, 6, 7, 8, 1 }; int n8 = arr8.Length; Console.WriteLine(\"The minimum element is \" + findMin(arr8, 0, n8 - 1)); int []arr9 = { 3, 4, 5, 1, 2 }; int n9 = arr9.Length; Console.WriteLine(\"The minimum element is \" + findMin(arr9, 0, n9 - 1));}} // This code is contributed by Amit Katiyar", "e": 66449, "s": 64422, "text": null }, { "code": "<script>// JavaScript program to find minimum element in a sorted// and rotated array containing duplicate elements. // Function to find minimum elementfunction findMin(arr, low, high){ while(low < high) { let mid = Math.floor(low + (high - low)/2); if (arr[mid] == arr[high]) high--; else if(arr[mid] > arr[high]) low = mid + 1; else high = mid; } return arr[high];} var arr1 = [5, 6, 1, 2, 3, 4];var n1 = arr1.length;document.write(\"The minimum element is \" + findMin(arr1, 0, n1-1) + \"<br>\"); var arr2 = [1, 2, 3, 4];var n2 = arr2.length;document.write(\"The minimum element is \" + findMin(arr2, 0, n2-1) + \"<br>\"); var arr3 = [1];var n3 = arr3.length;document.write(\"The minimum element is \" + findMin(arr3, 0, n3-1) + \"<br>\"); var arr4 = [1, 2];var n4 = arr4.length;document.write(\"The minimum element is \" + findMin(arr4, 0, n4-1) + \"<br>\"); var arr5 = [2, 1];var n5 = arr5.length;document.write(\"The minimum element is \" + findMin(arr5, 0, n5-1) + \"<br>\"); var arr6 = [5, 6, 7, 1, 2, 3, 4];var n6 = arr6.length;document.write(\"The minimum element is \" + findMin(arr6, 0, n6-1) + \"<br>\"); var arr7 = [1, 2, 3, 4, 5, 6, 7];var n7 = arr7.length;document.write(\"The minimum element is \" + findMin(arr7, 0, n7-1) + \"<br>\"); var arr8 = [2, 3, 4, 5, 6, 7, 8, 1];var n8 = arr8.length;document.write(\"The minimum element is \" + findMin(arr8, 0, n8-1) + \"<br>\"); var arr9 = [3, 4, 5, 1, 2];var n9 = arr9.length;document.write(\"The minimum element is \" + findMin(arr9, 0, n9-1) + \"<br>\"); // This code is contributed by probinsah</script>", "e": 68058, "s": 66449, "text": null }, { "code": null, "e": 68067, "s": 68058, "text": "Output: " }, { "code": null, "e": 68292, "s": 68067, "text": "The minimum element is 1\nThe minimum element is 1\nThe minimum element is 1\nThe minimum element is 1\nThe minimum element is 1\nThe minimum element is 1\nThe minimum element is 1\nThe minimum element is 1\nThe minimum element is 1" }, { "code": null, "e": 69145, "s": 68292, "text": "YouTubeGeeksforGeeks501K subscribersFind the minimum element in a sorted and rotated array | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:48•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=9k0vT6lx9XA\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 69315, "s": 69145, "text": "This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 69323, "s": 69317, "text": "ukasp" }, { "code": null, "e": 69331, "s": 69323, "text": "Sar_123" }, { "code": null, "e": 69345, "s": 69331, "text": "rathbhupendra" }, { "code": null, "e": 69361, "s": 69345, "text": "shreyashagrawal" }, { "code": null, "e": 69376, "s": 69361, "text": "SaptakathaAdak" }, { "code": null, "e": 69389, "s": 69376, "text": "SoumikMondal" }, { "code": null, "e": 69401, "s": 69389, "text": "anjali_1102" }, { "code": null, "e": 69416, "s": 69401, "text": "amit143katiyar" }, { "code": null, "e": 69429, "s": 69416, "text": "princi singh" }, { "code": null, "e": 69450, "s": 69429, "text": "avanitrachhadiya2155" }, { "code": null, "e": 69460, "s": 69450, "text": "probinsah" }, { "code": null, "e": 69476, "s": 69460, "text": "amartyaghoshgfg" }, { "code": null, "e": 69489, "s": 69476, "text": "simmytarika5" }, { "code": null, "e": 69495, "s": 69489, "text": "Adobe" }, { "code": null, "e": 69502, "s": 69495, "text": "Amazon" }, { "code": null, "e": 69516, "s": 69502, "text": "Binary Search" }, { "code": null, "e": 69526, "s": 69516, "text": "Microsoft" }, { "code": null, "e": 69541, "s": 69526, "text": "Morgan Stanley" }, { "code": null, "e": 69549, "s": 69541, "text": "Samsung" }, { "code": null, "e": 69558, "s": 69549, "text": "Snapdeal" }, { "code": null, "e": 69573, "s": 69558, "text": "Times Internet" }, { "code": null, "e": 69580, "s": 69573, "text": "Arrays" }, { "code": null, "e": 69599, "s": 69580, "text": "Divide and Conquer" }, { "code": null, "e": 69609, "s": 69599, "text": "Searching" }, { "code": null, "e": 69624, "s": 69609, "text": "Morgan Stanley" }, { "code": null, "e": 69631, "s": 69624, "text": "Amazon" }, { "code": null, "e": 69641, "s": 69631, "text": "Microsoft" }, { "code": null, "e": 69649, "s": 69641, "text": "Samsung" }, { "code": null, "e": 69658, "s": 69649, "text": "Snapdeal" }, { "code": null, "e": 69664, "s": 69658, "text": "Adobe" }, { "code": null, "e": 69679, "s": 69664, "text": "Times Internet" }, { "code": null, "e": 69686, "s": 69679, "text": "Arrays" }, { "code": null, "e": 69696, "s": 69686, "text": "Searching" }, { "code": null, "e": 69715, "s": 69696, "text": "Divide and Conquer" }, { "code": null, "e": 69729, "s": 69715, "text": "Binary Search" }, { "code": null, "e": 69827, "s": 69729, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 69842, "s": 69827, "text": "Arrays in Java" }, { "code": null, "e": 69858, "s": 69842, "text": "Arrays in C/C++" }, { "code": null, "e": 69885, "s": 69858, "text": "Program for array rotation" }, { "code": null, "e": 69933, "s": 69885, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 69977, "s": 69933, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 69988, "s": 69977, "text": "Merge Sort" }, { "code": null, "e": 69998, "s": 69988, "text": "QuickSort" }, { "code": null, "e": 70012, "s": 69998, "text": "Binary Search" }, { "code": null, "e": 70039, "s": 70012, "text": "Program for Tower of Hanoi" } ]
Check whether BST contains Dead End or not - GeeksforGeeks
07 Mar, 2022 Given a Binary search Tree that contains positive integer values greater than 0. The task is to check whether the BST contains a dead end or not. Here Dead End means, we are not able to insert any element after that node.Examples: Input : 8 / \ 5 9 / \ 2 7 / 1 Output : Yes Explanation : Node "1" is the dead End because after that we cant insert any element. Input : 8 / \ 7 10 / / \ 2 9 13 Output : Yes Explanation : We can't insert any element at node 9. If we take a closer look at the problem, we can notice that we basically need to check if there is a leaf node with value x such that x+1 and x-1 exist in BST with the exception of x = 1. For x = 1, we can’t insert 0 as the problem statement says BST contains positive integers only.To implement the above idea we first traverse the whole BST and store all nodes in a set. We also store all leaves in a separate hash to avoid re-traversal of BST. Finally, we check for every leaf node x, if x-1 and x+1 are present in set or not.Below is a C++ implementation of the above idea. C++ Python3 // C++ program check weather BST contains// dead end or not#include<bits/stdc++.h>using namespace std; // A BST nodestruct Node{ int data; struct Node *left, *right;}; // A utility function to create a new nodeNode *newNode(int data){ Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} /* A utility function to insert a new Node with given key in BST */struct Node* insert(struct Node* node, int key){ /* If the tree is empty, return a new Node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->data) node->left = insert(node->left, key); else if (key > node->data) node->right = insert(node->right, key); /* return the (unchanged) Node pointer */ return node;} // Function to store all node of given binary search treevoid storeNodes(Node * root, unordered_set<int> &all_nodes, unordered_set<int> &leaf_nodes){ if (root == NULL) return ; // store all node of binary search tree all_nodes.insert(root->data); // store leaf node in leaf_hash if (root->left==NULL && root->right==NULL) { leaf_nodes.insert(root->data); return ; } // recur call rest tree storeNodes(root-> left, all_nodes, leaf_nodes); storeNodes(root->right, all_nodes, leaf_nodes);} // Returns true if there is a dead end in tree,// else false.bool isDeadEnd(Node *root){ // Base case if (root == NULL) return false ; // create two empty hash sets that store all // BST elements and leaf nodes respectively. unordered_set<int> all_nodes, leaf_nodes; // insert 0 in 'all_nodes' for handle case // if bst contain value 1 all_nodes.insert(0); // Call storeNodes function to store all BST Node storeNodes(root, all_nodes, leaf_nodes); // Traversal leaf node and check Tree contain // continuous sequence of // size tree or Not for (auto i = leaf_nodes.begin() ; i != leaf_nodes.end(); i++) { int x = (*i); // Here we check first and last element of // continuous sequence that are x-1 & x+1 if (all_nodes.find(x+1) != all_nodes.end() && all_nodes.find(x-1) != all_nodes.end()) return true; } return false ;} // Driver programint main(){/* 8 / \ 5 11 / \ 2 7 \ 3 \ 4 */ Node *root = NULL; root = insert(root, 8); root = insert(root, 5); root = insert(root, 2); root = insert(root, 3); root = insert(root, 7); root = insert(root, 11); root = insert(root, 4); if (isDeadEnd(root) == true) cout << "Yes " << endl; else cout << "No " << endl; return 0;} # Python 3 program check# weather BST contains# dead end or notall_nodes = set()leaf_nodes = set() # A BST nodeclass newNode: def __init__(self, data): self.data = data self.left = None self.right = None ''' A utility function to insert a new Node with given key in BST '''def insert(node, key): '''/* If the tree is empty, return a new Node */ ''' if (node == None): return newNode(key) # Otherwise, recur down # the tree if (key < node.data): node.left = insert(node.left, key) else if (key > node.data): node.right = insert(node.right, key) # return the (unchanged) # Node pointer return node # Function to store all node# of given binary search treedef storeNodes(root): global all_nodes global leaf_nodes if (root == None): return # store all node of binary # search tree all_nodes.add(root.data) # store leaf node in leaf_hash if (root.left == None and root.right == None): leaf_nodes.add(root.data) return # recur call rest tree storeNodes(root. left) storeNodes(root.right) # Returns true if there is# a dead end in tree,# else false.def isDeadEnd(root): global all_nodes global leaf_nodes # Base case if (root == None): return False # create two empty hash # sets that store all BST # elements and leaf nodes # respectively. # insert 0 in 'all_nodes' # for handle case if bst # contain value 1 all_nodes.add(0) # Call storeNodes function # to store all BST Node storeNodes(root) # Traversal leaf node and # check Tree contain # continuous sequence of # size tree or Not for x in leaf_nodes: # Here we check first and # last element of continuous # sequence that are x-1 & x+1 if ((x + 1) in all_nodes and (x - 1) in all_nodes): return True return False # Driver codeif __name__ == '__main__': '''/* 8 / \ 5 11 / \ 2 7 \ 3 \ 4 */ ''' root = None root = insert(root, 8) root = insert(root, 5) root = insert(root, 2) root = insert(root, 3) root = insert(root, 7) root = insert(root, 11) root = insert(root, 4) if(isDeadEnd(root) == True): print("Yes") else: print("No") # This code is contributed by bgangwar59 Output: Yes Time Complexity : O(n)Simple Recursive solution to check whether BST contains dead EndThis article is contributed by Nishant_Singh(Pintu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. bgangwar59 guptapriyanshu2001 surinderdawra388 Binary Search Tree Hash Tree Hash Binary Search Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorted Array to Balanced BST Inorder Successor in Binary Search Tree Red-Black Tree | Set 2 (Insert) Find the node with minimum value in a Binary Search Tree Optimal Binary Search Tree | DP-24 Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing) Count pairs with given sum
[ { "code": null, "e": 25336, "s": 25308, "text": "\n07 Mar, 2022" }, { "code": null, "e": 25569, "s": 25336, "text": "Given a Binary search Tree that contains positive integer values greater than 0. The task is to check whether the BST contains a dead end or not. Here Dead End means, we are not able to insert any element after that node.Examples: " }, { "code": null, "e": 25990, "s": 25569, "text": "Input : 8\n / \\ \n 5 9\n / \\\n 2 7\n /\n 1 \nOutput : Yes\nExplanation : Node \"1\" is the dead End because\n after that we cant insert any element. \n\nInput : 8\n / \\ \n 7 10\n / / \\\n 2 9 13\n\nOutput : Yes\nExplanation : We can't insert any element at \n node 9. " }, { "code": null, "e": 26570, "s": 25990, "text": "If we take a closer look at the problem, we can notice that we basically need to check if there is a leaf node with value x such that x+1 and x-1 exist in BST with the exception of x = 1. For x = 1, we can’t insert 0 as the problem statement says BST contains positive integers only.To implement the above idea we first traverse the whole BST and store all nodes in a set. We also store all leaves in a separate hash to avoid re-traversal of BST. Finally, we check for every leaf node x, if x-1 and x+1 are present in set or not.Below is a C++ implementation of the above idea. " }, { "code": null, "e": 26574, "s": 26570, "text": "C++" }, { "code": null, "e": 26582, "s": 26574, "text": "Python3" }, { "code": "// C++ program check weather BST contains// dead end or not#include<bits/stdc++.h>using namespace std; // A BST nodestruct Node{ int data; struct Node *left, *right;}; // A utility function to create a new nodeNode *newNode(int data){ Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} /* A utility function to insert a new Node with given key in BST */struct Node* insert(struct Node* node, int key){ /* If the tree is empty, return a new Node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->data) node->left = insert(node->left, key); else if (key > node->data) node->right = insert(node->right, key); /* return the (unchanged) Node pointer */ return node;} // Function to store all node of given binary search treevoid storeNodes(Node * root, unordered_set<int> &all_nodes, unordered_set<int> &leaf_nodes){ if (root == NULL) return ; // store all node of binary search tree all_nodes.insert(root->data); // store leaf node in leaf_hash if (root->left==NULL && root->right==NULL) { leaf_nodes.insert(root->data); return ; } // recur call rest tree storeNodes(root-> left, all_nodes, leaf_nodes); storeNodes(root->right, all_nodes, leaf_nodes);} // Returns true if there is a dead end in tree,// else false.bool isDeadEnd(Node *root){ // Base case if (root == NULL) return false ; // create two empty hash sets that store all // BST elements and leaf nodes respectively. unordered_set<int> all_nodes, leaf_nodes; // insert 0 in 'all_nodes' for handle case // if bst contain value 1 all_nodes.insert(0); // Call storeNodes function to store all BST Node storeNodes(root, all_nodes, leaf_nodes); // Traversal leaf node and check Tree contain // continuous sequence of // size tree or Not for (auto i = leaf_nodes.begin() ; i != leaf_nodes.end(); i++) { int x = (*i); // Here we check first and last element of // continuous sequence that are x-1 & x+1 if (all_nodes.find(x+1) != all_nodes.end() && all_nodes.find(x-1) != all_nodes.end()) return true; } return false ;} // Driver programint main(){/* 8 / \\ 5 11 / \\ 2 7 \\ 3 \\ 4 */ Node *root = NULL; root = insert(root, 8); root = insert(root, 5); root = insert(root, 2); root = insert(root, 3); root = insert(root, 7); root = insert(root, 11); root = insert(root, 4); if (isDeadEnd(root) == true) cout << \"Yes \" << endl; else cout << \"No \" << endl; return 0;}", "e": 29327, "s": 26582, "text": null }, { "code": "# Python 3 program check# weather BST contains# dead end or notall_nodes = set()leaf_nodes = set() # A BST nodeclass newNode: def __init__(self, data): self.data = data self.left = None self.right = None ''' A utility function to insert a new Node with given key in BST '''def insert(node, key): '''/* If the tree is empty, return a new Node */ ''' if (node == None): return newNode(key) # Otherwise, recur down # the tree if (key < node.data): node.left = insert(node.left, key) else if (key > node.data): node.right = insert(node.right, key) # return the (unchanged) # Node pointer return node # Function to store all node# of given binary search treedef storeNodes(root): global all_nodes global leaf_nodes if (root == None): return # store all node of binary # search tree all_nodes.add(root.data) # store leaf node in leaf_hash if (root.left == None and root.right == None): leaf_nodes.add(root.data) return # recur call rest tree storeNodes(root. left) storeNodes(root.right) # Returns true if there is# a dead end in tree,# else false.def isDeadEnd(root): global all_nodes global leaf_nodes # Base case if (root == None): return False # create two empty hash # sets that store all BST # elements and leaf nodes # respectively. # insert 0 in 'all_nodes' # for handle case if bst # contain value 1 all_nodes.add(0) # Call storeNodes function # to store all BST Node storeNodes(root) # Traversal leaf node and # check Tree contain # continuous sequence of # size tree or Not for x in leaf_nodes: # Here we check first and # last element of continuous # sequence that are x-1 & x+1 if ((x + 1) in all_nodes and (x - 1) in all_nodes): return True return False # Driver codeif __name__ == '__main__': '''/* 8 / \\ 5 11 / \\ 2 7 \\ 3 \\ 4 */ ''' root = None root = insert(root, 8) root = insert(root, 5) root = insert(root, 2) root = insert(root, 3) root = insert(root, 7) root = insert(root, 11) root = insert(root, 4) if(isDeadEnd(root) == True): print(\"Yes\") else: print(\"No\") # This code is contributed by bgangwar59", "e": 31819, "s": 29327, "text": null }, { "code": null, "e": 31829, "s": 31819, "text": "Output: " }, { "code": null, "e": 31833, "s": 31829, "text": "Yes" }, { "code": null, "e": 32348, "s": 31833, "text": "Time Complexity : O(n)Simple Recursive solution to check whether BST contains dead EndThis article is contributed by Nishant_Singh(Pintu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 32359, "s": 32348, "text": "bgangwar59" }, { "code": null, "e": 32378, "s": 32359, "text": "guptapriyanshu2001" }, { "code": null, "e": 32395, "s": 32378, "text": "surinderdawra388" }, { "code": null, "e": 32414, "s": 32395, "text": "Binary Search Tree" }, { "code": null, "e": 32419, "s": 32414, "text": "Hash" }, { "code": null, "e": 32424, "s": 32419, "text": "Tree" }, { "code": null, "e": 32429, "s": 32424, "text": "Hash" }, { "code": null, "e": 32448, "s": 32429, "text": "Binary Search Tree" }, { "code": null, "e": 32453, "s": 32448, "text": "Tree" }, { "code": null, "e": 32551, "s": 32453, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32580, "s": 32551, "text": "Sorted Array to Balanced BST" }, { "code": null, "e": 32620, "s": 32580, "text": "Inorder Successor in Binary Search Tree" }, { "code": null, "e": 32652, "s": 32620, "text": "Red-Black Tree | Set 2 (Insert)" }, { "code": null, "e": 32709, "s": 32652, "text": "Find the node with minimum value in a Binary Search Tree" }, { "code": null, "e": 32744, "s": 32709, "text": "Optimal Binary Search Tree | DP-24" }, { "code": null, "e": 32829, "s": 32744, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 32865, "s": 32829, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 32896, "s": 32865, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 32930, "s": 32896, "text": "Hashing | Set 3 (Open Addressing)" } ]
Angular10 getLocaleId() Function - GeeksforGeeks
30 Apr, 2021 In this article, we are going to see what is getLocaleId in Angular 10 and how to use it. The getLocaleId is used to get the locale ID from the current locale. Syntax: getLocaleId(locale: string): string NgModule: Module used by getLocaleId is: CommonModule Approach: Create the angular app to be used In app.module.ts import LOCALE_ID because we need locale to be imported for using get getLocaleId. import { LOCALE_ID, NgModule } from '@angular/core'; In app.component.ts import getLocaleId and LOCALE_ID inject LOCALE_ID as a public variable. In app.component.html show the local variable using string interpolation serve the angular app using ng serve to see the output. Parameters: locale: the locale code Return value: string: the locale code. Example 1: app.module.ts import { LOCALE_ID, NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [ { provide: LOCALE_ID, useValue: 'en-GB' }, ], bootstrap: [AppComponent]})export class AppModule { } app.component.ts import {FormStyle, getLocaleId, TranslationWidth} from '@angular/common'; import { Component, Inject,OnInit, LOCALE_ID } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent { for = getLocaleId(this.locale); constructor( @Inject(LOCALE_ID) public locale: string,){} } app.component.html <h1> GeeksforGeeks</h1><p>Locale id is: {{for}}</p> Output: Reference: https://angular.io/api/common/getLocaleId Angular10 AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Angular Libraries For Web Developers How to use <mat-chip-list> and <mat-chip> in Angular Material ? How to make a Bootstrap Modal Popup in Angular 9/8 ? How to create module with Routing in Angular 9 ? Angular PrimeNG Dropdown Component 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": 25109, "s": 25081, "text": "\n30 Apr, 2021" }, { "code": null, "e": 25199, "s": 25109, "text": "In this article, we are going to see what is getLocaleId in Angular 10 and how to use it." }, { "code": null, "e": 25269, "s": 25199, "text": "The getLocaleId is used to get the locale ID from the current locale." }, { "code": null, "e": 25277, "s": 25269, "text": "Syntax:" }, { "code": null, "e": 25313, "s": 25277, "text": "getLocaleId(locale: string): string" }, { "code": null, "e": 25354, "s": 25313, "text": "NgModule: Module used by getLocaleId is:" }, { "code": null, "e": 25367, "s": 25354, "text": "CommonModule" }, { "code": null, "e": 25377, "s": 25367, "text": "Approach:" }, { "code": null, "e": 25411, "s": 25377, "text": "Create the angular app to be used" }, { "code": null, "e": 25510, "s": 25411, "text": "In app.module.ts import LOCALE_ID because we need locale to be imported for using get getLocaleId." }, { "code": null, "e": 25563, "s": 25510, "text": "import { LOCALE_ID, NgModule } from '@angular/core';" }, { "code": null, "e": 25616, "s": 25563, "text": "In app.component.ts import getLocaleId and LOCALE_ID" }, { "code": null, "e": 25655, "s": 25616, "text": "inject LOCALE_ID as a public variable." }, { "code": null, "e": 25728, "s": 25655, "text": "In app.component.html show the local variable using string interpolation" }, { "code": null, "e": 25784, "s": 25728, "text": "serve the angular app using ng serve to see the output." }, { "code": null, "e": 25796, "s": 25784, "text": "Parameters:" }, { "code": null, "e": 25820, "s": 25796, "text": "locale: the locale code" }, { "code": null, "e": 25834, "s": 25820, "text": "Return value:" }, { "code": null, "e": 25859, "s": 25834, "text": "string: the locale code." }, { "code": null, "e": 25870, "s": 25859, "text": "Example 1:" }, { "code": null, "e": 25884, "s": 25870, "text": "app.module.ts" }, { "code": "import { LOCALE_ID, NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [ { provide: LOCALE_ID, useValue: 'en-GB' }, ], bootstrap: [AppComponent]})export class AppModule { }", "e": 26357, "s": 25884, "text": null }, { "code": null, "e": 26374, "s": 26357, "text": "app.component.ts" }, { "code": "import {FormStyle, getLocaleId, TranslationWidth} from '@angular/common'; import { Component, Inject,OnInit, LOCALE_ID } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent { for = getLocaleId(this.locale); constructor( @Inject(LOCALE_ID) public locale: string,){} }", "e": 26785, "s": 26374, "text": null }, { "code": null, "e": 26804, "s": 26785, "text": "app.component.html" }, { "code": "<h1> GeeksforGeeks</h1><p>Locale id is: {{for}}</p>", "e": 26858, "s": 26804, "text": null }, { "code": null, "e": 26866, "s": 26858, "text": "Output:" }, { "code": null, "e": 26919, "s": 26866, "text": "Reference: https://angular.io/api/common/getLocaleId" }, { "code": null, "e": 26929, "s": 26919, "text": "Angular10" }, { "code": null, "e": 26939, "s": 26929, "text": "AngularJS" }, { "code": null, "e": 26956, "s": 26939, "text": "Web Technologies" }, { "code": null, "e": 27054, "s": 26956, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27063, "s": 27054, "text": "Comments" }, { "code": null, "e": 27076, "s": 27063, "text": "Old Comments" }, { "code": null, "e": 27120, "s": 27076, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 27184, "s": 27120, "text": "How to use <mat-chip-list> and <mat-chip> in Angular Material ?" }, { "code": null, "e": 27237, "s": 27184, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 27286, "s": 27237, "text": "How to create module with Routing in Angular 9 ?" }, { "code": null, "e": 27321, "s": 27286, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 27363, "s": 27321, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27396, "s": 27363, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27458, "s": 27396, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27501, "s": 27458, "text": "How to fetch data from an API in ReactJS ?" } ]
Changing the color of an axis in Matplotlib
First, we can get the axes. Then, ax.spines could help to set the color by specifying the name of the axes, i.e., top, bottom, right and left. Add an axes to the current figure and make it the current axes. Add an axes to the current figure and make it the current axes. Using step 1 axes, we can set the color of all the axes. Using step 1 axes, we can set the color of all the axes. Using ax.spines[axes].set_color(‘color’), set the color of the axes. Axes could be bottom, top, right, and left. Color could be yellow, red, black, and blue. Using ax.spines[axes].set_color(‘color’), set the color of the axes. Axes could be bottom, top, right, and left. Color could be yellow, red, black, and blue. To show the figure, use the plt.show() method. To show the figure, use the plt.show() method. from matplotlib import pyplot as plt ax = plt.axes() ax.spines['bottom'].set_color('yellow') ax.spines['top'].set_color('red') ax.spines['right'].set_color('black') ax.spines['left'].set_color('blue') plt.show()
[ { "code": null, "e": 1205, "s": 1062, "text": "First, we can get the axes. Then, ax.spines could help to set the color by specifying the name of the axes, i.e., top, bottom, right and left." }, { "code": null, "e": 1269, "s": 1205, "text": "Add an axes to the current figure and make it the current axes." }, { "code": null, "e": 1333, "s": 1269, "text": "Add an axes to the current figure and make it the current axes." }, { "code": null, "e": 1390, "s": 1333, "text": "Using step 1 axes, we can set the color of all the axes." }, { "code": null, "e": 1447, "s": 1390, "text": "Using step 1 axes, we can set the color of all the axes." }, { "code": null, "e": 1605, "s": 1447, "text": "Using ax.spines[axes].set_color(‘color’), set the color of the axes. Axes could be bottom, top, right, and left. Color could be yellow, red, black, and blue." }, { "code": null, "e": 1763, "s": 1605, "text": "Using ax.spines[axes].set_color(‘color’), set the color of the axes. Axes could be bottom, top, right, and left. Color could be yellow, red, black, and blue." }, { "code": null, "e": 1810, "s": 1763, "text": "To show the figure, use the plt.show() method." }, { "code": null, "e": 1857, "s": 1810, "text": "To show the figure, use the plt.show() method." }, { "code": null, "e": 2072, "s": 1857, "text": "from matplotlib import pyplot as plt\n\nax = plt.axes()\n\nax.spines['bottom'].set_color('yellow')\nax.spines['top'].set_color('red')\nax.spines['right'].set_color('black')\nax.spines['left'].set_color('blue')\n\nplt.show()" } ]
Marker interface in Java programming.
An empty interface in Java is known as a marker interface i.e. it does not contain any methods or fields by implementing these interfaces a class will exhibit a special behavior with respect to the interface implemented. java.lang.Cloneable and java.io.Serializable are examples of marker interfaces. Consider the following example, here we have a class with the name Student which implements the marking interface Cloneable. In the main method we are trying to create an object of the Student class and clone it using the clone() method. Live Demo import java.util.Scanner; public class Student implements Cloneable { int age; String name; public Student (String name, int age){ this.age = age; this.name = name; } public void display() { System.out.println("Name of the student is: "+name); System.out.println("Age of the student is: "+age); } public static void main (String args[]) throws CloneNotSupportedException { Scanner sc = new Scanner(System.in); System.out.println("Enter your name: "); String name = sc.next(); System.out.println("Enter your age: "); int age = sc.nextInt(); Student obj = new Student(name, age); Student obj2 = (Student) obj.clone(); obj2.display(); } } Enter your name: Krishna Enter your age: 29 Name of the student is: Krishna Age of the student is: 29 In the following java program, the class Student has two instance variables name and age where age is declared transient. In another class named ExampleSerialize, we are trying to serialize and desterilize the Student object and display its instance variables. Since the age is made invisible (transient) only the name-value is displayed. Live Demo import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; class Student implements Serializable{ private String name; private transient int age; public Student(String name, int age){ this.name = name; this.age = age; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public int getAge() { return this.age; } } public class ExampleSerialize { public static void main(String args[]) throws Exception{ Student std1 = new Student("Krishna", 30); FileOutputStream fos = new FileOutputStream("e:\\student.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(std1); FileInputStream fis = new FileInputStream("e:\\student.ser"); ObjectInputStream ois = new ObjectInputStream(fis); Student std2 = (Student) ois.readObject(); System.out.println(std2.getName()); } } Krishna
[ { "code": null, "e": 1363, "s": 1062, "text": "An empty interface in Java is known as a marker interface i.e. it does not contain any methods or fields by implementing these interfaces a class will exhibit a special behavior with respect to the interface implemented. java.lang.Cloneable and java.io.Serializable are examples of marker interfaces." }, { "code": null, "e": 1601, "s": 1363, "text": "Consider the following example, here we have a class with the name Student which implements the marking interface Cloneable. In the main method we are trying to create an object of the Student class and clone it using the clone() method." }, { "code": null, "e": 1612, "s": 1601, "text": " Live Demo" }, { "code": null, "e": 2344, "s": 1612, "text": "import java.util.Scanner;\npublic class Student implements Cloneable {\n int age;\n String name;\n public Student (String name, int age){\n this.age = age;\n this.name = name;\n }\n public void display() {\n System.out.println(\"Name of the student is: \"+name);\n System.out.println(\"Age of the student is: \"+age);\n }\n public static void main (String args[]) throws CloneNotSupportedException {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter your name: \");\n String name = sc.next();\n System.out.println(\"Enter your age: \");\n int age = sc.nextInt();\n Student obj = new Student(name, age);\n Student obj2 = (Student) obj.clone();\n obj2.display();\n }\n}" }, { "code": null, "e": 2446, "s": 2344, "text": "Enter your name:\nKrishna\nEnter your age:\n29\nName of the student is: Krishna\nAge of the student is: 29" }, { "code": null, "e": 2785, "s": 2446, "text": "In the following java program, the class Student has two instance variables name and age where age is declared transient. In another class named ExampleSerialize, we are trying to serialize and desterilize the Student object and display its instance variables. Since the age is made invisible (transient) only the name-value is displayed." }, { "code": null, "e": 2796, "s": 2785, "text": " Live Demo" }, { "code": null, "e": 3908, "s": 2796, "text": "import java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\nimport java.io.Serializable;\nclass Student implements Serializable{\n private String name;\n private transient int age;\n public Student(String name, int age){\n this.name = name;\n this.age = age;\n }\n public String getName() {\n return this.name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public void setAge(int age) {\n this.age = age;\n }\n public int getAge() {\n return this.age;\n }\n}\npublic class ExampleSerialize {\n public static void main(String args[]) throws Exception{\n Student std1 = new Student(\"Krishna\", 30);\n FileOutputStream fos = new FileOutputStream(\"e:\\\\student.ser\");\n ObjectOutputStream oos = new ObjectOutputStream(fos);\n oos.writeObject(std1);\n FileInputStream fis = new FileInputStream(\"e:\\\\student.ser\");\n ObjectInputStream ois = new ObjectInputStream(fis);\n Student std2 = (Student) ois.readObject();\n System.out.println(std2.getName());\n }\n}" }, { "code": null, "e": 3916, "s": 3908, "text": "Krishna" } ]
Git - Patch Operation
Patch is a text file, whose contents are similar to Git diff, but along with code, it also has metadata about commits; e.g., commit ID, date, commit message, etc. We can create a patch from commits and other people can apply them to their repository. Jerry implements the strcat function for his project. Jerry can create a path of his code and send it to Tom. Then, he can apply the received patch to his code. Jerry uses the Git format-patch command to create a patch for the latest commit. If you want to create a patch for a specific commit, then use COMMIT_ID with the format-patch command. [jerry@CentOS project]$ pwd /home/jerry/jerry_repo/project/src [jerry@CentOS src]$ git status -s M string_operations.c ?? string_operations [jerry@CentOS src]$ git add string_operations.c [jerry@CentOS src]$ git commit -m "Added my_strcat function" [master b4c7f09] Added my_strcat function 1 files changed, 13 insertions(+), 0 deletions(-) [jerry@CentOS src]$ git format-patch -1 0001-Added-my_strcat-function.patch The above command creates .patch files inside the current working directory. Tom can use this patch to modify his files. Git provides two commands to apply patches git amand git apply, respectively. Git apply modifies the local files without creating commit, while git am modifies the file and creates commit as well. To apply patch and create commit, use the following command − [tom@CentOS src]$ pwd /home/tom/top_repo/project/src [tom@CentOS src]$ git diff [tom@CentOS src]$ git status –s [tom@CentOS src]$ git apply 0001-Added-my_strcat-function.patch [tom@CentOS src]$ git status -s M string_operations.c ?? 0001-Added-my_strcat-function.patch The patch gets applied successfully, now we can view the modifications by using the git diff command. [tom@CentOS src]$ git diff The above command will produce the following result − diff --git a/src/string_operations.c b/src/string_operations.c index 8ab7f42..f282fcf 100644 --- a/src/string_operations.c +++ b/src/string_operations.c @@ -1,5 +1,16 @@ #include <stdio.h> +char *my_strcat(char *t, char *s) diff --git a/src/string_operations.c b/src/string_operations.c index 8ab7f42..f282fcf 100644 --- a/src/string_operations.c +++ b/src/string_operations.c @@ -1,5 +1,16 @@ #include <stdio.h> +char *my_strcat(char *t, char *s) + { + char *p = t; + + + while (*p) ++p; + while (*p++ = *s++) + ; + return t; + } + size_t my_strlen(const char *s) { const char *p = s; @@ -23,6 +34,7 @@ int main(void) { 251 Lectures 35.5 hours Gowthami Swarna 23 Lectures 2 hours Asif Hussain 15 Lectures 1.5 hours Abhilash Nelson 125 Lectures 9 hours John Shea 13 Lectures 2.5 hours Raghu Pandey 13 Lectures 3 hours Sebastian Sulinski Print Add Notes Bookmark this page
[ { "code": null, "e": 2296, "s": 2045, "text": "Patch is a text file, whose contents are similar to Git diff, but along with code, it also has metadata about commits; e.g., commit ID, date, commit message, etc. We can create a patch from commits and other people can apply them to their repository." }, { "code": null, "e": 2457, "s": 2296, "text": "Jerry implements the strcat function for his project. Jerry can create a path of his code and send it to Tom. Then, he can apply the received patch to his code." }, { "code": null, "e": 2641, "s": 2457, "text": "Jerry uses the Git format-patch command to create a patch for the latest commit. If you want to create a patch for a specific commit, then use COMMIT_ID with the format-patch command." }, { "code": null, "e": 3064, "s": 2641, "text": "[jerry@CentOS project]$ pwd\n/home/jerry/jerry_repo/project/src\n\n[jerry@CentOS src]$ git status -s\nM string_operations.c\n?? string_operations\n\n[jerry@CentOS src]$ git add string_operations.c\n\n[jerry@CentOS src]$ git commit -m \"Added my_strcat function\"\n\n[master b4c7f09] Added my_strcat function\n1 files changed, 13 insertions(+), 0 deletions(-)\n\n[jerry@CentOS src]$ git format-patch -1\n0001-Added-my_strcat-function.patch\n" }, { "code": null, "e": 3382, "s": 3064, "text": "The above command creates .patch files inside the current working directory. Tom can use this patch to modify his files. Git provides two commands to apply patches git amand git apply, respectively. Git apply modifies the local files without creating commit, while git am modifies the file and creates commit as well." }, { "code": null, "e": 3444, "s": 3382, "text": "To apply patch and create commit, use the following command −" }, { "code": null, "e": 3718, "s": 3444, "text": "[tom@CentOS src]$ pwd\n/home/tom/top_repo/project/src\n\n[tom@CentOS src]$ git diff\n\n[tom@CentOS src]$ git status –s\n\n[tom@CentOS src]$ git apply 0001-Added-my_strcat-function.patch\n\n[tom@CentOS src]$ git status -s\nM string_operations.c\n?? 0001-Added-my_strcat-function.patch\n" }, { "code": null, "e": 3820, "s": 3718, "text": "The patch gets applied successfully, now we can view the modifications by using the git diff command." }, { "code": null, "e": 3848, "s": 3820, "text": "[tom@CentOS src]$ git diff\n" }, { "code": null, "e": 3902, "s": 3848, "text": "The above command will produce the following result −" }, { "code": null, "e": 4569, "s": 3902, "text": "diff --git a/src/string_operations.c b/src/string_operations.c\nindex 8ab7f42..f282fcf 100644\n--- a/src/string_operations.c\n+++ b/src/string_operations.c\n@@ -1,5 +1,16 @@\n#include <stdio.h>\n+char *my_strcat(char *t, char *s)\ndiff --git a/src/string_operations.c b/src/string_operations.c\nindex 8ab7f42..f282fcf 100644\n--- a/src/string_operations.c\n+++ b/src/string_operations.c\n@@ -1,5 +1,16 @@\n#include <stdio.h>\n+char *my_strcat(char *t, char *s)\n+\n{\n +\n char *p = t;\n +\n +\n +\n while (*p)\n ++p;\n +\n while (*p++ = *s++)\n + ;\n + return t;\n +\n}\n+\nsize_t my_strlen(const char *s)\n{\n const char *p = s;\n @@ -23,6 +34,7 @@ int main(void)\n {\n" }, { "code": null, "e": 4606, "s": 4569, "text": "\n 251 Lectures \n 35.5 hours \n" }, { "code": null, "e": 4623, "s": 4606, "text": " Gowthami Swarna" }, { "code": null, "e": 4656, "s": 4623, "text": "\n 23 Lectures \n 2 hours \n" }, { "code": null, "e": 4670, "s": 4656, "text": " Asif Hussain" }, { "code": null, "e": 4705, "s": 4670, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4722, "s": 4705, "text": " Abhilash Nelson" }, { "code": null, "e": 4756, "s": 4722, "text": "\n 125 Lectures \n 9 hours \n" }, { "code": null, "e": 4767, "s": 4756, "text": " John Shea" }, { "code": null, "e": 4802, "s": 4767, "text": "\n 13 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4816, "s": 4802, "text": " Raghu Pandey" }, { "code": null, "e": 4849, "s": 4816, "text": "\n 13 Lectures \n 3 hours \n" }, { "code": null, "e": 4869, "s": 4849, "text": " Sebastian Sulinski" }, { "code": null, "e": 4876, "s": 4869, "text": " Print" }, { "code": null, "e": 4887, "s": 4876, "text": " Add Notes" } ]
Count the Number of matching characters in a pair of string in Python
We are given two strings. We need to find the count it of the characters in the first string which are also present in a second string. The set function gives us unique values all the elements in a string. We also use the the & operator which finds the common elements between the two given strings. Live Demo strA = 'Tutorials Point' uniq_strA = set(strA) # Given String print("Given String\n",strA) strB = 'aeio' uniq_strB = set(strB) # Given String print("Search character strings\n",strB) common_chars = uniq_strA & uniq_strB print("Count of matching characters are : ",len(common_chars)) Running the above code gives us the following result − Given String Tutorials Point Search character strings aeio Count of matching characters are : 3 We use the search function from the re module. We use a count variable and keep incrementing it when the search result is true. Live Demo import re strA = 'Tutorials Point' # Given String print("Given String\n",strA) strB = 'aeio' # Given String print("Search character strings\n",strB) cnt = 0 for i in strA: if re.search(i, strB): cnt = cnt + 1 print("Count of matching characters are : ",cnt) Running the above code gives us the following result − Given String Tutorials Point Search character strings aeio Count of matching characters are : 5
[ { "code": null, "e": 1198, "s": 1062, "text": "We are given two strings. We need to find the count it of the characters in the first string which are also present in a second string." }, { "code": null, "e": 1362, "s": 1198, "text": "The set function gives us unique values all the elements in a string. We also use the the & operator which finds the common elements between the two given strings." }, { "code": null, "e": 1373, "s": 1362, "text": " Live Demo" }, { "code": null, "e": 1656, "s": 1373, "text": "strA = 'Tutorials Point'\nuniq_strA = set(strA)\n# Given String\nprint(\"Given String\\n\",strA)\nstrB = 'aeio'\nuniq_strB = set(strB)\n# Given String\nprint(\"Search character strings\\n\",strB)\ncommon_chars = uniq_strA & uniq_strB\nprint(\"Count of matching characters are : \",len(common_chars))" }, { "code": null, "e": 1711, "s": 1656, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1807, "s": 1711, "text": "Given String\nTutorials Point\nSearch character strings\naeio\nCount of matching characters are : 3" }, { "code": null, "e": 1935, "s": 1807, "text": "We use the search function from the re module. We use a count variable and keep incrementing it when the search result is true." }, { "code": null, "e": 1946, "s": 1935, "text": " Live Demo" }, { "code": null, "e": 2213, "s": 1946, "text": "import re\nstrA = 'Tutorials Point'\n# Given String\nprint(\"Given String\\n\",strA)\nstrB = 'aeio'\n# Given String\nprint(\"Search character strings\\n\",strB)\ncnt = 0\nfor i in strA:\n if re.search(i, strB):\n cnt = cnt + 1\nprint(\"Count of matching characters are : \",cnt)" }, { "code": null, "e": 2268, "s": 2213, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2364, "s": 2268, "text": "Given String\nTutorials Point\nSearch character strings\naeio\nCount of matching characters are : 5" } ]
Train Image Recognition AI with 5 lines of code | by Moses Olafenwa | Towards Data Science
In this article, we will briefly introduce the field of artificial intelligence, particularly in computer vision, the challenges involved, the existing modern solutions to these challenges and how you can apply these solutions conveniently and easily without taking much time and effort. Artificial Intelligence has for decades been a field of research in which both scientists and engineers have been making intense efforts to unravel the mystery of getting machines and computers to perceive and understand our world well enough to act properly and serve humanity. One of the most important aspect of this research work is getting computers to understand visual information (images and videos) generated everyday around us. This field of getting computers to perceive and understand visual information is known as computer vision. During the rise of artificial intelligence research in the 1950s to the 1980s, computers were manually given instructions on how to recognize images, objects in images and what features to look out for. This method are traditional algorithms and were called Expert Systems, as they require that humans take the pain of identifying features for each unique scene of object that has to be recognize and representing these features in mathematical models that the computer can understand. That involves a whole lot of tedious work because there are hundreds and thousands of various ways an object can be represented and there are thousands (or even millions) of different scenes and objects that uniquely exist, and therefore finding the optimized and accurate mathematical models to represent all the possible features of each objects or scene, and for all possible objects or scene is more of work that will last forever. Then, in the 1990s, the concept of Machine Learning was introduced and it ushered in an era in which instead of telling computers what to look out for in recognizing scenes and objects in images and videos, we can instead design algorithms that will make computers to learn how to recognize scenes and objects in images by itself, just like a child learns to understand his/her environment by exploring. Machine learning opened the way for computers to learn to recognize almost any scene or object we want them too. With the emergence of powerful computers such as the NVIDIA GPUs and state-of-the-art Deep Learning algorithms for image recognition such as AlexNet in 2012 by Alex Krizhevsky et al, ResNet in 2015 by Kaeming He et al, SqueezeNet in 2016 by Forrest Landola et al, DenseNet in 2016 by Gao Huang et al, to mention a few, it is possible to put together a number of pictures (more like image books for computers) and define an artificial intelligence model to learn features of scenes and objects in these pictures by itself and use the knowledge gained from the learning process to recognize all other instance of the type of scene or objects it will encounter after. To train an artificial intelligence model that can recognize whatever you want it to recognize in pictures, it traditional involves lots of expertise in Applied Mathematics and use of Deep Learning libraries, not to mention the amount of time involved and stress you have to go through to write the code for the algorithm and fit the code to your images. This is where we have provided our solutions. Our team at AI Commons has developed a python library that can let you train an artificial intelligence model that can recognize any object you want it to recognize in images using just 5 simple lines of python code. The python library is ImageAI , a library built to let students, developers and researchers with all levels of expertise to build systems and applications with state-of-the-art computer vision capabilities using between 5 to 15 simple lines of code. Now, let us walk you through creating your first artificial intelligence model that can recognize whatever you want it to. To train your artificial intelligence model, you need a collection of images called a dataset. A dataset contains hundreds to thousands of sample images of objects you want your artificial intelligence model to recognize. But you don’t have worry! We are not asking you to go and download thousands of pictures right now just to train your artificial intelligence model. For this tutorial, we have provided a dataset called IdenProf. IdenProf (Identifiable Professionals) is a dataset that contains 11,000 pictures of 10 different professionals that humans can see and recognize their jobs by their mode of dressing. The classes of professionals whose pictures are in this dataset are as below: · Chef · Doctor · Engineer · Farmer · Firefighter · Judge · Mechanic · Pilot · Police · Waiter This dataset is split into 9000 (900 pictures for each profession) pictures to train the artificial intelligence model and 2000 (200 pictures for each profession) pictures to test the performance of the artificial intelligence model as it is training. IdenProf has been properly arranged and made ready for training your artificial intelligence model to recognize professionals by their mode of dressing. For reference purposes, if you are using your own image dataset, you must collect at least 500 pictures for each object or scene you want your artificial intelligence model to recognize. To train any image dataset you collect yourself with ImageAI, you must arrange the images in folders as seen in the example below: idenprof//train//chef// 900 images of chefsidenprof//train//doctor// 900 images of doctorsidenprof//train//engineer// 900 images of engineeridenprof//train//farmer// 900 images of farmersidenprof//train//firefighter// 900 images of firefightersidenprof//train//judge// 900 images of judgesidenprof//train//mechanic// 900 images of mechanicsidenprof//train//pilot// 900 images of pilotsidenprof//train//chef// 900 images of chefidenprof//train//police// 900 images of policeidenprof//train//waiter// 900 images of waitersidenprof//test//chef// 200 images of chefsidenprof//test//doctor// 200 images of doctorsidenprof//test//engineer// 200 images of engineeridenprof//test//farmer// 200 images of farmersidenprof//test//firefighter// 200 images of firefightersidenprof//test//judge// 200 images of judgesidenprof//test//mechanic// 200 images of mechanicsidenprof//test//pilot// 200 images of pilotsidenprof//test//chef// 200 images of chefidenprof//test//police// 200 images of policeidenprof//test//waiter// 200 images of waiters Now that you have understand how to prepare own image dataset for training artificial intelligence models, we will now proceed with guiding you training an artificial intelligence model to recognize professionals using ImageAI. · First you must download the zip of IdenProf dataset via this link. Also you can view all the details and sample results of artificial intelligence models trained to recognize professions in the IdenProf GitHub repository whose link is below. https://github.com/OlafenwaMoses/IdenProf · Because training artificial intelligence models require high performance computer systems, I strongly advice that you ensure your computer/laptop that you want to use for this training has NVIDIA GPU. Alternatively, you can use Google Colab for this experiment has it offers a free NVIDIA K80 GPU for experiments. · Then you have to install ImageAI and its dependencies. Install Python 3.7.6 and pip (Skip this section if you already have Python 3.7.6) www.python.org Install ImageAI and dependencies (Skip any of the installation instruction in this section if you already have the library installed ) - Tensorflow pip install tensorflow==2.4.0 - Others pip install keras==2.4.3 numpy==1.19.3 pillow==7.0.0 scipy==1.4.1 h5py==2.10.0 matplotlib==3.3.2 opencv-python keras-resnet==0.2.0 Install the ImageAI library pip install imageai --upgrade · Create a python file with any name you want to give it, for example “FirstTraining.py”. · Copy the zip of the IdenProf dataset into the folder where your Python file is. Then unzip it into the same folder. · Then copy the code below into the python file (e.g FirstTraining.py). That’s it! That’s all the code you need to train your artificial intelligence model. Before you run the code to start the training, let us explain the code. In the first line, we imported ImageAI’s model training class. In the second line we, created an instance of the model training class. In the third line, we set the model type to ResNet50 (there are four model types available which are MobileNetv2, ResNet50, InceptionV3 and DenseNet121). In the fourth line, we set the data directory (dataset directory) to the folder of the dataset zip file you unzipped. Then in the fifth line, we call the trainModel function and specified the following values: • number_objects : This refers to the number of different types of professionals in the IdenProf dataset.• num_experiments : This is the number of times the model trainer will study all the images in the idenprof dataset in order to achieve maximum accuracy.• Enhance_data (Optional) : This is to tell the model trainer to create modified copies of the images in the IdenProf dataset to ensure maximum accuracy is achieved.• batch_size: This refers to the number of images the set that the model trainer will study at once, until it has studied all the images in the IdenProf dataset.• Show_network_summary (Optional) : This is to show the structure of the model type you are using to train the artificial intelligence model. Now you can start run the Python file and start the training. When the training starts, you will see results like the one below: =====================================Total params: 23,608,202Trainable params: 23,555,082Non-trainable params: 53,120______________________________________Using Enhanced Data GenerationFound 4000 images belonging to 4 classes.Found 800 images belonging to 4 classes.JSON Mapping for the model classes saved to C:\Users\User\PycharmProjects\FirstTraining\idenprof\json\model_class.jsonNumber of experiments (Epochs) : 200Epoch 1/100 1/280 [>.............................] - ETA: 52s - loss: 2.3026 - acc: 0.25002/280 [>.............................] - ETA: 52s - loss: 2.3026 - acc: 0.25003/280 [>.............................] - ETA: 52s - loss: 2.3026 - acc: 0.2500..............................,..............................,..............................,279/280 [===========================>..] - ETA: 1s - loss: 2.3097 - acc: 0.0625Epoch 00000: saving model to C:\Users\User\PycharmProjects\FirstTraining\idenprof\models\model_ex-000_acc-0.100000.h5280/280 [==============================] - 51s - loss: 2.3095 - acc: 0.0600 - val_loss: 2.3026 - val_acc: 0.1000 Let us explain the details shown above: 1. The statement “JSON Mapping for the model classes saved to C:\Users\User\PycharmProjects\FirstTraining\idenprof\json\model_class.json” means the model trainer has saved a JSON file for the idenprof dataset which you can use to recognize other pictures with the custom image prediction class (explanation available as you read further). 2. The line Epoch 1/200 means the network is performing the first training of the targeted 200 3. The line 1/280 [>.............................] — ETA: 52s — loss: 2.3026 — acc: 0.2500 represents the number of batches that has been trained in the present experiment 4. The line Epoch 00000: saving model to C:\Users\User\PycharmProjects\FirstTraining\idenprof\models\model_ex-000_acc-0.100000.h5 refers to the model saved after the present training. The ex_000 represents the experiment at this stage while the acc0.100000 and valacc: 0.1000 represents the accuracy of the model on the test images after the present experiment (maximum value value of accuracy is 1.0). This result helps to know the best performed model you can use for custom image prediction. Once you are done training your artificial intelligence model, you can use the “CustomImagePrediction” class to perform image prediction with you’re the model that achieved the highest accuracy. Just in case you have not been able to train the artificial intelligence model yourself due to lack of accessing an NVIDIA GPU, for the purpose of this tutorial, we have provided an artificial intelligence model we have trained on the IdenProf dataset which you can use right now to predict new images of any of the 10 professionals that is in the dataset. This model achieved over 79% accuracy after 61 training experiments. Click this link to download the model. Also, if you have not perform the training yourself, also download the JSON file of the idenprof model via this link. Then, you are ready to start recognizing professionals using the trained artificial intelligence model. Just follow the instructions below. Next, create another Python file and give it a name, for example FirstCustomImageRecognition.py . Copy the artificial intelligence model you downloaded above or the one you trained that achieved the highest accuracy and paste it to the folder where your new python file (e.g FirstCustomImageRecognition.py ) . Also copy the JSON file you downloaded or was generated by your training and paste it to the same folder as your new python file. Copy a sample image(s) of any professional that fall into the categories in the IdenProf dataset to the same folder as your new python file. Then copy the code below and put it into your new python file View sample image and result below. waiter : 99.99997615814209chef : 1.568847380895022e-05judge : 1.0255866556008186e-05 That was easy! Now let’s explain the code above that produced this prediction result. The first and second lines of code above imports the ImageAI’s CustomImageClassification class for predicting and recognizing images with trained models and the python os class. The third line of code creates a variable which holds the reference to the path that contains your python file (in this example, your FirstCustomImageRecognition.py) and the ResNet50 model file you downloaded or trained yourself. In the above code, we created an instance of the CustomImageClassification() class in the fourth line, then we set the model type of the prediction object to ResNet50 by calling the .setModelTypeAsResNet50() in the fifth line and then we set the model path of the prediction object to the path of the artificial intelligence model file (idenprof_061–0.7933.h5) we copied to the project folder folder in the sixth line. In the seventh line, we set the path of the JSON file we copied to the folder in the seventh line and loaded the model in the eightieth line. Finally, we ran prediction on the image we copied to the folder and print out the result to the Command Line Interface. So far, you have learnt how to use ImageAI to easily train your own artificial intelligence model that can predict any type of object or set of objects in an image. If you will like to know everything about how image recognition works with links to more useful and practical resources, visit the Image Recognition Guide linked below. www.fritz.ai You can find all the details and documentation use ImageAI for training custom artificial intelligence models, as well as other computer vision features contained in ImageAI on the official GitHub repository. github.com If you find this article helpful and enjoyed it, kindly give it a clap. Also, feel free to share it with friends and colleagues. Do you have any questions, suggestions or will like to reach to me? Send me an email to [email protected] . I am also available on twitter via the handle @OlafenwaMoses and on Facebook via https://www.facebook.com/moses.olafenwa .
[ { "code": null, "e": 460, "s": 172, "text": "In this article, we will briefly introduce the field of artificial intelligence, particularly in computer vision, the challenges involved, the existing modern solutions to these challenges and how you can apply these solutions conveniently and easily without taking much time and effort." }, { "code": null, "e": 1005, "s": 460, "text": "Artificial Intelligence has for decades been a field of research in which both scientists and engineers have been making intense efforts to unravel the mystery of getting machines and computers to perceive and understand our world well enough to act properly and serve humanity. One of the most important aspect of this research work is getting computers to understand visual information (images and videos) generated everyday around us. This field of getting computers to perceive and understand visual information is known as computer vision." }, { "code": null, "e": 1927, "s": 1005, "text": "During the rise of artificial intelligence research in the 1950s to the 1980s, computers were manually given instructions on how to recognize images, objects in images and what features to look out for. This method are traditional algorithms and were called Expert Systems, as they require that humans take the pain of identifying features for each unique scene of object that has to be recognize and representing these features in mathematical models that the computer can understand. That involves a whole lot of tedious work because there are hundreds and thousands of various ways an object can be represented and there are thousands (or even millions) of different scenes and objects that uniquely exist, and therefore finding the optimized and accurate mathematical models to represent all the possible features of each objects or scene, and for all possible objects or scene is more of work that will last forever." }, { "code": null, "e": 2444, "s": 1927, "text": "Then, in the 1990s, the concept of Machine Learning was introduced and it ushered in an era in which instead of telling computers what to look out for in recognizing scenes and objects in images and videos, we can instead design algorithms that will make computers to learn how to recognize scenes and objects in images by itself, just like a child learns to understand his/her environment by exploring. Machine learning opened the way for computers to learn to recognize almost any scene or object we want them too." }, { "code": null, "e": 3109, "s": 2444, "text": "With the emergence of powerful computers such as the NVIDIA GPUs and state-of-the-art Deep Learning algorithms for image recognition such as AlexNet in 2012 by Alex Krizhevsky et al, ResNet in 2015 by Kaeming He et al, SqueezeNet in 2016 by Forrest Landola et al, DenseNet in 2016 by Gao Huang et al, to mention a few, it is possible to put together a number of pictures (more like image books for computers) and define an artificial intelligence model to learn features of scenes and objects in these pictures by itself and use the knowledge gained from the learning process to recognize all other instance of the type of scene or objects it will encounter after." }, { "code": null, "e": 3510, "s": 3109, "text": "To train an artificial intelligence model that can recognize whatever you want it to recognize in pictures, it traditional involves lots of expertise in Applied Mathematics and use of Deep Learning libraries, not to mention the amount of time involved and stress you have to go through to write the code for the algorithm and fit the code to your images. This is where we have provided our solutions." }, { "code": null, "e": 4100, "s": 3510, "text": "Our team at AI Commons has developed a python library that can let you train an artificial intelligence model that can recognize any object you want it to recognize in images using just 5 simple lines of python code. The python library is ImageAI , a library built to let students, developers and researchers with all levels of expertise to build systems and applications with state-of-the-art computer vision capabilities using between 5 to 15 simple lines of code. Now, let us walk you through creating your first artificial intelligence model that can recognize whatever you want it to." }, { "code": null, "e": 4795, "s": 4100, "text": "To train your artificial intelligence model, you need a collection of images called a dataset. A dataset contains hundreds to thousands of sample images of objects you want your artificial intelligence model to recognize. But you don’t have worry! We are not asking you to go and download thousands of pictures right now just to train your artificial intelligence model. For this tutorial, we have provided a dataset called IdenProf. IdenProf (Identifiable Professionals) is a dataset that contains 11,000 pictures of 10 different professionals that humans can see and recognize their jobs by their mode of dressing. The classes of professionals whose pictures are in this dataset are as below:" }, { "code": null, "e": 4802, "s": 4795, "text": "· Chef" }, { "code": null, "e": 4811, "s": 4802, "text": "· Doctor" }, { "code": null, "e": 4822, "s": 4811, "text": "· Engineer" }, { "code": null, "e": 4831, "s": 4822, "text": "· Farmer" }, { "code": null, "e": 4845, "s": 4831, "text": "· Firefighter" }, { "code": null, "e": 4853, "s": 4845, "text": "· Judge" }, { "code": null, "e": 4864, "s": 4853, "text": "· Mechanic" }, { "code": null, "e": 4872, "s": 4864, "text": "· Pilot" }, { "code": null, "e": 4881, "s": 4872, "text": "· Police" }, { "code": null, "e": 4890, "s": 4881, "text": "· Waiter" }, { "code": null, "e": 5613, "s": 4890, "text": "This dataset is split into 9000 (900 pictures for each profession) pictures to train the artificial intelligence model and 2000 (200 pictures for each profession) pictures to test the performance of the artificial intelligence model as it is training. IdenProf has been properly arranged and made ready for training your artificial intelligence model to recognize professionals by their mode of dressing. For reference purposes, if you are using your own image dataset, you must collect at least 500 pictures for each object or scene you want your artificial intelligence model to recognize. To train any image dataset you collect yourself with ImageAI, you must arrange the images in folders as seen in the example below:" }, { "code": null, "e": 6643, "s": 5613, "text": "idenprof//train//chef// 900 images of chefsidenprof//train//doctor// 900 images of doctorsidenprof//train//engineer// 900 images of engineeridenprof//train//farmer// 900 images of farmersidenprof//train//firefighter// 900 images of firefightersidenprof//train//judge// 900 images of judgesidenprof//train//mechanic// 900 images of mechanicsidenprof//train//pilot// 900 images of pilotsidenprof//train//chef// 900 images of chefidenprof//train//police// 900 images of policeidenprof//train//waiter// 900 images of waitersidenprof//test//chef// 200 images of chefsidenprof//test//doctor// 200 images of doctorsidenprof//test//engineer// 200 images of engineeridenprof//test//farmer// 200 images of farmersidenprof//test//firefighter// 200 images of firefightersidenprof//test//judge// 200 images of judgesidenprof//test//mechanic// 200 images of mechanicsidenprof//test//pilot// 200 images of pilotsidenprof//test//chef// 200 images of chefidenprof//test//police// 200 images of policeidenprof//test//waiter// 200 images of waiters" }, { "code": null, "e": 6871, "s": 6643, "text": "Now that you have understand how to prepare own image dataset for training artificial intelligence models, we will now proceed with guiding you training an artificial intelligence model to recognize professionals using ImageAI." }, { "code": null, "e": 7115, "s": 6871, "text": "· First you must download the zip of IdenProf dataset via this link. Also you can view all the details and sample results of artificial intelligence models trained to recognize professions in the IdenProf GitHub repository whose link is below." }, { "code": null, "e": 7157, "s": 7115, "text": "https://github.com/OlafenwaMoses/IdenProf" }, { "code": null, "e": 7473, "s": 7157, "text": "· Because training artificial intelligence models require high performance computer systems, I strongly advice that you ensure your computer/laptop that you want to use for this training has NVIDIA GPU. Alternatively, you can use Google Colab for this experiment has it offers a free NVIDIA K80 GPU for experiments." }, { "code": null, "e": 7530, "s": 7473, "text": "· Then you have to install ImageAI and its dependencies." }, { "code": null, "e": 7559, "s": 7530, "text": "Install Python 3.7.6 and pip" }, { "code": null, "e": 7612, "s": 7559, "text": "(Skip this section if you already have Python 3.7.6)" }, { "code": null, "e": 7627, "s": 7612, "text": "www.python.org" }, { "code": null, "e": 7660, "s": 7627, "text": "Install ImageAI and dependencies" }, { "code": null, "e": 7762, "s": 7660, "text": "(Skip any of the installation instruction in this section if you already have the library installed )" }, { "code": null, "e": 7775, "s": 7762, "text": "- Tensorflow" }, { "code": null, "e": 7805, "s": 7775, "text": "pip install tensorflow==2.4.0" }, { "code": null, "e": 7814, "s": 7805, "text": "- Others" }, { "code": null, "e": 7945, "s": 7814, "text": "pip install keras==2.4.3 numpy==1.19.3 pillow==7.0.0 scipy==1.4.1 h5py==2.10.0 matplotlib==3.3.2 opencv-python keras-resnet==0.2.0" }, { "code": null, "e": 7973, "s": 7945, "text": "Install the ImageAI library" }, { "code": null, "e": 8003, "s": 7973, "text": "pip install imageai --upgrade" }, { "code": null, "e": 8093, "s": 8003, "text": "· Create a python file with any name you want to give it, for example “FirstTraining.py”." }, { "code": null, "e": 8211, "s": 8093, "text": "· Copy the zip of the IdenProf dataset into the folder where your Python file is. Then unzip it into the same folder." }, { "code": null, "e": 8283, "s": 8211, "text": "· Then copy the code below into the python file (e.g FirstTraining.py)." }, { "code": null, "e": 8440, "s": 8283, "text": "That’s it! That’s all the code you need to train your artificial intelligence model. Before you run the code to start the training, let us explain the code." }, { "code": null, "e": 9665, "s": 8440, "text": "In the first line, we imported ImageAI’s model training class. In the second line we, created an instance of the model training class. In the third line, we set the model type to ResNet50 (there are four model types available which are MobileNetv2, ResNet50, InceptionV3 and DenseNet121). In the fourth line, we set the data directory (dataset directory) to the folder of the dataset zip file you unzipped. Then in the fifth line, we call the trainModel function and specified the following values: • number_objects : This refers to the number of different types of professionals in the IdenProf dataset.• num_experiments : This is the number of times the model trainer will study all the images in the idenprof dataset in order to achieve maximum accuracy.• Enhance_data (Optional) : This is to tell the model trainer to create modified copies of the images in the IdenProf dataset to ensure maximum accuracy is achieved.• batch_size: This refers to the number of images the set that the model trainer will study at once, until it has studied all the images in the IdenProf dataset.• Show_network_summary (Optional) : This is to show the structure of the model type you are using to train the artificial intelligence model." }, { "code": null, "e": 9794, "s": 9665, "text": "Now you can start run the Python file and start the training. When the training starts, you will see results like the one below:" }, { "code": null, "e": 10864, "s": 9794, "text": "=====================================Total params: 23,608,202Trainable params: 23,555,082Non-trainable params: 53,120______________________________________Using Enhanced Data GenerationFound 4000 images belonging to 4 classes.Found 800 images belonging to 4 classes.JSON Mapping for the model classes saved to C:\\Users\\User\\PycharmProjects\\FirstTraining\\idenprof\\json\\model_class.jsonNumber of experiments (Epochs) : 200Epoch 1/100 1/280 [>.............................] - ETA: 52s - loss: 2.3026 - acc: 0.25002/280 [>.............................] - ETA: 52s - loss: 2.3026 - acc: 0.25003/280 [>.............................] - ETA: 52s - loss: 2.3026 - acc: 0.2500..............................,..............................,..............................,279/280 [===========================>..] - ETA: 1s - loss: 2.3097 - acc: 0.0625Epoch 00000: saving model to C:\\Users\\User\\PycharmProjects\\FirstTraining\\idenprof\\models\\model_ex-000_acc-0.100000.h5280/280 [==============================] - 51s - loss: 2.3095 - acc: 0.0600 - val_loss: 2.3026 - val_acc: 0.1000" }, { "code": null, "e": 10904, "s": 10864, "text": "Let us explain the details shown above:" }, { "code": null, "e": 11243, "s": 10904, "text": "1. The statement “JSON Mapping for the model classes saved to C:\\Users\\User\\PycharmProjects\\FirstTraining\\idenprof\\json\\model_class.json” means the model trainer has saved a JSON file for the idenprof dataset which you can use to recognize other pictures with the custom image prediction class (explanation available as you read further)." }, { "code": null, "e": 12006, "s": 11243, "text": "2. The line Epoch 1/200 means the network is performing the first training of the targeted 200 3. The line 1/280 [>.............................] — ETA: 52s — loss: 2.3026 — acc: 0.2500 represents the number of batches that has been trained in the present experiment 4. The line Epoch 00000: saving model to C:\\Users\\User\\PycharmProjects\\FirstTraining\\idenprof\\models\\model_ex-000_acc-0.100000.h5 refers to the model saved after the present training. The ex_000 represents the experiment at this stage while the acc0.100000 and valacc: 0.1000 represents the accuracy of the model on the test images after the present experiment (maximum value value of accuracy is 1.0). This result helps to know the best performed model you can use for custom image prediction." }, { "code": null, "e": 12201, "s": 12006, "text": "Once you are done training your artificial intelligence model, you can use the “CustomImagePrediction” class to perform image prediction with you’re the model that achieved the highest accuracy." }, { "code": null, "e": 12924, "s": 12201, "text": "Just in case you have not been able to train the artificial intelligence model yourself due to lack of accessing an NVIDIA GPU, for the purpose of this tutorial, we have provided an artificial intelligence model we have trained on the IdenProf dataset which you can use right now to predict new images of any of the 10 professionals that is in the dataset. This model achieved over 79% accuracy after 61 training experiments. Click this link to download the model. Also, if you have not perform the training yourself, also download the JSON file of the idenprof model via this link. Then, you are ready to start recognizing professionals using the trained artificial intelligence model. Just follow the instructions below." }, { "code": null, "e": 13505, "s": 12924, "text": "Next, create another Python file and give it a name, for example FirstCustomImageRecognition.py . Copy the artificial intelligence model you downloaded above or the one you trained that achieved the highest accuracy and paste it to the folder where your new python file (e.g FirstCustomImageRecognition.py ) . Also copy the JSON file you downloaded or was generated by your training and paste it to the same folder as your new python file. Copy a sample image(s) of any professional that fall into the categories in the IdenProf dataset to the same folder as your new python file." }, { "code": null, "e": 13567, "s": 13505, "text": "Then copy the code below and put it into your new python file" }, { "code": null, "e": 13603, "s": 13567, "text": "View sample image and result below." }, { "code": null, "e": 13694, "s": 13603, "text": "waiter : 99.99997615814209chef : 1.568847380895022e-05judge : 1.0255866556008186e-05" }, { "code": null, "e": 13780, "s": 13694, "text": "That was easy! Now let’s explain the code above that produced this prediction result." }, { "code": null, "e": 14869, "s": 13780, "text": "The first and second lines of code above imports the ImageAI’s CustomImageClassification class for predicting and recognizing images with trained models and the python os class. The third line of code creates a variable which holds the reference to the path that contains your python file (in this example, your FirstCustomImageRecognition.py) and the ResNet50 model file you downloaded or trained yourself. In the above code, we created an instance of the CustomImageClassification() class in the fourth line, then we set the model type of the prediction object to ResNet50 by calling the .setModelTypeAsResNet50() in the fifth line and then we set the model path of the prediction object to the path of the artificial intelligence model file (idenprof_061–0.7933.h5) we copied to the project folder folder in the sixth line. In the seventh line, we set the path of the JSON file we copied to the folder in the seventh line and loaded the model in the eightieth line. Finally, we ran prediction on the image we copied to the folder and print out the result to the Command Line Interface." }, { "code": null, "e": 15034, "s": 14869, "text": "So far, you have learnt how to use ImageAI to easily train your own artificial intelligence model that can predict any type of object or set of objects in an image." }, { "code": null, "e": 15203, "s": 15034, "text": "If you will like to know everything about how image recognition works with links to more useful and practical resources, visit the Image Recognition Guide linked below." }, { "code": null, "e": 15216, "s": 15203, "text": "www.fritz.ai" }, { "code": null, "e": 15425, "s": 15216, "text": "You can find all the details and documentation use ImageAI for training custom artificial intelligence models, as well as other computer vision features contained in ImageAI on the official GitHub repository." }, { "code": null, "e": 15436, "s": 15425, "text": "github.com" }, { "code": null, "e": 15565, "s": 15436, "text": "If you find this article helpful and enjoyed it, kindly give it a clap. Also, feel free to share it with friends and colleagues." } ]
Dynamic Spinner in Kotlin - GeeksforGeeks
28 Mar, 2022 Android Spinner is a view similar to dropdown list which is used to select one option from the list of options. It provides an easy way to select one item from the list of items and it shows a dropdown list of all values when we click on it. Default value of the android spinner will be currently selected value and by using Adapter we can easily bind the items to spinner object.Here, we will create the spinner programmatically in Kotlin file. First we create a new project by following the below steps: Click on File, then New => New Project.After that include the Kotlin support and click on next.Select the minimum SDK as per convenience and click next button.Then select the Empty activity => next => finish. Click on File, then New => New Project. After that include the Kotlin support and click on next. Select the minimum SDK as per convenience and click next button. Then select the Empty activity => next => finish. In this file, we use the TextView widget and also set its attributes. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/linear_layout" android:gravity = "center"> <TextView android:id="@+id/txtView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Select language:" android:textSize = "20dp" /> </LinearLayout> Here, we update the name of the application using the string tag. We also create the list of the items which will be used in the dropdown menu. XML <resources> <string name="app_name">SpinnerInKotlin</string> <string name="selected_item">Selected item:</string> <string-array name="Languages"> <item>Java</item> <item>Kotlin</item> <item>Swift</item> <item>Python</item> <item>Scala</item> <item>Perl</item> </string-array></resources> First, we declare a variable languages to access the strings items from the strings.xmnl file. val languages = resources.getStringArray(R.array.Languages) then, we can create the spinner using val spinner = Spinner(this) spinner.layoutParams = LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) Add the spinner in the linear Layout using val linearLayout = findViewById<LinearLayout>(R.id.linear_layout) //add spinner in linear layout linearLayout?.addView(spinner) Kotlin package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.Viewimport android.view.ViewGroupimport android.widget.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // access the items of the list val languages = resources.getStringArray(R.array.Languages) //create spinner programmatically val spinner = Spinner(this) spinner.layoutParams = LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) val linearLayout = findViewById<LinearLayout>(R.id.linear_layout) //add spinner in linear layout linearLayout?.addView(spinner) if (spinner != null) { val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, languages) spinner.adapter = adapter spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { Toast.makeText(this@MainActivity, getString(R.string.selected_item) + " " + "" + languages[position], Toast.LENGTH_SHORT).show() } override fun onNothingSelected(parent: AdapterView<*>) { // write code to perform some action } } } }} XML <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.geeksforgeeks.myfirstkotlinapp"> <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> ayushpandey3july Kotlin Android Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Android RecyclerView in Kotlin Retrofit with Kotlin Coroutine in Android Android Menus ImageView in Android with Example How to Get Current Location in Android? Kotlin Android Tutorial How to Convert Kotlin Code to Java Code in Android Studio? Kotlin when expression MVP (Model View Presenter) Architecture Pattern in Android with Example ScrollView in Android
[ { "code": null, "e": 23753, "s": 23725, "text": "\n28 Mar, 2022" }, { "code": null, "e": 23995, "s": 23753, "text": "Android Spinner is a view similar to dropdown list which is used to select one option from the list of options. It provides an easy way to select one item from the list of items and it shows a dropdown list of all values when we click on it." }, { "code": null, "e": 24199, "s": 23995, "text": "Default value of the android spinner will be currently selected value and by using Adapter we can easily bind the items to spinner object.Here, we will create the spinner programmatically in Kotlin file." }, { "code": null, "e": 24259, "s": 24199, "text": "First we create a new project by following the below steps:" }, { "code": null, "e": 24468, "s": 24259, "text": "Click on File, then New => New Project.After that include the Kotlin support and click on next.Select the minimum SDK as per convenience and click next button.Then select the Empty activity => next => finish." }, { "code": null, "e": 24508, "s": 24468, "text": "Click on File, then New => New Project." }, { "code": null, "e": 24565, "s": 24508, "text": "After that include the Kotlin support and click on next." }, { "code": null, "e": 24630, "s": 24565, "text": "Select the minimum SDK as per convenience and click next button." }, { "code": null, "e": 24680, "s": 24630, "text": "Then select the Empty activity => next => finish." }, { "code": null, "e": 24750, "s": 24680, "text": "In this file, we use the TextView widget and also set its attributes." }, { "code": null, "e": 24754, "s": 24750, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:orientation=\"vertical\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:id=\"@+id/linear_layout\" android:gravity = \"center\"> <TextView android:id=\"@+id/txtView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Select language:\" android:textSize = \"20dp\" /> </LinearLayout>", "e": 25271, "s": 24754, "text": null }, { "code": null, "e": 25415, "s": 25271, "text": "Here, we update the name of the application using the string tag. We also create the list of the items which will be used in the dropdown menu." }, { "code": null, "e": 25419, "s": 25415, "text": "XML" }, { "code": "<resources> <string name=\"app_name\">SpinnerInKotlin</string> <string name=\"selected_item\">Selected item:</string> <string-array name=\"Languages\"> <item>Java</item> <item>Kotlin</item> <item>Swift</item> <item>Python</item> <item>Scala</item> <item>Perl</item> </string-array></resources>", "e": 25763, "s": 25419, "text": null }, { "code": null, "e": 25858, "s": 25763, "text": "First, we declare a variable languages to access the strings items from the strings.xmnl file." }, { "code": null, "e": 25919, "s": 25858, "text": "val languages = resources.getStringArray(R.array.Languages)\n" }, { "code": null, "e": 25957, "s": 25919, "text": "then, we can create the spinner using" }, { "code": null, "e": 26138, "s": 25957, "text": "val spinner = Spinner(this)\n spinner.layoutParams = LinearLayout.LayoutParams(\n ViewGroup.LayoutParams.WRAP_CONTENT,\n ViewGroup.LayoutParams.WRAP_CONTENT)\n" }, { "code": null, "e": 26181, "s": 26138, "text": "Add the spinner in the linear Layout using" }, { "code": null, "e": 26326, "s": 26181, "text": "val linearLayout = findViewById<LinearLayout>(R.id.linear_layout)\n //add spinner in linear layout\n linearLayout?.addView(spinner)\n" }, { "code": null, "e": 26333, "s": 26326, "text": "Kotlin" }, { "code": "package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.Viewimport android.view.ViewGroupimport android.widget.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // access the items of the list val languages = resources.getStringArray(R.array.Languages) //create spinner programmatically val spinner = Spinner(this) spinner.layoutParams = LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) val linearLayout = findViewById<LinearLayout>(R.id.linear_layout) //add spinner in linear layout linearLayout?.addView(spinner) if (spinner != null) { val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, languages) spinner.adapter = adapter spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { Toast.makeText(this@MainActivity, getString(R.string.selected_item) + \" \" + \"\" + languages[position], Toast.LENGTH_SHORT).show() } override fun onNothingSelected(parent: AdapterView<*>) { // write code to perform some action } } } }}", "e": 28002, "s": 26333, "text": null }, { "code": null, "e": 28006, "s": 28002, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"package=\"com.geeksforgeeks.myfirstkotlinapp\"> <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>", "e": 28661, "s": 28006, "text": null }, { "code": null, "e": 28680, "s": 28663, "text": "ayushpandey3july" }, { "code": null, "e": 28695, "s": 28680, "text": "Kotlin Android" }, { "code": null, "e": 28702, "s": 28695, "text": "Kotlin" }, { "code": null, "e": 28800, "s": 28702, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28809, "s": 28800, "text": "Comments" }, { "code": null, "e": 28822, "s": 28809, "text": "Old Comments" }, { "code": null, "e": 28853, "s": 28822, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 28895, "s": 28853, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 28909, "s": 28895, "text": "Android Menus" }, { "code": null, "e": 28943, "s": 28909, "text": "ImageView in Android with Example" }, { "code": null, "e": 28983, "s": 28943, "text": "How to Get Current Location in Android?" }, { "code": null, "e": 29007, "s": 28983, "text": "Kotlin Android Tutorial" }, { "code": null, "e": 29066, "s": 29007, "text": "How to Convert Kotlin Code to Java Code in Android Studio?" }, { "code": null, "e": 29089, "s": 29066, "text": "Kotlin when expression" }, { "code": null, "e": 29161, "s": 29089, "text": "MVP (Model View Presenter) Architecture Pattern in Android with Example" } ]
Explain attributes and the different types of attributes in DBMS?
Attributes are the properties which describe an entity. Example The attributes of student entity are as follows − Roll number Roll number Name Name Branch Branch Age Age The different types of attributes are as follows − It can be divided into smaller sub parts, each sub part can form an independent attribute. For example − Name FirstName MiddelName LastName Attributes that cannot be further subdivided are called atomic attributes. For example − Phone number PIN code Attributes having a single value for a particular item is called a single valued attribute. For example: Room Number Attribute having a set of values for a single entity is called a multi-valued attribute. For example − e-mail Tel.No Hobbies When one attribute value is derived from the other is called a derived attribute. For example: Age can be derived from date of birth, where, Age is the derived attribute. Age is the derived attribute. DOB is the stored attribute. DOB is the stored attribute. Nesting of composite and multi-valued attributes forms a complex attribute. For example If a person has more than one house and each house has more than one phone. Then, that attribute phone is represented as a complex attribute.
[ { "code": null, "e": 1118, "s": 1062, "text": "Attributes are the properties which describe an entity." }, { "code": null, "e": 1126, "s": 1118, "text": "Example" }, { "code": null, "e": 1176, "s": 1126, "text": "The attributes of student entity are as follows −" }, { "code": null, "e": 1188, "s": 1176, "text": "Roll number" }, { "code": null, "e": 1200, "s": 1188, "text": "Roll number" }, { "code": null, "e": 1205, "s": 1200, "text": "Name" }, { "code": null, "e": 1210, "s": 1205, "text": "Name" }, { "code": null, "e": 1217, "s": 1210, "text": "Branch" }, { "code": null, "e": 1224, "s": 1217, "text": "Branch" }, { "code": null, "e": 1228, "s": 1224, "text": "Age" }, { "code": null, "e": 1232, "s": 1228, "text": "Age" }, { "code": null, "e": 1283, "s": 1232, "text": "The different types of attributes are as follows −" }, { "code": null, "e": 1374, "s": 1283, "text": "It can be divided into smaller sub parts, each sub part can form an independent attribute." }, { "code": null, "e": 1388, "s": 1374, "text": "For example −" }, { "code": null, "e": 1501, "s": 1388, "text": " Name\n FirstName MiddelName LastName" }, { "code": null, "e": 1576, "s": 1501, "text": "Attributes that cannot be further subdivided are called atomic attributes." }, { "code": null, "e": 1590, "s": 1576, "text": "For example −" }, { "code": null, "e": 1660, "s": 1590, "text": " Phone number\n PIN code" }, { "code": null, "e": 1752, "s": 1660, "text": "Attributes having a single value for a particular item is called a single valued attribute." }, { "code": null, "e": 1777, "s": 1752, "text": "For example: Room Number" }, { "code": null, "e": 1866, "s": 1777, "text": "Attribute having a set of values for a single entity is called a multi-valued attribute." }, { "code": null, "e": 1880, "s": 1866, "text": "For example −" }, { "code": null, "e": 1947, "s": 1880, "text": " e-mail\n Tel.No\n Hobbies" }, { "code": null, "e": 2029, "s": 1947, "text": "When one attribute value is derived from the other is called a derived attribute." }, { "code": null, "e": 2088, "s": 2029, "text": "For example: Age can be derived from date of birth, where," }, { "code": null, "e": 2118, "s": 2088, "text": "Age is the derived attribute." }, { "code": null, "e": 2148, "s": 2118, "text": "Age is the derived attribute." }, { "code": null, "e": 2177, "s": 2148, "text": "DOB is the stored attribute." }, { "code": null, "e": 2206, "s": 2177, "text": "DOB is the stored attribute." }, { "code": null, "e": 2282, "s": 2206, "text": "Nesting of composite and multi-valued attributes forms a complex attribute." }, { "code": null, "e": 2294, "s": 2282, "text": "For example" }, { "code": null, "e": 2436, "s": 2294, "text": "If a person has more than one house and each house has more than one phone. Then, that attribute phone is represented as a complex attribute." } ]
Convert characters of a string to opposite case - GeeksforGeeks
16 Mar, 2022 Given a string, convert the characters of the string into opposite case,i.e. if a character is lower case then convert it into upper case and vice-versa. Examples: Input : geeksForgEeks Output : GEEKSfORGeEKS Input : hello every one Output : HELLO EVERY ONE ASCII values of alphabets: A – Z = 65 to 90, a – z = 97 to 122 Steps: Take one string of any length and calculate its length.Scan string character by character and keep checking the index. If a character in an index is in lower case, then subtract 32 to convert it in upper case, else add 32 to convert it in lower casePrint the final string. Take one string of any length and calculate its length. Scan string character by character and keep checking the index. If a character in an index is in lower case, then subtract 32 to convert it in upper case, else add 32 to convert it in lower case If a character in an index is in lower case, then subtract 32 to convert it in upper case, else add 32 to convert it in lower case Print the final string. C++ Java Python3 C# Javascript // CPP program to Convert characters// of a string to opposite case#include <iostream>using namespace std; // Function to convert characters// of a string to opposite casevoid convertOpposite(string& str){ int ln = str.length(); // Conversion according to ASCII values for (int i = 0; i < ln; i++) { if (str[i] >= 'a' && str[i] <= 'z') // Convert lowercase to uppercase str[i] = str[i] - 32; else if (str[i] >= 'A' && str[i] <= 'Z') // Convert uppercase to lowercase str[i] = str[i] + 32; }} // Driver functionint main(){ string str = "GeEkSfOrGeEkS"; // Calling the Function convertOpposite(str); cout << str; return 0;} // Java program to Convert characters// of a string to opposite caseclass Test { // Method to convert characters // of a string to opposite case static void convertOpposite(StringBuffer str) { int ln = str.length(); // Conversion using predefined methods for (int i = 0; i < ln; i++) { Character c = str.charAt(i); if (Character.isLowerCase(c)) str.replace(i, i + 1, Character.toUpperCase(c) + ""); else str.replace(i, i + 1, Character.toLowerCase(c) + ""); } } public static void main(String[] args) { StringBuffer str = new StringBuffer("GeEkSfOrGeEkS"); // Calling the Method convertOpposite(str); System.out.println(str); }}// This code is contributed by Gaurav Miglani # Python3 program to Convert characters# of a string to opposite case # Function to convert characters# of a string to opposite casedef convertOpposite(str): ln = len(str) # Conversion according to ASCII values for i in range(ln): if str[i] >= 'a' and str[i] <= 'z': # Convert lowercase to uppercase str[i] = chr(ord(str[i]) - 32) else if str[i] >= 'A' and str[i] <= 'Z': # Convert lowercase to uppercase str[i] = chr(ord(str[i]) + 32) # Driver codeif __name__ == "__main__": str = "GeEkSfOrGeEkS" str = list(str) # Calling the Function convertOpposite(str) str = ''.join(str) print(str) # This code is contributed by# sanjeev2552 // C# program to Convert characters// of a string to opposite caseusing System;using System.Text; class GFG{ // Method to convert characters // of a string to opposite case static void convertOpposite(StringBuilder str) { int ln = str.Length; // Conversion according to ASCII values for (int i=0; i<ln; i++) { if (str[i]>='a' && str[i]<='z') //Convert lowercase to uppercase str[i] = (char)(str[i] - 32); else if(str[i]>='A' && str[i]<='Z') //Convert uppercase to lowercase str[i] = (char)(str[i] + 32); } } // Driver code public static void Main() { StringBuilder str = new StringBuilder("GeEkSfOrGeEkS"); // Calling the Method convertOpposite(str); Console.WriteLine(str); }}// This code is contributed by PrinciRaj1992 <script> // Function to convert characters// of a string to opposite casefunction convertOpposite(str){ var ln = str.length; // Conversion according to ASCII values for (var i = 0; i < ln; i++) { if (str[i] >= 'a' && str[i] <= 'z') // Convert lowercase to uppercase document.write( String.fromCharCode(str.charCodeAt(i) - 32) ); else if (str[i] >= 'A' && str[i] <= 'Z') // Convert uppercase to lowercase document.write( String.fromCharCode(str.charCodeAt(i) + 32) ); }} // Driver functionvar str = "GeEkSfOrGeEkS"; // Calling the Function convertOpposite(str); </script> gEeKsFoRgEeKs Time Complexity: O(n) Note: This program can alternatively be done using C++ inbuilt functions – Character.toLowerCase(char) and Character.toUpperCase(char). Approach 2: The problem can be solved using letter case toggling. Follow the below steps to solve the problem: Traverse the given string S. For each character Si, do Si = Si ^ (1 << 5). Si ^ (1 << 5) toggles the 5th bit which means 97 will become 65 and 65 will become 97:65 ^ 32 = 9797 ^ 32 = 65 65 ^ 32 = 97 97 ^ 32 = 65 Print the string after all operations Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to toggle all characters#include<bits/stdc++.h>using namespace std; // Function to toggle charactersvoid toggleChars(string &S){ for(auto &it : S){ if(isalpha(it)){ it ^= (1 << 5); } }} // Driver codeint main(){ string S = "GeKf@rGeek$"; toggleChars(S); cout << "String after toggle " << endl; cout << S << endl; return 0;} //Code contributed by koulick_sadhu // Java program to toggle all charactersimport java.util.*; class GFG{ static char []S = "GeKf@rGeek$".toCharArray(); // Function to toggle charactersstatic void toggleChars(){ for(int i = 0; i < S.length; i++) { if (Character.isAlphabetic(S[i])) { S[i] ^= (1 << 5); } }} // Driver codepublic static void main(String[] args){ toggleChars(); System.out.print("String after toggle " + "\n"); System.out.print(String.valueOf(S));}} // This code is contributed by Amit Katiyar # python program for the same approachdef isalpha(input): input_char = ord(input[0]) # CHECKING FOR ALPHABET if((input_char >= 65 and input_char <= 90) or (input_char >= 97 and input_char <= 122)): return True else: return False # Function to toggle charactersdef toggleChars(S): s = "" for it in range(len(S)): if(isalpha(S[it])): s += chr(ord(S[it])^(1<<5)) else: s += S[it] return s # Driver codeS = "GeKf@rGeek$"print(f"String after toggle {toggleChars(S)}") # This code is contributed by shinjanpatra // C# program to toggle all charactersusing System; class GFG{ static char []S = "GeKf@rGeek$".ToCharArray(); // Function to toggle charactersstatic void toggleChars(){ for(int i = 0; i < S.Length; i++) { if (char.IsLetter(S[i])) { S[i] = (char)((int)(S[i]) ^ (1 << 5)); } }} // Driver codepublic static void Main(String[] args){ toggleChars(); Console.Write("String after toggle " + "\n"); Console.Write(String.Join("", S));}} // This code is contributed by Princi Singh <script> function isalpha(input) { var input_char = input.charCodeAt(0); // CHECKING FOR ALPHABET if ( (input_char >= 65 && input_char <= 90) || (input_char >= 97 && input_char <= 122)) { return true; } else { return false; } } // Function to toggle charactersfunction toggleChars(S){var s = ""; for(var it = 0; it < S.length; it++) { if(isalpha(S.charAt(it))) { s += String.fromCharCode(S.charCodeAt(it)^(1<<5)) } else{ s += S.charAt(it); } } return s;} // Driver codevar S = "GeKf@rGeek$";document.write( "String after toggle " +toggleChars(S));</script> // This code is contributed by Akshit Saxena This article is contributed by Rishabh Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. princiraj1992 gfg_sal_gfg sanjeev2552 jakubtrlicik koulick_sadhu akshitsaxenaa09 amit143katiyar princi singh surinderdawra388 shinjanpatra School Programming Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java C++ Classes and Objects Operator Overloading in C++ Constructors in C++ Copy Constructor in C++ Write a program to reverse an array or string Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string C++ Data Types Python program to check if a string is palindrome or not
[ { "code": null, "e": 25186, "s": 25158, "text": "\n16 Mar, 2022" }, { "code": null, "e": 25341, "s": 25186, "text": "Given a string, convert the characters of the string into opposite case,i.e. if a character is lower case then convert it into upper case and vice-versa. " }, { "code": null, "e": 25352, "s": 25341, "text": "Examples: " }, { "code": null, "e": 25447, "s": 25352, "text": "Input : geeksForgEeks\nOutput : GEEKSfORGeEKS\n\nInput : hello every one\nOutput : HELLO EVERY ONE" }, { "code": null, "e": 25519, "s": 25447, "text": "ASCII values of alphabets: A – Z = 65 to 90, a – z = 97 to 122 Steps: " }, { "code": null, "e": 25792, "s": 25519, "text": "Take one string of any length and calculate its length.Scan string character by character and keep checking the index. If a character in an index is in lower case, then subtract 32 to convert it in upper case, else add 32 to convert it in lower casePrint the final string." }, { "code": null, "e": 25848, "s": 25792, "text": "Take one string of any length and calculate its length." }, { "code": null, "e": 26043, "s": 25848, "text": "Scan string character by character and keep checking the index. If a character in an index is in lower case, then subtract 32 to convert it in upper case, else add 32 to convert it in lower case" }, { "code": null, "e": 26174, "s": 26043, "text": "If a character in an index is in lower case, then subtract 32 to convert it in upper case, else add 32 to convert it in lower case" }, { "code": null, "e": 26198, "s": 26174, "text": "Print the final string." }, { "code": null, "e": 26202, "s": 26198, "text": "C++" }, { "code": null, "e": 26207, "s": 26202, "text": "Java" }, { "code": null, "e": 26215, "s": 26207, "text": "Python3" }, { "code": null, "e": 26218, "s": 26215, "text": "C#" }, { "code": null, "e": 26229, "s": 26218, "text": "Javascript" }, { "code": "// CPP program to Convert characters// of a string to opposite case#include <iostream>using namespace std; // Function to convert characters// of a string to opposite casevoid convertOpposite(string& str){ int ln = str.length(); // Conversion according to ASCII values for (int i = 0; i < ln; i++) { if (str[i] >= 'a' && str[i] <= 'z') // Convert lowercase to uppercase str[i] = str[i] - 32; else if (str[i] >= 'A' && str[i] <= 'Z') // Convert uppercase to lowercase str[i] = str[i] + 32; }} // Driver functionint main(){ string str = \"GeEkSfOrGeEkS\"; // Calling the Function convertOpposite(str); cout << str; return 0;}", "e": 26939, "s": 26229, "text": null }, { "code": "// Java program to Convert characters// of a string to opposite caseclass Test { // Method to convert characters // of a string to opposite case static void convertOpposite(StringBuffer str) { int ln = str.length(); // Conversion using predefined methods for (int i = 0; i < ln; i++) { Character c = str.charAt(i); if (Character.isLowerCase(c)) str.replace(i, i + 1, Character.toUpperCase(c) + \"\"); else str.replace(i, i + 1, Character.toLowerCase(c) + \"\"); } } public static void main(String[] args) { StringBuffer str = new StringBuffer(\"GeEkSfOrGeEkS\"); // Calling the Method convertOpposite(str); System.out.println(str); }}// This code is contributed by Gaurav Miglani", "e": 27825, "s": 26939, "text": null }, { "code": "# Python3 program to Convert characters# of a string to opposite case # Function to convert characters# of a string to opposite casedef convertOpposite(str): ln = len(str) # Conversion according to ASCII values for i in range(ln): if str[i] >= 'a' and str[i] <= 'z': # Convert lowercase to uppercase str[i] = chr(ord(str[i]) - 32) else if str[i] >= 'A' and str[i] <= 'Z': # Convert lowercase to uppercase str[i] = chr(ord(str[i]) + 32) # Driver codeif __name__ == \"__main__\": str = \"GeEkSfOrGeEkS\" str = list(str) # Calling the Function convertOpposite(str) str = ''.join(str) print(str) # This code is contributed by# sanjeev2552", "e": 28547, "s": 27825, "text": null }, { "code": "// C# program to Convert characters// of a string to opposite caseusing System;using System.Text; class GFG{ // Method to convert characters // of a string to opposite case static void convertOpposite(StringBuilder str) { int ln = str.Length; // Conversion according to ASCII values for (int i=0; i<ln; i++) { if (str[i]>='a' && str[i]<='z') //Convert lowercase to uppercase str[i] = (char)(str[i] - 32); else if(str[i]>='A' && str[i]<='Z') //Convert uppercase to lowercase str[i] = (char)(str[i] + 32); } } // Driver code public static void Main() { StringBuilder str = new StringBuilder(\"GeEkSfOrGeEkS\"); // Calling the Method convertOpposite(str); Console.WriteLine(str); }}// This code is contributed by PrinciRaj1992", "e": 29511, "s": 28547, "text": null }, { "code": "<script> // Function to convert characters// of a string to opposite casefunction convertOpposite(str){ var ln = str.length; // Conversion according to ASCII values for (var i = 0; i < ln; i++) { if (str[i] >= 'a' && str[i] <= 'z') // Convert lowercase to uppercase document.write( String.fromCharCode(str.charCodeAt(i) - 32) ); else if (str[i] >= 'A' && str[i] <= 'Z') // Convert uppercase to lowercase document.write( String.fromCharCode(str.charCodeAt(i) + 32) ); }} // Driver functionvar str = \"GeEkSfOrGeEkS\"; // Calling the Function convertOpposite(str); </script>", "e": 30207, "s": 29511, "text": null }, { "code": null, "e": 30221, "s": 30207, "text": "gEeKsFoRgEeKs" }, { "code": null, "e": 30380, "s": 30221, "text": "Time Complexity: O(n) Note: This program can alternatively be done using C++ inbuilt functions – Character.toLowerCase(char) and Character.toUpperCase(char). " }, { "code": null, "e": 30491, "s": 30380, "text": "Approach 2: The problem can be solved using letter case toggling. Follow the below steps to solve the problem:" }, { "code": null, "e": 30520, "s": 30491, "text": "Traverse the given string S." }, { "code": null, "e": 30567, "s": 30520, "text": "For each character Si, do Si = Si ^ (1 << 5)." }, { "code": null, "e": 30679, "s": 30567, "text": "Si ^ (1 << 5) toggles the 5th bit which means 97 will become 65 and 65 will become 97:65 ^ 32 = 9797 ^ 32 = 65 " }, { "code": null, "e": 30692, "s": 30679, "text": "65 ^ 32 = 97" }, { "code": null, "e": 30706, "s": 30692, "text": "97 ^ 32 = 65 " }, { "code": null, "e": 30744, "s": 30706, "text": "Print the string after all operations" }, { "code": null, "e": 30795, "s": 30744, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 30799, "s": 30795, "text": "C++" }, { "code": null, "e": 30804, "s": 30799, "text": "Java" }, { "code": null, "e": 30812, "s": 30804, "text": "Python3" }, { "code": null, "e": 30815, "s": 30812, "text": "C#" }, { "code": null, "e": 30826, "s": 30815, "text": "Javascript" }, { "code": "// C++ program to toggle all characters#include<bits/stdc++.h>using namespace std; // Function to toggle charactersvoid toggleChars(string &S){ for(auto &it : S){ if(isalpha(it)){ it ^= (1 << 5); } }} // Driver codeint main(){ string S = \"GeKf@rGeek$\"; toggleChars(S); cout << \"String after toggle \" << endl; cout << S << endl; return 0;} //Code contributed by koulick_sadhu", "e": 31244, "s": 30826, "text": null }, { "code": "// Java program to toggle all charactersimport java.util.*; class GFG{ static char []S = \"GeKf@rGeek$\".toCharArray(); // Function to toggle charactersstatic void toggleChars(){ for(int i = 0; i < S.length; i++) { if (Character.isAlphabetic(S[i])) { S[i] ^= (1 << 5); } }} // Driver codepublic static void main(String[] args){ toggleChars(); System.out.print(\"String after toggle \" + \"\\n\"); System.out.print(String.valueOf(S));}} // This code is contributed by Amit Katiyar", "e": 31772, "s": 31244, "text": null }, { "code": "# python program for the same approachdef isalpha(input): input_char = ord(input[0]) # CHECKING FOR ALPHABET if((input_char >= 65 and input_char <= 90) or (input_char >= 97 and input_char <= 122)): return True else: return False # Function to toggle charactersdef toggleChars(S): s = \"\" for it in range(len(S)): if(isalpha(S[it])): s += chr(ord(S[it])^(1<<5)) else: s += S[it] return s # Driver codeS = \"GeKf@rGeek$\"print(f\"String after toggle {toggleChars(S)}\") # This code is contributed by shinjanpatra", "e": 32375, "s": 31772, "text": null }, { "code": "// C# program to toggle all charactersusing System; class GFG{ static char []S = \"GeKf@rGeek$\".ToCharArray(); // Function to toggle charactersstatic void toggleChars(){ for(int i = 0; i < S.Length; i++) { if (char.IsLetter(S[i])) { S[i] = (char)((int)(S[i]) ^ (1 << 5)); } }} // Driver codepublic static void Main(String[] args){ toggleChars(); Console.Write(\"String after toggle \" + \"\\n\"); Console.Write(String.Join(\"\", S));}} // This code is contributed by Princi Singh", "e": 32902, "s": 32375, "text": null }, { "code": "<script> function isalpha(input) { var input_char = input.charCodeAt(0); // CHECKING FOR ALPHABET if ( (input_char >= 65 && input_char <= 90) || (input_char >= 97 && input_char <= 122)) { return true; } else { return false; } } // Function to toggle charactersfunction toggleChars(S){var s = \"\"; for(var it = 0; it < S.length; it++) { if(isalpha(S.charAt(it))) { s += String.fromCharCode(S.charCodeAt(it)^(1<<5)) } else{ s += S.charAt(it); } } return s;} // Driver codevar S = \"GeKf@rGeek$\";document.write( \"String after toggle \" +toggleChars(S));</script> // This code is contributed by Akshit Saxena", "e": 33686, "s": 32902, "text": null }, { "code": null, "e": 34106, "s": 33686, "text": "This article is contributed by Rishabh Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 34120, "s": 34106, "text": "princiraj1992" }, { "code": null, "e": 34132, "s": 34120, "text": "gfg_sal_gfg" }, { "code": null, "e": 34144, "s": 34132, "text": "sanjeev2552" }, { "code": null, "e": 34157, "s": 34144, "text": "jakubtrlicik" }, { "code": null, "e": 34171, "s": 34157, "text": "koulick_sadhu" }, { "code": null, "e": 34187, "s": 34171, "text": "akshitsaxenaa09" }, { "code": null, "e": 34202, "s": 34187, "text": "amit143katiyar" }, { "code": null, "e": 34215, "s": 34202, "text": "princi singh" }, { "code": null, "e": 34232, "s": 34215, "text": "surinderdawra388" }, { "code": null, "e": 34245, "s": 34232, "text": "shinjanpatra" }, { "code": null, "e": 34264, "s": 34245, "text": "School Programming" }, { "code": null, "e": 34272, "s": 34264, "text": "Strings" }, { "code": null, "e": 34280, "s": 34272, "text": "Strings" }, { "code": null, "e": 34378, "s": 34280, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34397, "s": 34378, "text": "Interfaces in Java" }, { "code": null, "e": 34421, "s": 34397, "text": "C++ Classes and Objects" }, { "code": null, "e": 34449, "s": 34421, "text": "Operator Overloading in C++" }, { "code": null, "e": 34469, "s": 34449, "text": "Constructors in C++" }, { "code": null, "e": 34493, "s": 34469, "text": "Copy Constructor in C++" }, { "code": null, "e": 34539, "s": 34493, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 34573, "s": 34539, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 34633, "s": 34573, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 34648, "s": 34633, "text": "C++ Data Types" } ]
Creating a Pandas Series from Lists - GeeksforGeeks
06 Jan, 2019 A Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.). It has to be remembered that unlike Python lists, a Series will always contain data of the same type. Let’s see how to create a Pandas Series from lists. Method #1 : Using Series() method without any argument. # import pandas as pdimport pandas as pd # create Pandas Series with default index values# default index ranges is from 0 to len(list) - 1x = pd.Series(['Geeks', 'for', 'Geeks']) # print the Seriesprint(x) Output : Method #2 : Using Series() method with 'index' argument. # import pandas lib. as pdimport pandas as pd # create Pandas Series with define indexesx = pd.Series([10, 20, 30, 40, 50], index =['a', 'b', 'c', 'd', 'e']) # print the Seriesprint(x) Output : Another example: # import pandas lib. as pdimport pandas as pd ind = [10, 20, 30, 40, 50, 60, 70] lst = ['Geeks', 'for', 'Geeks', 'is', 'portal', 'for', 'geeks'] # create Pandas Series with define indexesx = pd.Series(lst, index = ind) # print the Seriesprint(x) Output: Method #3: Using Series() method with multi-list # importing pandas import pandas as pd # multi-listlist = [ ['Geeks'], ['For'], ['Geeks'], ['is'], ['a'], ['portal'], ['for'], ['geeks'] ] # create Pandas Seriesdf = pd.Series((i[0] for i in list)) print(df) Output: pandas-series-program Picked Python pandas-series Python-pandas Technical Scripter 2018 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Create a Pandas DataFrame from Lists Reading and Writing to text files in Python *args and **kwargs in Python sum() function in Python
[ { "code": null, "e": 24844, "s": 24816, "text": "\n06 Jan, 2019" }, { "code": null, "e": 25090, "s": 24844, "text": "A Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.). It has to be remembered that unlike Python lists, a Series will always contain data of the same type." }, { "code": null, "e": 25142, "s": 25090, "text": "Let’s see how to create a Pandas Series from lists." }, { "code": null, "e": 25198, "s": 25142, "text": "Method #1 : Using Series() method without any argument." }, { "code": "# import pandas as pdimport pandas as pd # create Pandas Series with default index values# default index ranges is from 0 to len(list) - 1x = pd.Series(['Geeks', 'for', 'Geeks']) # print the Seriesprint(x)", "e": 25406, "s": 25198, "text": null }, { "code": null, "e": 25472, "s": 25406, "text": "Output : Method #2 : Using Series() method with 'index' argument." }, { "code": "# import pandas lib. as pdimport pandas as pd # create Pandas Series with define indexesx = pd.Series([10, 20, 30, 40, 50], index =['a', 'b', 'c', 'd', 'e']) # print the Seriesprint(x)", "e": 25659, "s": 25472, "text": null }, { "code": null, "e": 25668, "s": 25659, "text": "Output :" }, { "code": null, "e": 25685, "s": 25668, "text": "Another example:" }, { "code": "# import pandas lib. as pdimport pandas as pd ind = [10, 20, 30, 40, 50, 60, 70] lst = ['Geeks', 'for', 'Geeks', 'is', 'portal', 'for', 'geeks'] # create Pandas Series with define indexesx = pd.Series(lst, index = ind) # print the Seriesprint(x)", "e": 25958, "s": 25685, "text": null }, { "code": null, "e": 25966, "s": 25958, "text": "Output:" }, { "code": null, "e": 26015, "s": 25966, "text": "Method #3: Using Series() method with multi-list" }, { "code": "# importing pandas import pandas as pd # multi-listlist = [ ['Geeks'], ['For'], ['Geeks'], ['is'], ['a'], ['portal'], ['for'], ['geeks'] ] # create Pandas Seriesdf = pd.Series((i[0] for i in list)) print(df)", "e": 26243, "s": 26015, "text": null }, { "code": null, "e": 26251, "s": 26243, "text": "Output:" }, { "code": null, "e": 26273, "s": 26251, "text": "pandas-series-program" }, { "code": null, "e": 26280, "s": 26273, "text": "Picked" }, { "code": null, "e": 26301, "s": 26280, "text": "Python pandas-series" }, { "code": null, "e": 26315, "s": 26301, "text": "Python-pandas" }, { "code": null, "e": 26339, "s": 26315, "text": "Technical Scripter 2018" }, { "code": null, "e": 26346, "s": 26339, "text": "Python" }, { "code": null, "e": 26365, "s": 26346, "text": "Technical Scripter" }, { "code": null, "e": 26463, "s": 26365, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26481, "s": 26463, "text": "Python Dictionary" }, { "code": null, "e": 26516, "s": 26481, "text": "Read a file line by line in Python" }, { "code": null, "e": 26538, "s": 26516, "text": "Enumerate() in Python" }, { "code": null, "e": 26570, "s": 26538, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26600, "s": 26570, "text": "Iterate over a list in Python" }, { "code": null, "e": 26642, "s": 26600, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26679, "s": 26642, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26723, "s": 26679, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26752, "s": 26723, "text": "*args and **kwargs in Python" } ]
Query a nested field within an array with MongoDB
To query a nested field within an array, use $elemMatch in MongoDB. Let us create a collection with documents − > db.demo153.insertOne({"ClientDetails":[{"ClientName":"Chris","ClientProject":"Online Banking System"},{"ClientName":"David","ClientProject":"Online School Management"}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e351957fdf09dd6d08539df") } > db.demo153.insertOne({"ClientDetails":[{"ClientName":"Carol","ClientProject":"Online Book System"},{"ClientName":"Mike","ClientProject":"Game Development"}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e3519c9fdf09dd6d08539e0") } Display all documents from a collection with the help of find() method − > db.demo153.find(); This will produce the following output − { "_id" : ObjectId("5e351957fdf09dd6d08539df"), "ClientDetails" : [ { "ClientName" : "Chris", "ClientProject" : "Online Banking System" }, { "ClientName" : "David", "ClientProject" : "Online School Management" } ] } { "_id" : ObjectId("5e3519c9fdf09dd6d08539e0"), "ClientDetails" : [ { "ClientName" : "Carol", "ClientProject" : "Online Book System" }, { "ClientName" : "Mike", "ClientProject" : "Game Development" } ] } Following is how to query a nested field within an array − > db.demo153.find({"ClientDetails": { "$elemMatch" : {"ClientProject": { "$in": ["Online Banking System"] } } } }); This will produce the following output − { "_id" : ObjectId("5e351957fdf09dd6d08539df"), "ClientDetails" : [ { "ClientName" : "Chris", "ClientProject" : "Online Banking System" }, { "ClientName" : "David", "ClientProject" : "Online School Management" } ] }
[ { "code": null, "e": 1174, "s": 1062, "text": "To query a nested field within an array, use $elemMatch in MongoDB. Let us create a collection with documents −" }, { "code": null, "e": 1680, "s": 1174, "text": "> db.demo153.insertOne({\"ClientDetails\":[{\"ClientName\":\"Chris\",\"ClientProject\":\"Online Banking System\"},{\"ClientName\":\"David\",\"ClientProject\":\"Online School Management\"}]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e351957fdf09dd6d08539df\")\n}\n> db.demo153.insertOne({\"ClientDetails\":[{\"ClientName\":\"Carol\",\"ClientProject\":\"Online Book System\"},{\"ClientName\":\"Mike\",\"ClientProject\":\"Game Development\"}]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e3519c9fdf09dd6d08539e0\")\n}" }, { "code": null, "e": 1753, "s": 1680, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1774, "s": 1753, "text": "> db.demo153.find();" }, { "code": null, "e": 1815, "s": 1774, "text": "This will produce the following output −" }, { "code": null, "e": 2271, "s": 1815, "text": "{\n \"_id\" : ObjectId(\"5e351957fdf09dd6d08539df\"), \"ClientDetails\" : [\n { \"ClientName\" : \"Chris\", \"ClientProject\" : \"Online Banking System\" },\n { \"ClientName\" : \"David\", \"ClientProject\" : \"Online School Management\" }\n ]\n}\n{\n \"_id\" : ObjectId(\"5e3519c9fdf09dd6d08539e0\"), \"ClientDetails\" : [\n { \"ClientName\" : \"Carol\", \"ClientProject\" : \"Online Book System\" },\n { \"ClientName\" : \"Mike\", \"ClientProject\" : \"Game Development\" }\n ]\n}" }, { "code": null, "e": 2330, "s": 2271, "text": "Following is how to query a nested field within an array −" }, { "code": null, "e": 2446, "s": 2330, "text": "> db.demo153.find({\"ClientDetails\": { \"$elemMatch\" : {\"ClientProject\": { \"$in\": [\"Online Banking System\"] } } } });" }, { "code": null, "e": 2487, "s": 2446, "text": "This will produce the following output −" }, { "code": null, "e": 2703, "s": 2487, "text": "{ \"_id\" : ObjectId(\"5e351957fdf09dd6d08539df\"), \"ClientDetails\" : [ { \"ClientName\" : \"Chris\", \"ClientProject\" : \"Online Banking System\" }, { \"ClientName\" : \"David\", \"ClientProject\" : \"Online School Management\" } ] }" } ]
Ext.js - Class System
Ext JS is a JavaScript framework having functionalities of object oriented programming. Ext is the namespace, which encapsulates all the classes in Ext JS. Ext provides more than 300 classes, which we can use for various functionalities. Ext.define() is used for defining the classes in Ext JS. Ext.define(class name, class members/properties, callback function); Class name is the name of the class according to app structure. For example, appName.folderName.ClassName studentApp.view.StudentView. Class properties/members defines the behavior of class. Callback function is optional. It is called when the class has loaded properly. Ext.define(studentApp.view.StudentDeatilsGrid, { extend : 'Ext.grid.GridPanel', id : 'studentsDetailsGrid', store : 'StudentsDetailsGridStore', renderTo : 'studentsDetailsRenderDiv', layout : 'fit', columns : [{ text : 'Student Name', dataIndex : 'studentName' },{ text : 'ID', dataIndex : 'studentId' },{ text : 'Department', dataIndex : 'department' }] }); As like other OOPS based languages, we can create objects in Ext JS as well. Following are the different ways of creating objects in Ext JS. var studentObject = new student(); studentObject.getStudentName(); Ext.create('Ext.Panel', { renderTo : 'helloWorldPanel', height : 100, width : 100, title : 'Hello world', html : 'First Ext JS Hello World Program' }); Inheritance is the principle of using functionality defined in class A into class B. In Ext JS, inheritance can be done using two methods − Ext.define(studentApp.view.StudentDetailsGrid, { extend : 'Ext.grid.GridPanel', ... }); Here, our custom class StudentDetailsGrid is using the basic features of Ext JS class GridPanel. Mixins is a different way of using class A in class B without extend. mixins : { commons : 'DepartmentApp.utils.DepartmentUtils' }, Mixins are added in the controller where we declare all the other classes such as store, view, etc. In this way, we can call DepartmentUtils class and use its functions in the controller or in this application. Print Add Notes Bookmark this page
[ { "code": null, "e": 2179, "s": 2023, "text": "Ext JS is a JavaScript framework having functionalities of object oriented programming. Ext is the namespace, which encapsulates all the classes in Ext JS." }, { "code": null, "e": 2261, "s": 2179, "text": "Ext provides more than 300 classes, which we can use for various functionalities." }, { "code": null, "e": 2318, "s": 2261, "text": "Ext.define() is used for defining the classes in Ext JS." }, { "code": null, "e": 2388, "s": 2318, "text": "Ext.define(class name, class members/properties, callback function);\n" }, { "code": null, "e": 2524, "s": 2388, "text": "Class name is the name of the class according to app structure. For example, appName.folderName.ClassName studentApp.view.StudentView." }, { "code": null, "e": 2580, "s": 2524, "text": "Class properties/members defines the behavior of class." }, { "code": null, "e": 2660, "s": 2580, "text": "Callback function is optional. It is called when the class has loaded properly." }, { "code": null, "e": 3086, "s": 2660, "text": "Ext.define(studentApp.view.StudentDeatilsGrid, {\n extend : 'Ext.grid.GridPanel',\n id : 'studentsDetailsGrid',\n store : 'StudentsDetailsGridStore',\n renderTo : 'studentsDetailsRenderDiv',\n layout : 'fit',\n \n columns : [{\n text : 'Student Name',\n dataIndex : 'studentName'\n },{\n text : 'ID',\n dataIndex : 'studentId'\n },{\n text : 'Department',\n dataIndex : 'department'\n }]\n});" }, { "code": null, "e": 3163, "s": 3086, "text": "As like other OOPS based languages, we can create objects in Ext JS as well." }, { "code": null, "e": 3227, "s": 3163, "text": "Following are the different ways of creating objects in Ext JS." }, { "code": null, "e": 3295, "s": 3227, "text": "var studentObject = new student();\nstudentObject.getStudentName();\n" }, { "code": null, "e": 3465, "s": 3295, "text": "Ext.create('Ext.Panel', {\n renderTo : 'helloWorldPanel',\n height : 100,\n width : 100,\n title : 'Hello world',\n html : \t'First Ext JS Hello World Program'\t\t\n});" }, { "code": null, "e": 3550, "s": 3465, "text": "Inheritance is the principle of using functionality defined in class A into class B." }, { "code": null, "e": 3605, "s": 3550, "text": "In Ext JS, inheritance can be done using two methods −" }, { "code": null, "e": 3699, "s": 3605, "text": "Ext.define(studentApp.view.StudentDetailsGrid, {\n extend : 'Ext.grid.GridPanel',\n ...\n});" }, { "code": null, "e": 3796, "s": 3699, "text": "Here, our custom class StudentDetailsGrid is using the basic features of Ext JS class GridPanel." }, { "code": null, "e": 3866, "s": 3796, "text": "Mixins is a different way of using class A in class B without extend." }, { "code": null, "e": 3931, "s": 3866, "text": "mixins : {\n commons : 'DepartmentApp.utils.DepartmentUtils'\n}," }, { "code": null, "e": 4142, "s": 3931, "text": "Mixins are added in the controller where we declare all the other classes such as store, view, etc. In this way, we can call DepartmentUtils class and use its functions in the controller or in this application." }, { "code": null, "e": 4149, "s": 4142, "text": " Print" }, { "code": null, "e": 4160, "s": 4149, "text": " Add Notes" } ]
Network Visualizations with GRANDstack | by Tomaz Bratanic | Towards Data Science
Throughout the years, I have worked on a couple of Neo4j projects. Almost all the projects have in common that there was a need to develop a custom network visualization tool that would allow end-users to explore the graph without having to learn any Cypher query language syntax. This blog post will present a simple network visualization tool I have developed that lets you visualize and explore the Harry Potter universe. The visualization application is built using the GRANDstack. All the code is available on GitHub. The GRANDstack consists of four components: Neo4j database: Native graph database to store network data GraphQL: Data query and manipulation language for APIs Apollo: A suite of tools that work together to create GraphQL dataflows. React: A JavaScript library for building component based reusable user interfaces Neo4j is a native graph database suitable for storing, manipulating, and querying network data. If you are a complete Neo4j beginner and want to learn more, I suggest you look at the Neo4j introduction page. The Harry Potter network data comes from a blog post I did a while back where I used NLP to extract connections between characters in the Harry Potter and the Philosopher’s Stone book. The graph schema model is as follows: In the center of our graph are the book’s characters. Some of the characters belong to a Hogwarts house like Gryffindor or Slytherin. Characters are also loyal to various groups. For example, Hermione Granger is devoted to the Society for the Promotion of Elfish Welfare. The network also contains information about the family relationships between characters. Lastly, the interactions between characters are stored in the database as well. Here is a sample subgraph visualization around Harry Potter: I have added both the dataset files as well as instructions on how to load the data into Neo4j in the GitHub repository. GraphQL was initially developed by Facebook and later publicly released in 2015. GraphQL is a query language and server-side runtime for APIs that prioritizes giving clients precisely the data they request. A GraphQL service is created by defining types and fields on those types and then providing functions for each field. Neo4j has developed a GraphQL library that enables rapid development of a GraphQL server that interacts with a Neo4j database. In addition, the library automatically provides the functions needed to retrieve the types and fields defined in the GraphQL schema. Of course, you can always provide a custom resolver for any field if you want. Here, I have defined two types in the schema. The type name must be identical to the node label in Neo4j. Neo4j GraphQL library offers full CRUD support by default. In our network visualization tool, we will only be reading the data from Neo4j and never updating the database. As we don’t need the full CRUD support, we can exclude the create, update, and delete mutations from being generated. You can include the properties of the nodes that should be available via the GraphQL endpoint the fields of a type. For example, we could retrieve information about House or Group nodes in the client using these two schema types. A sample GraphQL query to retrieve information about House nodes is: query house { houses { name }} And the result of this query is: { "data": { "houses": [ { "name": "Gryffindor"}, { "name": "Slytherin"}, { "name": "Hufflepuff"}, { "name": "Ravenclaw"}] }} Well, that was easy! You don’t even need to know any Cypher query language for basic CRUD operations. Neo4j GraphQL library also offers support for pagination, sorting, and filtering queries out of the box. Read more about it in the documentation. Next, we can construct a schema type for a character. The character type is a bit more complex. Here, we have introduced the @relationship directive. If you remember the graph schema, a character can belong to a house or be loyal to a group. To retrieve the information about the character’s house, we have to traverse the BELONGS_TO relationship. In the @relationshipdirective, you specify the type of relationship to be traversed and its direction. The direction of the relationship can either be outgoing or incoming. Our application includes an autocomplete feature. We will use Neo4j’s Full-text search feature to achieve an autocomplete functionality on the frontend. You can define custom GraphQL queries under the Query type. This is most of the code we needed to generate for our GraphQL server to interact with Neo4j. I have also added the interaction type, but it is pretty basic and doesn’t introduce additional functionalities, so I skipped it here. Now that we have our database and GraphQL server ready, we can go ahead and develop the frontend. I have used the vis-react for network visualizations. I have chosen it because it exposes both the node/edge datasets and the network object. We need the node/edge datasets to create dynamic network visualizations, while the network object is used to add interactivity. Apollo client library provides two React hooks for retrieving data from the GraphQL endpoint. The first is the useQuery hook. When a react component mounts and renders, the Apollo Client automatically executed a specified query. You can define the useQuery hook as follows: First, you need to define the GraphQL query. Here, I specified I want to retrieve all characters that have the PageRank value greater than 0,16. In addition, I am only interested in the name, pagerank, and community fields, so I can specify the query to retrieve only those fields. Next, you can define the Reach Hook by using the useQuery functionality. Finally, the fetched data is combined with the interaction information and then input into the vis-react library to produce the following network visualization. The second React hook provided by the Apollo Client library is the useLazyQuery . The useLazyQuery hook is designed for running queries in response to other events. For example, you can execute a query by clicking on the button or, in our case, by selecting a character from a selecting a node in the visualization to populate the popup. The character’s data is then available in the function return under the characterData alias. Notice that I have used the where predicate in my GraphQL query to fetch the data of a specific character. I have used the react-modal library to generate popups, so the code looks like the following: Sometimes you want to be able to access the GraphQL return within the function. In our example application, we need to return the autocomplete options to the input component from the function. To achieve this, you can access Apollo Client and wait for the query to finish with an async function. By combining the auto-complete, popup, and other queries I have created the following network exploration component: Hopefully, this blog post will help you get started with the GRANDstack and network exploration and visualizations. If you have any ideas how to improve this application please let me know in GH issues or create a Pull Request. As always, the code is available on GitHub.
[ { "code": null, "e": 695, "s": 172, "text": "Throughout the years, I have worked on a couple of Neo4j projects. Almost all the projects have in common that there was a need to develop a custom network visualization tool that would allow end-users to explore the graph without having to learn any Cypher query language syntax. This blog post will present a simple network visualization tool I have developed that lets you visualize and explore the Harry Potter universe. The visualization application is built using the GRANDstack. All the code is available on GitHub." }, { "code": null, "e": 739, "s": 695, "text": "The GRANDstack consists of four components:" }, { "code": null, "e": 799, "s": 739, "text": "Neo4j database: Native graph database to store network data" }, { "code": null, "e": 854, "s": 799, "text": "GraphQL: Data query and manipulation language for APIs" }, { "code": null, "e": 927, "s": 854, "text": "Apollo: A suite of tools that work together to create GraphQL dataflows." }, { "code": null, "e": 1009, "s": 927, "text": "React: A JavaScript library for building component based reusable user interfaces" }, { "code": null, "e": 1217, "s": 1009, "text": "Neo4j is a native graph database suitable for storing, manipulating, and querying network data. If you are a complete Neo4j beginner and want to learn more, I suggest you look at the Neo4j introduction page." }, { "code": null, "e": 1440, "s": 1217, "text": "The Harry Potter network data comes from a blog post I did a while back where I used NLP to extract connections between characters in the Harry Potter and the Philosopher’s Stone book. The graph schema model is as follows:" }, { "code": null, "e": 1942, "s": 1440, "text": "In the center of our graph are the book’s characters. Some of the characters belong to a Hogwarts house like Gryffindor or Slytherin. Characters are also loyal to various groups. For example, Hermione Granger is devoted to the Society for the Promotion of Elfish Welfare. The network also contains information about the family relationships between characters. Lastly, the interactions between characters are stored in the database as well. Here is a sample subgraph visualization around Harry Potter:" }, { "code": null, "e": 2063, "s": 1942, "text": "I have added both the dataset files as well as instructions on how to load the data into Neo4j in the GitHub repository." }, { "code": null, "e": 2727, "s": 2063, "text": "GraphQL was initially developed by Facebook and later publicly released in 2015. GraphQL is a query language and server-side runtime for APIs that prioritizes giving clients precisely the data they request. A GraphQL service is created by defining types and fields on those types and then providing functions for each field. Neo4j has developed a GraphQL library that enables rapid development of a GraphQL server that interacts with a Neo4j database. In addition, the library automatically provides the functions needed to retrieve the types and fields defined in the GraphQL schema. Of course, you can always provide a custom resolver for any field if you want." }, { "code": null, "e": 3238, "s": 2727, "text": "Here, I have defined two types in the schema. The type name must be identical to the node label in Neo4j. Neo4j GraphQL library offers full CRUD support by default. In our network visualization tool, we will only be reading the data from Neo4j and never updating the database. As we don’t need the full CRUD support, we can exclude the create, update, and delete mutations from being generated. You can include the properties of the nodes that should be available via the GraphQL endpoint the fields of a type." }, { "code": null, "e": 3421, "s": 3238, "text": "For example, we could retrieve information about House or Group nodes in the client using these two schema types. A sample GraphQL query to retrieve information about House nodes is:" }, { "code": null, "e": 3460, "s": 3421, "text": "query house { houses { name }}" }, { "code": null, "e": 3493, "s": 3460, "text": "And the result of this query is:" }, { "code": null, "e": 3629, "s": 3493, "text": "{ \"data\": { \"houses\": [ { \"name\": \"Gryffindor\"}, { \"name\": \"Slytherin\"}, { \"name\": \"Hufflepuff\"}, { \"name\": \"Ravenclaw\"}] }}" }, { "code": null, "e": 3931, "s": 3629, "text": "Well, that was easy! You don’t even need to know any Cypher query language for basic CRUD operations. Neo4j GraphQL library also offers support for pagination, sorting, and filtering queries out of the box. Read more about it in the documentation. Next, we can construct a schema type for a character." }, { "code": null, "e": 4398, "s": 3931, "text": "The character type is a bit more complex. Here, we have introduced the @relationship directive. If you remember the graph schema, a character can belong to a house or be loyal to a group. To retrieve the information about the character’s house, we have to traverse the BELONGS_TO relationship. In the @relationshipdirective, you specify the type of relationship to be traversed and its direction. The direction of the relationship can either be outgoing or incoming." }, { "code": null, "e": 4611, "s": 4398, "text": "Our application includes an autocomplete feature. We will use Neo4j’s Full-text search feature to achieve an autocomplete functionality on the frontend. You can define custom GraphQL queries under the Query type." }, { "code": null, "e": 4840, "s": 4611, "text": "This is most of the code we needed to generate for our GraphQL server to interact with Neo4j. I have also added the interaction type, but it is pretty basic and doesn’t introduce additional functionalities, so I skipped it here." }, { "code": null, "e": 5208, "s": 4840, "text": "Now that we have our database and GraphQL server ready, we can go ahead and develop the frontend. I have used the vis-react for network visualizations. I have chosen it because it exposes both the node/edge datasets and the network object. We need the node/edge datasets to create dynamic network visualizations, while the network object is used to add interactivity." }, { "code": null, "e": 5482, "s": 5208, "text": "Apollo client library provides two React hooks for retrieving data from the GraphQL endpoint. The first is the useQuery hook. When a react component mounts and renders, the Apollo Client automatically executed a specified query. You can define the useQuery hook as follows:" }, { "code": null, "e": 5998, "s": 5482, "text": "First, you need to define the GraphQL query. Here, I specified I want to retrieve all characters that have the PageRank value greater than 0,16. In addition, I am only interested in the name, pagerank, and community fields, so I can specify the query to retrieve only those fields. Next, you can define the Reach Hook by using the useQuery functionality. Finally, the fetched data is combined with the interaction information and then input into the vis-react library to produce the following network visualization." }, { "code": null, "e": 6336, "s": 5998, "text": "The second React hook provided by the Apollo Client library is the useLazyQuery . The useLazyQuery hook is designed for running queries in response to other events. For example, you can execute a query by clicking on the button or, in our case, by selecting a character from a selecting a node in the visualization to populate the popup." }, { "code": null, "e": 6630, "s": 6336, "text": "The character’s data is then available in the function return under the characterData alias. Notice that I have used the where predicate in my GraphQL query to fetch the data of a specific character. I have used the react-modal library to generate popups, so the code looks like the following:" }, { "code": null, "e": 6926, "s": 6630, "text": "Sometimes you want to be able to access the GraphQL return within the function. In our example application, we need to return the autocomplete options to the input component from the function. To achieve this, you can access Apollo Client and wait for the query to finish with an async function." }, { "code": null, "e": 7043, "s": 6926, "text": "By combining the auto-complete, popup, and other queries I have created the following network exploration component:" }, { "code": null, "e": 7271, "s": 7043, "text": "Hopefully, this blog post will help you get started with the GRANDstack and network exploration and visualizations. If you have any ideas how to improve this application please let me know in GH issues or create a Pull Request." } ]
Scala Stack take() method with example - GeeksforGeeks
03 Nov, 2019 In Scala Stack class, the take() method is utilized to return a stack consisting of the first ‘n’ elements of the stack. Method Definition: def take(n: Int): Stack[A] Return Type: It returns a stack consisting of the first ‘n’ elements of the stack. Example #1: // Scala program of take() // method // Import Stack import scala.collection.mutable._ // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating stack val s1 = Stack(1, 2, 3, 4) // Print the stack println(s1) // Applying take method val result = s1.take(2) // Display output print("Stack containing first two elements: " + result) } } Stack(1, 2, 3, 4) Stack containing first two elements: Stack(1, 2) Example #2: // Scala program of take() // method // Import Stack import scala.collection.mutable._ // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating stack val s1 = Stack(1, 2, 3, 4) // Print the stack println(s1) // Applying take method val result = s1.take(3) // Display output print("Stack containing first three elements: " + result) } } Stack(1, 2, 3, 4) Stack containing first three elements: Stack(1, 2, 3) Scala scala-collection Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Scala Tutorial – Learn Scala with Step By Step Guide Type Casting in Scala Scala Lists Operators in Scala Class and Object in Scala Scala String substring() method with example Inheritance in Scala Throw Keyword in Scala Hello World in Scala Scala | Arrays
[ { "code": null, "e": 24138, "s": 24110, "text": "\n03 Nov, 2019" }, { "code": null, "e": 24259, "s": 24138, "text": "In Scala Stack class, the take() method is utilized to return a stack consisting of the first ‘n’ elements of the stack." }, { "code": null, "e": 24305, "s": 24259, "text": "Method Definition: def take(n: Int): Stack[A]" }, { "code": null, "e": 24388, "s": 24305, "text": "Return Type: It returns a stack consisting of the first ‘n’ elements of the stack." }, { "code": null, "e": 24400, "s": 24388, "text": "Example #1:" }, { "code": "// Scala program of take() // method // Import Stack import scala.collection.mutable._ // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating stack val s1 = Stack(1, 2, 3, 4) // Print the stack println(s1) // Applying take method val result = s1.take(2) // Display output print(\"Stack containing first two elements: \" + result) } } ", "e": 24898, "s": 24400, "text": null }, { "code": null, "e": 24966, "s": 24898, "text": "Stack(1, 2, 3, 4)\nStack containing first two elements: Stack(1, 2)\n" }, { "code": null, "e": 24978, "s": 24966, "text": "Example #2:" }, { "code": "// Scala program of take() // method // Import Stack import scala.collection.mutable._ // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating stack val s1 = Stack(1, 2, 3, 4) // Print the stack println(s1) // Applying take method val result = s1.take(3) // Display output print(\"Stack containing first three elements: \" + result) } } ", "e": 25478, "s": 24978, "text": null }, { "code": null, "e": 25551, "s": 25478, "text": "Stack(1, 2, 3, 4)\nStack containing first three elements: Stack(1, 2, 3)\n" }, { "code": null, "e": 25557, "s": 25551, "text": "Scala" }, { "code": null, "e": 25574, "s": 25557, "text": "scala-collection" }, { "code": null, "e": 25587, "s": 25574, "text": "Scala-Method" }, { "code": null, "e": 25593, "s": 25587, "text": "Scala" }, { "code": null, "e": 25691, "s": 25593, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25700, "s": 25691, "text": "Comments" }, { "code": null, "e": 25713, "s": 25700, "text": "Old Comments" }, { "code": null, "e": 25766, "s": 25713, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 25788, "s": 25766, "text": "Type Casting in Scala" }, { "code": null, "e": 25800, "s": 25788, "text": "Scala Lists" }, { "code": null, "e": 25819, "s": 25800, "text": "Operators in Scala" }, { "code": null, "e": 25845, "s": 25819, "text": "Class and Object in Scala" }, { "code": null, "e": 25890, "s": 25845, "text": "Scala String substring() method with example" }, { "code": null, "e": 25911, "s": 25890, "text": "Inheritance in Scala" }, { "code": null, "e": 25934, "s": 25911, "text": "Throw Keyword in Scala" }, { "code": null, "e": 25955, "s": 25934, "text": "Hello World in Scala" } ]
PyQt5 – Setting and accessing WHATS THIS help text for Status Bar - GeeksforGeeks
26 Mar, 2020 n PyQt5 there are lots of widgets and bars and when we tend to make an application, we end up putting lots of windows and for each window there exit status bar. Sometimes we can’t remember why this status bar is used and what is this status bar. That’s why for back-end purposes PyQt5 allows us to set help text. In this article we will see how to set and access help text for status bar. In order to set help text we use setWhatsThis() method and for accessing the help text we use whatsThis() method. Syntax : self.statusBar().setWhatsThis() self.statusBar().whatsThis() Argument :setWhatsThis() takes string as argument.whatsThis() takes no argument. Return :setWhatsThis() return NonewhatsThis() returns string. Code: from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Python") # setting the geometry of window self.setGeometry(60, 60, 600, 400) # setting status bar message self.statusBar().showMessage("This is status bar") # setting border self.statusBar().setStyleSheet("border :3px solid black;") # setting help text self.statusBar().setWhatsThis("this is help text for status bar") # creating a label widget self.label_1 = QLabel(self) # moving position self.label_1.move(100, 100) # setting up the border self.label_1.setStyleSheet("border :1px solid blue;") # accessing help text of status bar help = self.statusBar().whatsThis() # setting text to label self.label_1.setText(help) # resizing label self.label_1.adjustSize() # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Reading and Writing to text files in Python sum() function in Python *args and **kwargs in Python
[ { "code": null, "e": 25034, "s": 25006, "text": "\n26 Mar, 2020" }, { "code": null, "e": 25423, "s": 25034, "text": "n PyQt5 there are lots of widgets and bars and when we tend to make an application, we end up putting lots of windows and for each window there exit status bar. Sometimes we can’t remember why this status bar is used and what is this status bar. That’s why for back-end purposes PyQt5 allows us to set help text. In this article we will see how to set and access help text for status bar." }, { "code": null, "e": 25537, "s": 25423, "text": "In order to set help text we use setWhatsThis() method and for accessing the help text we use whatsThis() method." }, { "code": null, "e": 25546, "s": 25537, "text": "Syntax :" }, { "code": null, "e": 25608, "s": 25546, "text": "self.statusBar().setWhatsThis()\nself.statusBar().whatsThis()\n" }, { "code": null, "e": 25689, "s": 25608, "text": "Argument :setWhatsThis() takes string as argument.whatsThis() takes no argument." }, { "code": null, "e": 25751, "s": 25689, "text": "Return :setWhatsThis() return NonewhatsThis() returns string." }, { "code": null, "e": 25757, "s": 25751, "text": "Code:" }, { "code": "from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Python\") # setting the geometry of window self.setGeometry(60, 60, 600, 400) # setting status bar message self.statusBar().showMessage(\"This is status bar\") # setting border self.statusBar().setStyleSheet(\"border :3px solid black;\") # setting help text self.statusBar().setWhatsThis(\"this is help text for status bar\") # creating a label widget self.label_1 = QLabel(self) # moving position self.label_1.move(100, 100) # setting up the border self.label_1.setStyleSheet(\"border :1px solid blue;\") # accessing help text of status bar help = self.statusBar().whatsThis() # setting text to label self.label_1.setText(help) # resizing label self.label_1.adjustSize() # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 27000, "s": 25757, "text": null }, { "code": null, "e": 27009, "s": 27000, "text": "Output :" }, { "code": null, "e": 27020, "s": 27009, "text": "Python-gui" }, { "code": null, "e": 27032, "s": 27020, "text": "Python-PyQt" }, { "code": null, "e": 27039, "s": 27032, "text": "Python" }, { "code": null, "e": 27137, "s": 27039, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27146, "s": 27137, "text": "Comments" }, { "code": null, "e": 27159, "s": 27146, "text": "Old Comments" }, { "code": null, "e": 27177, "s": 27159, "text": "Python Dictionary" }, { "code": null, "e": 27212, "s": 27177, "text": "Read a file line by line in Python" }, { "code": null, "e": 27234, "s": 27212, "text": "Enumerate() in Python" }, { "code": null, "e": 27266, "s": 27234, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27308, "s": 27266, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27334, "s": 27308, "text": "Python String | replace()" }, { "code": null, "e": 27371, "s": 27334, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27415, "s": 27371, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27440, "s": 27415, "text": "sum() function in Python" } ]
Control Structures in Programming Languages - GeeksforGeeks
16 Jan, 2020 Control Structures are just a way to specify flow of control in programs. Any algorithm or program can be more clear and understood if they use self-contained modules called as logic or control structures. It basically analyzes and chooses in which direction a program flows based on certain parameters or conditions. There are three basic types of logic, or flow of control, known as: Sequence logic, or sequential flowSelection logic, or conditional flowIteration logic, or repetitive flow Sequence logic, or sequential flow Selection logic, or conditional flow Iteration logic, or repetitive flow Let us see them in detail: Sequential Logic (Sequential Flow)Sequential logic as the name suggests follows a serial or sequential flow in which the flow depends on the series of instructions given to the computer. Unless new instructions are given, the modules are executed in the obvious sequence. The sequences may be given, by means of numbered steps explicitly. Also, implicitly follows the order in which modules are written. Most of the processing, even some complex problems, will generally follow this elementary flow pattern.Sequential Control flowSelection Logic (Conditional Flow)Selection Logic simply involves a number of conditions or parameters which decides one out of several written modules. The structures which use these type of logic are known as Conditional Structures. These structures can be of three types:Single AlternativeThis structure has the form:If (condition) then: [Module A] [End of If structure]Implementation:C/C++ if statement with ExamplesJava if statement with ExamplesDouble AlternativeThis structure has the form:If (Condition), then: [Module A] Else: [Module B] [End if structure] Implementation:C/C++ if-else statement with ExamplesJava if-else statement with ExamplesMultiple AlternativesThis structure has the form:If (condition A), then: [Module A] Else if (condition B), then: [Module B] .. .. Else if (condition N), then: [Module N] [End If structure] Implementation:C/C++ if-else if statement with ExamplesJava if-else if statement with ExamplesIn this way, the flow of the program depends on the set of conditions that are written. This can be more understood by the following flow charts:Double Alternative Control FlowIteration Logic (Repetitive Flow)The Iteration logic employs a loop which involves a repeat statement followed by a module known as the body of a loop.The two types of these structures are:Repeat-For StructureThis structure has the form:Repeat for i = A to N by I: [Module] [End of loop] Here, A is the initial value, N is the end value and I is the increment. The loop ends when A>B. K increases or decreases according to the positive and negative value of I respectively.Repeat-For FlowImplementation:C/C++ for loop with ExamplesJava for loop with ExamplesRepeat-While StructureIt also uses a condition to control the loop. This structure has the form:Repeat while condition: [Module] [End of Loop] Repeat While FlowImplementation:C/C++ while loop with ExamplesJava while loop with ExamplesIn this, there requires a statement that initializes the condition controlling the loop, and there must also be a statement inside the module that will change this condition leading to the end of the loop. Sequential Logic (Sequential Flow)Sequential logic as the name suggests follows a serial or sequential flow in which the flow depends on the series of instructions given to the computer. Unless new instructions are given, the modules are executed in the obvious sequence. The sequences may be given, by means of numbered steps explicitly. Also, implicitly follows the order in which modules are written. Most of the processing, even some complex problems, will generally follow this elementary flow pattern.Sequential Control flow Sequential logic as the name suggests follows a serial or sequential flow in which the flow depends on the series of instructions given to the computer. Unless new instructions are given, the modules are executed in the obvious sequence. The sequences may be given, by means of numbered steps explicitly. Also, implicitly follows the order in which modules are written. Most of the processing, even some complex problems, will generally follow this elementary flow pattern. Sequential Control flow Selection Logic (Conditional Flow)Selection Logic simply involves a number of conditions or parameters which decides one out of several written modules. The structures which use these type of logic are known as Conditional Structures. These structures can be of three types:Single AlternativeThis structure has the form:If (condition) then: [Module A] [End of If structure]Implementation:C/C++ if statement with ExamplesJava if statement with ExamplesDouble AlternativeThis structure has the form:If (Condition), then: [Module A] Else: [Module B] [End if structure] Implementation:C/C++ if-else statement with ExamplesJava if-else statement with ExamplesMultiple AlternativesThis structure has the form:If (condition A), then: [Module A] Else if (condition B), then: [Module B] .. .. Else if (condition N), then: [Module N] [End If structure] Implementation:C/C++ if-else if statement with ExamplesJava if-else if statement with ExamplesIn this way, the flow of the program depends on the set of conditions that are written. This can be more understood by the following flow charts:Double Alternative Control Flow Selection Logic simply involves a number of conditions or parameters which decides one out of several written modules. The structures which use these type of logic are known as Conditional Structures. These structures can be of three types: Single AlternativeThis structure has the form:If (condition) then: [Module A] [End of If structure]Implementation:C/C++ if statement with ExamplesJava if statement with Examples If (condition) then: [Module A] [End of If structure] Implementation: C/C++ if statement with Examples Java if statement with Examples Double AlternativeThis structure has the form:If (Condition), then: [Module A] Else: [Module B] [End if structure] Implementation:C/C++ if-else statement with ExamplesJava if-else statement with Examples If (Condition), then: [Module A] Else: [Module B] [End if structure] Implementation: C/C++ if-else statement with Examples Java if-else statement with Examples Multiple AlternativesThis structure has the form:If (condition A), then: [Module A] Else if (condition B), then: [Module B] .. .. Else if (condition N), then: [Module N] [End If structure] Implementation:C/C++ if-else if statement with ExamplesJava if-else if statement with Examples If (condition A), then: [Module A] Else if (condition B), then: [Module B] .. .. Else if (condition N), then: [Module N] [End If structure] Implementation: C/C++ if-else if statement with Examples Java if-else if statement with Examples In this way, the flow of the program depends on the set of conditions that are written. This can be more understood by the following flow charts: Double Alternative Control Flow Iteration Logic (Repetitive Flow)The Iteration logic employs a loop which involves a repeat statement followed by a module known as the body of a loop.The two types of these structures are:Repeat-For StructureThis structure has the form:Repeat for i = A to N by I: [Module] [End of loop] Here, A is the initial value, N is the end value and I is the increment. The loop ends when A>B. K increases or decreases according to the positive and negative value of I respectively.Repeat-For FlowImplementation:C/C++ for loop with ExamplesJava for loop with ExamplesRepeat-While StructureIt also uses a condition to control the loop. This structure has the form:Repeat while condition: [Module] [End of Loop] Repeat While FlowImplementation:C/C++ while loop with ExamplesJava while loop with ExamplesIn this, there requires a statement that initializes the condition controlling the loop, and there must also be a statement inside the module that will change this condition leading to the end of the loop. Repeat-For StructureThis structure has the form:Repeat for i = A to N by I: [Module] [End of loop] Here, A is the initial value, N is the end value and I is the increment. The loop ends when A>B. K increases or decreases according to the positive and negative value of I respectively.Repeat-For FlowImplementation:C/C++ for loop with ExamplesJava for loop with Examples Repeat for i = A to N by I: [Module] [End of loop] Here, A is the initial value, N is the end value and I is the increment. The loop ends when A>B. K increases or decreases according to the positive and negative value of I respectively. Repeat-For Flow Implementation: C/C++ for loop with Examples Java for loop with Examples Repeat-While StructureIt also uses a condition to control the loop. This structure has the form:Repeat while condition: [Module] [End of Loop] Repeat While FlowImplementation:C/C++ while loop with ExamplesJava while loop with Examples Repeat while condition: [Module] [End of Loop] Repeat While Flow Implementation: C/C++ while loop with Examples Java while loop with Examples In this, there requires a statement that initializes the condition controlling the loop, and there must also be a statement inside the module that will change this condition leading to the end of the loop. Programming Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. R - Matrices R - Charts and Graphs R - Data Types 7 Highest Paying Programming Languages For Freelancers in 2022 Introduction of Object Oriented Programming 5 Best Languages for Competitive Programming Exception Handling in C# Maximum value of unsigned int in C++ Problem in comparing Floating point numbers and how to compare them correctly? Difference between for and while loop in C, C++, Java
[ { "code": null, "e": 24648, "s": 24620, "text": "\n16 Jan, 2020" }, { "code": null, "e": 25034, "s": 24648, "text": "Control Structures are just a way to specify flow of control in programs. Any algorithm or program can be more clear and understood if they use self-contained modules called as logic or control structures. It basically analyzes and chooses in which direction a program flows based on certain parameters or conditions. There are three basic types of logic, or flow of control, known as:" }, { "code": null, "e": 25140, "s": 25034, "text": "Sequence logic, or sequential flowSelection logic, or conditional flowIteration logic, or repetitive flow" }, { "code": null, "e": 25175, "s": 25140, "text": "Sequence logic, or sequential flow" }, { "code": null, "e": 25212, "s": 25175, "text": "Selection logic, or conditional flow" }, { "code": null, "e": 25248, "s": 25212, "text": "Iteration logic, or repetitive flow" }, { "code": null, "e": 25275, "s": 25248, "text": "Let us see them in detail:" }, { "code": null, "e": 27977, "s": 25275, "text": "Sequential Logic (Sequential Flow)Sequential logic as the name suggests follows a serial or sequential flow in which the flow depends on the series of instructions given to the computer. Unless new instructions are given, the modules are executed in the obvious sequence. The sequences may be given, by means of numbered steps explicitly. Also, implicitly follows the order in which modules are written. Most of the processing, even some complex problems, will generally follow this elementary flow pattern.Sequential Control flowSelection Logic (Conditional Flow)Selection Logic simply involves a number of conditions or parameters which decides one out of several written modules. The structures which use these type of logic are known as Conditional Structures. These structures can be of three types:Single AlternativeThis structure has the form:If (condition) then:\n [Module A] \n[End of If structure]Implementation:C/C++ if statement with ExamplesJava if statement with ExamplesDouble AlternativeThis structure has the form:If (Condition), then:\n [Module A]\nElse:\n [Module B]\n[End if structure]\nImplementation:C/C++ if-else statement with ExamplesJava if-else statement with ExamplesMultiple AlternativesThis structure has the form:If (condition A), then:\n [Module A]\nElse if (condition B), then:\n [Module B]\n ..\n ..\nElse if (condition N), then:\n [Module N]\n[End If structure]\nImplementation:C/C++ if-else if statement with ExamplesJava if-else if statement with ExamplesIn this way, the flow of the program depends on the set of conditions that are written. This can be more understood by the following flow charts:Double Alternative Control FlowIteration Logic (Repetitive Flow)The Iteration logic employs a loop which involves a repeat statement followed by a module known as the body of a loop.The two types of these structures are:Repeat-For StructureThis structure has the form:Repeat for i = A to N by I:\n [Module]\n[End of loop]\nHere, A is the initial value, N is the end value and I is the increment. The loop ends when A>B. K increases or decreases according to the positive and negative value of I respectively.Repeat-For FlowImplementation:C/C++ for loop with ExamplesJava for loop with ExamplesRepeat-While StructureIt also uses a condition to control the loop. This structure has the form:Repeat while condition:\n [Module]\n[End of Loop]\nRepeat While FlowImplementation:C/C++ while loop with ExamplesJava while loop with ExamplesIn this, there requires a statement that initializes the condition controlling the loop, and there must also be a statement inside the module that will change this condition leading to the end of the loop." }, { "code": null, "e": 28508, "s": 27977, "text": "Sequential Logic (Sequential Flow)Sequential logic as the name suggests follows a serial or sequential flow in which the flow depends on the series of instructions given to the computer. Unless new instructions are given, the modules are executed in the obvious sequence. The sequences may be given, by means of numbered steps explicitly. Also, implicitly follows the order in which modules are written. Most of the processing, even some complex problems, will generally follow this elementary flow pattern.Sequential Control flow" }, { "code": null, "e": 28982, "s": 28508, "text": "Sequential logic as the name suggests follows a serial or sequential flow in which the flow depends on the series of instructions given to the computer. Unless new instructions are given, the modules are executed in the obvious sequence. The sequences may be given, by means of numbered steps explicitly. Also, implicitly follows the order in which modules are written. Most of the processing, even some complex problems, will generally follow this elementary flow pattern." }, { "code": null, "e": 29006, "s": 28982, "text": "Sequential Control flow" }, { "code": null, "e": 30169, "s": 29006, "text": "Selection Logic (Conditional Flow)Selection Logic simply involves a number of conditions or parameters which decides one out of several written modules. The structures which use these type of logic are known as Conditional Structures. These structures can be of three types:Single AlternativeThis structure has the form:If (condition) then:\n [Module A] \n[End of If structure]Implementation:C/C++ if statement with ExamplesJava if statement with ExamplesDouble AlternativeThis structure has the form:If (Condition), then:\n [Module A]\nElse:\n [Module B]\n[End if structure]\nImplementation:C/C++ if-else statement with ExamplesJava if-else statement with ExamplesMultiple AlternativesThis structure has the form:If (condition A), then:\n [Module A]\nElse if (condition B), then:\n [Module B]\n ..\n ..\nElse if (condition N), then:\n [Module N]\n[End If structure]\nImplementation:C/C++ if-else if statement with ExamplesJava if-else if statement with ExamplesIn this way, the flow of the program depends on the set of conditions that are written. This can be more understood by the following flow charts:Double Alternative Control Flow" }, { "code": null, "e": 30410, "s": 30169, "text": "Selection Logic simply involves a number of conditions or parameters which decides one out of several written modules. The structures which use these type of logic are known as Conditional Structures. These structures can be of three types:" }, { "code": null, "e": 30596, "s": 30410, "text": "Single AlternativeThis structure has the form:If (condition) then:\n [Module A] \n[End of If structure]Implementation:C/C++ if statement with ExamplesJava if statement with Examples" }, { "code": null, "e": 30658, "s": 30596, "text": "If (condition) then:\n [Module A] \n[End of If structure]" }, { "code": null, "e": 30674, "s": 30658, "text": "Implementation:" }, { "code": null, "e": 30707, "s": 30674, "text": "C/C++ if statement with Examples" }, { "code": null, "e": 30739, "s": 30707, "text": "Java if statement with Examples" }, { "code": null, "e": 30953, "s": 30739, "text": "Double AlternativeThis structure has the form:If (Condition), then:\n [Module A]\nElse:\n [Module B]\n[End if structure]\nImplementation:C/C++ if-else statement with ExamplesJava if-else statement with Examples" }, { "code": null, "e": 31033, "s": 30953, "text": "If (Condition), then:\n [Module A]\nElse:\n [Module B]\n[End if structure]\n" }, { "code": null, "e": 31049, "s": 31033, "text": "Implementation:" }, { "code": null, "e": 31087, "s": 31049, "text": "C/C++ if-else statement with Examples" }, { "code": null, "e": 31124, "s": 31087, "text": "Java if-else statement with Examples" }, { "code": null, "e": 31439, "s": 31124, "text": "Multiple AlternativesThis structure has the form:If (condition A), then:\n [Module A]\nElse if (condition B), then:\n [Module B]\n ..\n ..\nElse if (condition N), then:\n [Module N]\n[End If structure]\nImplementation:C/C++ if-else if statement with ExamplesJava if-else if statement with Examples" }, { "code": null, "e": 31611, "s": 31439, "text": "If (condition A), then:\n [Module A]\nElse if (condition B), then:\n [Module B]\n ..\n ..\nElse if (condition N), then:\n [Module N]\n[End If structure]\n" }, { "code": null, "e": 31627, "s": 31611, "text": "Implementation:" }, { "code": null, "e": 31668, "s": 31627, "text": "C/C++ if-else if statement with Examples" }, { "code": null, "e": 31708, "s": 31668, "text": "Java if-else if statement with Examples" }, { "code": null, "e": 31854, "s": 31708, "text": "In this way, the flow of the program depends on the set of conditions that are written. This can be more understood by the following flow charts:" }, { "code": null, "e": 31886, "s": 31854, "text": "Double Alternative Control Flow" }, { "code": null, "e": 32896, "s": 31886, "text": "Iteration Logic (Repetitive Flow)The Iteration logic employs a loop which involves a repeat statement followed by a module known as the body of a loop.The two types of these structures are:Repeat-For StructureThis structure has the form:Repeat for i = A to N by I:\n [Module]\n[End of loop]\nHere, A is the initial value, N is the end value and I is the increment. The loop ends when A>B. K increases or decreases according to the positive and negative value of I respectively.Repeat-For FlowImplementation:C/C++ for loop with ExamplesJava for loop with ExamplesRepeat-While StructureIt also uses a condition to control the loop. This structure has the form:Repeat while condition:\n [Module]\n[End of Loop]\nRepeat While FlowImplementation:C/C++ while loop with ExamplesJava while loop with ExamplesIn this, there requires a statement that initializes the condition controlling the loop, and there must also be a statement inside the module that will change this condition leading to the end of the loop." }, { "code": null, "e": 33273, "s": 32896, "text": "Repeat-For StructureThis structure has the form:Repeat for i = A to N by I:\n [Module]\n[End of loop]\nHere, A is the initial value, N is the end value and I is the increment. The loop ends when A>B. K increases or decreases according to the positive and negative value of I respectively.Repeat-For FlowImplementation:C/C++ for loop with ExamplesJava for loop with Examples" }, { "code": null, "e": 33332, "s": 33273, "text": "Repeat for i = A to N by I:\n [Module]\n[End of loop]\n" }, { "code": null, "e": 33518, "s": 33332, "text": "Here, A is the initial value, N is the end value and I is the increment. The loop ends when A>B. K increases or decreases according to the positive and negative value of I respectively." }, { "code": null, "e": 33534, "s": 33518, "text": "Repeat-For Flow" }, { "code": null, "e": 33550, "s": 33534, "text": "Implementation:" }, { "code": null, "e": 33579, "s": 33550, "text": "C/C++ for loop with Examples" }, { "code": null, "e": 33607, "s": 33579, "text": "Java for loop with Examples" }, { "code": null, "e": 33847, "s": 33607, "text": "Repeat-While StructureIt also uses a condition to control the loop. This structure has the form:Repeat while condition:\n [Module]\n[End of Loop]\nRepeat While FlowImplementation:C/C++ while loop with ExamplesJava while loop with Examples" }, { "code": null, "e": 33900, "s": 33847, "text": "Repeat while condition:\n [Module]\n[End of Loop]\n" }, { "code": null, "e": 33918, "s": 33900, "text": "Repeat While Flow" }, { "code": null, "e": 33934, "s": 33918, "text": "Implementation:" }, { "code": null, "e": 33965, "s": 33934, "text": "C/C++ while loop with Examples" }, { "code": null, "e": 33995, "s": 33965, "text": "Java while loop with Examples" }, { "code": null, "e": 34201, "s": 33995, "text": "In this, there requires a statement that initializes the condition controlling the loop, and there must also be a statement inside the module that will change this condition leading to the end of the loop." }, { "code": null, "e": 34222, "s": 34201, "text": "Programming Language" }, { "code": null, "e": 34320, "s": 34222, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34333, "s": 34320, "text": "R - Matrices" }, { "code": null, "e": 34355, "s": 34333, "text": "R - Charts and Graphs" }, { "code": null, "e": 34370, "s": 34355, "text": "R - Data Types" }, { "code": null, "e": 34433, "s": 34370, "text": "7 Highest Paying Programming Languages For Freelancers in 2022" }, { "code": null, "e": 34477, "s": 34433, "text": "Introduction of Object Oriented Programming" }, { "code": null, "e": 34522, "s": 34477, "text": "5 Best Languages for Competitive Programming" }, { "code": null, "e": 34547, "s": 34522, "text": "Exception Handling in C#" }, { "code": null, "e": 34584, "s": 34547, "text": "Maximum value of unsigned int in C++" }, { "code": null, "e": 34663, "s": 34584, "text": "Problem in comparing Floating point numbers and how to compare them correctly?" } ]
Blazing Fast Data Wrangling With R data.table | by Thu Vu | Towards Data Science
Update March 2020: You can find a very interesting comparison between data.tableand dplyr here. I have recently noticed that every R script I wrote starts with library(data.table). And that seems a very compelling reason for me to write a post about it. You may have seen that as the machine learning community is developing, Python has gained enormous popularity and as a result, the Pandas library has automatically become a staple for a lot of people. However, if I had a choice, I would definitely prefer using R data.table for relatively large dataset data manipulation, in-depth exploration and ad-hoc analyses. Why? Because it’s so fast, elegant and beautiful (sorry if I got too enthusiastic!). But hey, working with data means you’ll have to turn the code upside down, mould it, clean it for maybe... uhm... a thousand times before you can actually build a machine learning model. In fact, data pre-processing usually takes 80–90% the time of a data science project. That’s why I can’t afford slow and inefficient code (and I don’t think anyone should, as a data professional). So let’s dive into what data.table is and why many people have become big fans of it. data.table package is an extension of data.frame package in R. It is widely used for fast aggregation of large datasets, low latency add/update/remove of columns, quicker ordered joins, and a fast file reader. That sounds good, right? You may think it’s difficult to pick up, but actually a data.table is also a type of data.frame. So rest assured that any code you use for a data.frame will also work as well with a data.table. But believe me, once you’ve used data.table, you’ll never want to use the base R data.frame syntax again. Keep reading if you want to know why. From my own experience, working with fast code can really improve the thinking flow in the data analysis process. Speed also very important in a data science project, in which you usually have to quickly prototype an idea. When it comes to speed, data.table puts all other packages in Python and many other languages to shame. This is shown in this benchmark, which compares tools from R, Python and Julia. To do five data manipulations on a 50GB dataset, data.table only took on average 123s, while Spark took 381s, (py)datatable took 712s, and pandas could not do the task due to out of memory. One of the most powerful functions in data.table package is fread(), which imports data similarly to whatread.csv() does. But it’s optimized and much much faster. Let’s look at this example: require("microbenchmark")res <- microbenchmark( read.csv = read.csv(url("https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data"), header=FALSE), fread = data.table::fread("https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data", header=FALSE), times = 10)res The results will show that on average, fread() will be 3-4 times faster than read.csv() function. Almost every data manipulation with data.table will look like this: As a result, the code you write will be very consistent and easy to read. Let’s take the US Census Income dataset for illustration purposes: dt <- fread("https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data", header=FALSE)names(dt) <- c("age", "workclass", "fnlwgt", "education", "education_num", "marital_status", "occupation", "relationship", "race", "sex", "capital_gain", "capital_loss","hours_per_week", "native_country", "label") In the below examples, I’ll compare the code in base R, Python and data.table, so that you can easily compare them: To compute the average age of all “Tech-support” workers: To compute the average age of all “Tech-support” workers: > in base R you’d probably write something like this: mean(dt[dt$occupation == 'Tech-support', 'age']) > in Python: np.mean(dt[dt.occupation == 'Tech-support'].age) > vs. in data.table: dt[occupation == 'Tech-support', mean(age)] As you can see in this simple example, data.table removes all redundancy of repeating dt all the times, compared to Python and base R. This in turn reduces the chance of making typo mistakes (remember the coding principle DRY — Don’t repeat yourself!) 2. To aggregate age by occupation for all male workers: > in base R you’d probably write: aggregate(age ~ occupation, dt[dt$sex == 'Male', ], sum) > in Python: dt[dt.sex == 'Male'].groupby('occupation')['age'].sum() > vs. in data.table: dt[sex == 'Male', .(sum(age)), by = occupation] The by = term defines which column(s) you want to aggregate your data on. This data.table syntax may seem a little intimidating at first, but once you get used to it you’ll never bother typing “groupby(...)” again. 3. To conditionally modify values in a column, for example to increase the age of all Tech-support workers by 5 (I know it’s a silly example, but just for illustration :)). > in base R you’d probably have to write this horrible line (who has time to write dt$ so many times!): dt$age[dt$occupation == 'Tech-support'] <- dt$age[dt$occupation == 'Tech-support'] + 5 > in Python (there are several alternatives that are equally long): mask = dt['occupation'] == 'Tech-support'dt.loc[mask, 'age'] = dt.loc[mask, 'age'] + 5 or using np.where: dt['age'] = np.where(dt['occupation'] == 'Tech-support', dt.age + 5, dt.age] > vs. in data.table: dt[occupation == 'Tech-support', age := age + 5]# and the ifelse function does just as nicely:dt[, age := ifelse(occupation == 'Tech-support', age + 5, age)] It’s almost like a magic, isn’t it? No more cumbersome repetitive code, and it keeps yourself DRY. You may have noticed the strange operator := in the data.table syntax. This operator is used to assign new values to an existing column, just like using the argument inplace=True in Python. 4. Renaming columns is a breeze in data.table. If I want to rename occupation column as job: > in base R you might write: colnames(dt)[which(names(dt) == "occupation")] <- "job" > and in Python: dt = dt.rename(columns={'occupation': 'job'}) > vs. in data.table: setnames(dt, 'occupation', 'job') 5. What about applying a function to several columns? Suppose you want to multiply capital_gain and capital_loss by 1000: > in base R: apply(dt[,c('capital_gain', 'capital_loss')], 2, function(x) x*1000) > in Python: dt[['capital_gain', 'capital_loss']].apply(lambda x : x*1000) > vs. in data.table: dt[, lapply(.SD, function(x) x*1000), .SDcols = c("capital_gain", "capital_loss")] You might find this syntax in data.table is a little quirky, but the .SDcols argument comes in very handy in many cases, and the general form of data.table syntax is preserved this way. From a few simple illustrations above, one can see that the code in R data.table is in many cases faster, cleaner and more efficient than in base R and Python. The form of data.table code is very consistent. You only need to remember: DT[i, j, by] As an additional note, the data subsetting with i by keying a data.table even allows faster subsets, joins and sorts, which you can read more about in this documentation, or this very useful cheat sheet. Thank you for reading. If you like this post, I would write more about how to do advanced data wrangling with R and Python in the future posts.
[ { "code": null, "e": 268, "s": 172, "text": "Update March 2020: You can find a very interesting comparison between data.tableand dplyr here." }, { "code": null, "e": 426, "s": 268, "text": "I have recently noticed that every R script I wrote starts with library(data.table). And that seems a very compelling reason for me to write a post about it." }, { "code": null, "e": 627, "s": 426, "text": "You may have seen that as the machine learning community is developing, Python has gained enormous popularity and as a result, the Pandas library has automatically become a staple for a lot of people." }, { "code": null, "e": 1259, "s": 627, "text": "However, if I had a choice, I would definitely prefer using R data.table for relatively large dataset data manipulation, in-depth exploration and ad-hoc analyses. Why? Because it’s so fast, elegant and beautiful (sorry if I got too enthusiastic!). But hey, working with data means you’ll have to turn the code upside down, mould it, clean it for maybe... uhm... a thousand times before you can actually build a machine learning model. In fact, data pre-processing usually takes 80–90% the time of a data science project. That’s why I can’t afford slow and inefficient code (and I don’t think anyone should, as a data professional)." }, { "code": null, "e": 1345, "s": 1259, "text": "So let’s dive into what data.table is and why many people have become big fans of it." }, { "code": null, "e": 1555, "s": 1345, "text": "data.table package is an extension of data.frame package in R. It is widely used for fast aggregation of large datasets, low latency add/update/remove of columns, quicker ordered joins, and a fast file reader." }, { "code": null, "e": 1918, "s": 1555, "text": "That sounds good, right? You may think it’s difficult to pick up, but actually a data.table is also a type of data.frame. So rest assured that any code you use for a data.frame will also work as well with a data.table. But believe me, once you’ve used data.table, you’ll never want to use the base R data.frame syntax again. Keep reading if you want to know why." }, { "code": null, "e": 2141, "s": 1918, "text": "From my own experience, working with fast code can really improve the thinking flow in the data analysis process. Speed also very important in a data science project, in which you usually have to quickly prototype an idea." }, { "code": null, "e": 2515, "s": 2141, "text": "When it comes to speed, data.table puts all other packages in Python and many other languages to shame. This is shown in this benchmark, which compares tools from R, Python and Julia. To do five data manipulations on a 50GB dataset, data.table only took on average 123s, while Spark took 381s, (py)datatable took 712s, and pandas could not do the task due to out of memory." }, { "code": null, "e": 2706, "s": 2515, "text": "One of the most powerful functions in data.table package is fread(), which imports data similarly to whatread.csv() does. But it’s optimized and much much faster. Let’s look at this example:" }, { "code": null, "e": 3009, "s": 2706, "text": "require(\"microbenchmark\")res <- microbenchmark( read.csv = read.csv(url(\"https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data\"), header=FALSE), fread = data.table::fread(\"https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data\", header=FALSE), times = 10)res" }, { "code": null, "e": 3107, "s": 3009, "text": "The results will show that on average, fread() will be 3-4 times faster than read.csv() function." }, { "code": null, "e": 3175, "s": 3107, "text": "Almost every data manipulation with data.table will look like this:" }, { "code": null, "e": 3316, "s": 3175, "text": "As a result, the code you write will be very consistent and easy to read. Let’s take the US Census Income dataset for illustration purposes:" }, { "code": null, "e": 3633, "s": 3316, "text": "dt <- fread(\"https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data\", header=FALSE)names(dt) <- c(\"age\", \"workclass\", \"fnlwgt\", \"education\", \"education_num\", \"marital_status\", \"occupation\", \"relationship\", \"race\", \"sex\", \"capital_gain\", \"capital_loss\",\"hours_per_week\", \"native_country\", \"label\")" }, { "code": null, "e": 3749, "s": 3633, "text": "In the below examples, I’ll compare the code in base R, Python and data.table, so that you can easily compare them:" }, { "code": null, "e": 3807, "s": 3749, "text": "To compute the average age of all “Tech-support” workers:" }, { "code": null, "e": 3865, "s": 3807, "text": "To compute the average age of all “Tech-support” workers:" }, { "code": null, "e": 3919, "s": 3865, "text": "> in base R you’d probably write something like this:" }, { "code": null, "e": 3968, "s": 3919, "text": "mean(dt[dt$occupation == 'Tech-support', 'age'])" }, { "code": null, "e": 3981, "s": 3968, "text": "> in Python:" }, { "code": null, "e": 4030, "s": 3981, "text": "np.mean(dt[dt.occupation == 'Tech-support'].age)" }, { "code": null, "e": 4051, "s": 4030, "text": "> vs. in data.table:" }, { "code": null, "e": 4095, "s": 4051, "text": "dt[occupation == 'Tech-support', mean(age)]" }, { "code": null, "e": 4347, "s": 4095, "text": "As you can see in this simple example, data.table removes all redundancy of repeating dt all the times, compared to Python and base R. This in turn reduces the chance of making typo mistakes (remember the coding principle DRY — Don’t repeat yourself!)" }, { "code": null, "e": 4403, "s": 4347, "text": "2. To aggregate age by occupation for all male workers:" }, { "code": null, "e": 4437, "s": 4403, "text": "> in base R you’d probably write:" }, { "code": null, "e": 4494, "s": 4437, "text": "aggregate(age ~ occupation, dt[dt$sex == 'Male', ], sum)" }, { "code": null, "e": 4507, "s": 4494, "text": "> in Python:" }, { "code": null, "e": 4563, "s": 4507, "text": "dt[dt.sex == 'Male'].groupby('occupation')['age'].sum()" }, { "code": null, "e": 4584, "s": 4563, "text": "> vs. in data.table:" }, { "code": null, "e": 4632, "s": 4584, "text": "dt[sex == 'Male', .(sum(age)), by = occupation]" }, { "code": null, "e": 4847, "s": 4632, "text": "The by = term defines which column(s) you want to aggregate your data on. This data.table syntax may seem a little intimidating at first, but once you get used to it you’ll never bother typing “groupby(...)” again." }, { "code": null, "e": 5020, "s": 4847, "text": "3. To conditionally modify values in a column, for example to increase the age of all Tech-support workers by 5 (I know it’s a silly example, but just for illustration :))." }, { "code": null, "e": 5124, "s": 5020, "text": "> in base R you’d probably have to write this horrible line (who has time to write dt$ so many times!):" }, { "code": null, "e": 5211, "s": 5124, "text": "dt$age[dt$occupation == 'Tech-support'] <- dt$age[dt$occupation == 'Tech-support'] + 5" }, { "code": null, "e": 5279, "s": 5211, "text": "> in Python (there are several alternatives that are equally long):" }, { "code": null, "e": 5366, "s": 5279, "text": "mask = dt['occupation'] == 'Tech-support'dt.loc[mask, 'age'] = dt.loc[mask, 'age'] + 5" }, { "code": null, "e": 5385, "s": 5366, "text": "or using np.where:" }, { "code": null, "e": 5462, "s": 5385, "text": "dt['age'] = np.where(dt['occupation'] == 'Tech-support', dt.age + 5, dt.age]" }, { "code": null, "e": 5483, "s": 5462, "text": "> vs. in data.table:" }, { "code": null, "e": 5641, "s": 5483, "text": "dt[occupation == 'Tech-support', age := age + 5]# and the ifelse function does just as nicely:dt[, age := ifelse(occupation == 'Tech-support', age + 5, age)]" }, { "code": null, "e": 5930, "s": 5641, "text": "It’s almost like a magic, isn’t it? No more cumbersome repetitive code, and it keeps yourself DRY. You may have noticed the strange operator := in the data.table syntax. This operator is used to assign new values to an existing column, just like using the argument inplace=True in Python." }, { "code": null, "e": 6023, "s": 5930, "text": "4. Renaming columns is a breeze in data.table. If I want to rename occupation column as job:" }, { "code": null, "e": 6052, "s": 6023, "text": "> in base R you might write:" }, { "code": null, "e": 6108, "s": 6052, "text": "colnames(dt)[which(names(dt) == \"occupation\")] <- \"job\"" }, { "code": null, "e": 6125, "s": 6108, "text": "> and in Python:" }, { "code": null, "e": 6171, "s": 6125, "text": "dt = dt.rename(columns={'occupation': 'job'})" }, { "code": null, "e": 6192, "s": 6171, "text": "> vs. in data.table:" }, { "code": null, "e": 6226, "s": 6192, "text": "setnames(dt, 'occupation', 'job')" }, { "code": null, "e": 6348, "s": 6226, "text": "5. What about applying a function to several columns? Suppose you want to multiply capital_gain and capital_loss by 1000:" }, { "code": null, "e": 6361, "s": 6348, "text": "> in base R:" }, { "code": null, "e": 6430, "s": 6361, "text": "apply(dt[,c('capital_gain', 'capital_loss')], 2, function(x) x*1000)" }, { "code": null, "e": 6443, "s": 6430, "text": "> in Python:" }, { "code": null, "e": 6505, "s": 6443, "text": "dt[['capital_gain', 'capital_loss']].apply(lambda x : x*1000)" }, { "code": null, "e": 6526, "s": 6505, "text": "> vs. in data.table:" }, { "code": null, "e": 6609, "s": 6526, "text": "dt[, lapply(.SD, function(x) x*1000), .SDcols = c(\"capital_gain\", \"capital_loss\")]" }, { "code": null, "e": 6795, "s": 6609, "text": "You might find this syntax in data.table is a little quirky, but the .SDcols argument comes in very handy in many cases, and the general form of data.table syntax is preserved this way." }, { "code": null, "e": 7030, "s": 6795, "text": "From a few simple illustrations above, one can see that the code in R data.table is in many cases faster, cleaner and more efficient than in base R and Python. The form of data.table code is very consistent. You only need to remember:" }, { "code": null, "e": 7043, "s": 7030, "text": "DT[i, j, by]" }, { "code": null, "e": 7247, "s": 7043, "text": "As an additional note, the data subsetting with i by keying a data.table even allows faster subsets, joins and sorts, which you can read more about in this documentation, or this very useful cheat sheet." } ]
Google Charts - Basic Timelines Chart
Following is an example of a basic timelines chart. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example. We've used Timeline class to show timelines diagram. //Timeline chart var chart = new google.visualization.Timeline(document.getElementById('container')); googlecharts_timelines_basic.htm <html> <head> <title>Google Charts Tutorial</title> <script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js"> </script> <script type = "text/javascript" src = "https://www.google.com/jsapi"> </script> <script type = "text/javascript"> google.charts.load('current', {packages: ['timeline']}); </script> </head> <body> <div id = "container" style = "width: 550px; height: 400px; margin: 0 auto"> </div> <script language = "JavaScript"> function drawChart() { // Define the chart to be drawn. var data = new google.visualization.DataTable(); data.addColumn({ type: 'string', id: 'President' }); data.addColumn({ type: 'date', id: 'Start' }); data.addColumn({ type: 'date', id: 'End' }); data.addRows([ [ 'Washington', new Date(1789, 3, 30), new Date(1797, 2, 4) ], [ 'Adams', new Date(1797, 2, 4), new Date(1801, 2, 4) ], [ 'Jefferson', new Date(1801, 2, 4), new Date(1809, 2, 4) ]]); var options = { width: '100%', height: '100%' }; // Instantiate and draw the chart. var chart = new google.visualization.Timeline(document.getElementById('container')); chart.draw(data, options); } google.charts.setOnLoadCallback(drawChart); </script> </body> </html> Verify the result. Print Add Notes Bookmark this page
[ { "code": null, "e": 2457, "s": 2261, "text": "Following is an example of a basic timelines chart. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example." }, { "code": null, "e": 2510, "s": 2457, "text": "We've used Timeline class to show timelines diagram." }, { "code": null, "e": 2613, "s": 2510, "text": "//Timeline chart\nvar chart = new google.visualization.Timeline(document.getElementById('container'));\n" }, { "code": null, "e": 2646, "s": 2613, "text": "googlecharts_timelines_basic.htm" }, { "code": null, "e": 4177, "s": 2646, "text": "<html>\n <head>\n <title>Google Charts Tutorial</title>\n <script type = \"text/javascript\" src = \"https://www.gstatic.com/charts/loader.js\">\n </script>\n <script type = \"text/javascript\" src = \"https://www.google.com/jsapi\">\n </script>\n <script type = \"text/javascript\">\n google.charts.load('current', {packages: ['timeline']}); \n </script>\n </head>\n \n <body>\n <div id = \"container\" style = \"width: 550px; height: 400px; margin: 0 auto\">\n </div>\n <script language = \"JavaScript\">\n function drawChart() {\n // Define the chart to be drawn.\n var data = new google.visualization.DataTable();\n data.addColumn({ type: 'string', id: 'President' });\n data.addColumn({ type: 'date', id: 'Start' });\n data.addColumn({ type: 'date', id: 'End' });\n data.addRows([\n [ 'Washington', new Date(1789, 3, 30), new Date(1797, 2, 4) ],\n [ 'Adams', new Date(1797, 2, 4), new Date(1801, 2, 4) ],\n [ 'Jefferson', new Date(1801, 2, 4), new Date(1809, 2, 4) ]]);\n\n var options = { \n width: '100%', \n height: '100%'\n };\n \n // Instantiate and draw the chart.\n var chart = new google.visualization.Timeline(document.getElementById('container'));\n chart.draw(data, options);\n }\n google.charts.setOnLoadCallback(drawChart);\n </script>\n </body>\n</html>" }, { "code": null, "e": 4196, "s": 4177, "text": "Verify the result." }, { "code": null, "e": 4203, "s": 4196, "text": " Print" }, { "code": null, "e": 4214, "s": 4203, "text": " Add Notes" } ]
Python - Get Indices of Even Elements from list - GeeksforGeeks
23 Jan, 2020 Sometimes, while working with Python lists, we can have a problem in which we wish to find Even elements. This task can occur in many domains such as web development and while working with Databases. We might sometimes, require to just find the indices of them. Let’s discuss certain way to find indices of Even elements. Method #1 : Using loopThis is brute force method in which this task can be performed. In this, we check for even element in list and append its index accordingly. # Python3 code to demonstrate working of# Even Elements indices# using loop # initialize listtest_list = [5, 6, 10, 4, 7, 1, 19] # printing original listprint("The original list is : " + str(test_list)) # Even Elements indices# using loopres = []for idx, ele in enumerate(test_list): if ele % 2 == 0: res.append(idx) # printing resultprint("Indices list Even elements is : " + str(res)) The original list is : [5, 6, 10, 4, 7, 1, 19] Indices list Even elements is : [1, 2, 3] Method #2 : Using list comprehensionThis is the shorthand by which this task can be performed. This method works in similar way as the above method. The difference is that it’s a one liner. # Python3 code to demonstrate working of# Even Elements indices# using list comprehension # initialize listtest_list = [5, 6, 10, 4, 7, 1, 19] # printing original listprint("The original list is : " + str(test_list)) # Even Elements indices# using list comprehensionres = [idx for idx, ele in enumerate(test_list) if ele % 2 == 0] # printing resultprint("Indices list Even elements is : " + str(res)) The original list is : [5, 6, 10, 4, 7, 1, 19] Indices list Even elements is : [1, 2, 3] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python program to check whether a number is Prime or not
[ { "code": null, "e": 24041, "s": 24013, "text": "\n23 Jan, 2020" }, { "code": null, "e": 24363, "s": 24041, "text": "Sometimes, while working with Python lists, we can have a problem in which we wish to find Even elements. This task can occur in many domains such as web development and while working with Databases. We might sometimes, require to just find the indices of them. Let’s discuss certain way to find indices of Even elements." }, { "code": null, "e": 24526, "s": 24363, "text": "Method #1 : Using loopThis is brute force method in which this task can be performed. In this, we check for even element in list and append its index accordingly." }, { "code": "# Python3 code to demonstrate working of# Even Elements indices# using loop # initialize listtest_list = [5, 6, 10, 4, 7, 1, 19] # printing original listprint(\"The original list is : \" + str(test_list)) # Even Elements indices# using loopres = []for idx, ele in enumerate(test_list): if ele % 2 == 0: res.append(idx) # printing resultprint(\"Indices list Even elements is : \" + str(res))", "e": 24935, "s": 24526, "text": null }, { "code": null, "e": 25025, "s": 24935, "text": "The original list is : [5, 6, 10, 4, 7, 1, 19]\nIndices list Even elements is : [1, 2, 3]\n" }, { "code": null, "e": 25217, "s": 25027, "text": "Method #2 : Using list comprehensionThis is the shorthand by which this task can be performed. This method works in similar way as the above method. The difference is that it’s a one liner." }, { "code": "# Python3 code to demonstrate working of# Even Elements indices# using list comprehension # initialize listtest_list = [5, 6, 10, 4, 7, 1, 19] # printing original listprint(\"The original list is : \" + str(test_list)) # Even Elements indices# using list comprehensionres = [idx for idx, ele in enumerate(test_list) if ele % 2 == 0] # printing resultprint(\"Indices list Even elements is : \" + str(res))", "e": 25630, "s": 25217, "text": null }, { "code": null, "e": 25720, "s": 25630, "text": "The original list is : [5, 6, 10, 4, 7, 1, 19]\nIndices list Even elements is : [1, 2, 3]\n" }, { "code": null, "e": 25741, "s": 25720, "text": "Python list-programs" }, { "code": null, "e": 25748, "s": 25741, "text": "Python" }, { "code": null, "e": 25764, "s": 25748, "text": "Python Programs" }, { "code": null, "e": 25862, "s": 25764, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25871, "s": 25862, "text": "Comments" }, { "code": null, "e": 25884, "s": 25871, "text": "Old Comments" }, { "code": null, "e": 25902, "s": 25884, "text": "Python Dictionary" }, { "code": null, "e": 25937, "s": 25902, "text": "Read a file line by line in Python" }, { "code": null, "e": 25969, "s": 25937, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26011, "s": 25969, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26037, "s": 26011, "text": "Python String | replace()" }, { "code": null, "e": 26080, "s": 26037, "text": "Python program to convert a list to string" }, { "code": null, "e": 26102, "s": 26080, "text": "Defaultdict in Python" }, { "code": null, "e": 26141, "s": 26102, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26187, "s": 26141, "text": "Python | Split string into list of characters" } ]
Haskell - Function Composition
Function Composition is the process of using the output of one function as an input of another function. It will be better if we learn the mathematics behind composition. In mathematics, composition is denoted by f{g(x)} where g() is a function and its output in used as an input of another function, that is, f(). Function composition can be implemented using any two functions, provided the output type of one function matches with the input type of the second function. We use the dot operator (.) to implement function composition in Haskell. Take a look at the following example code. Here, we have used function composition to calculate whether an input number is even or odd. eveno :: Int -> Bool noto :: Bool -> String eveno x = if x `rem` 2 == 0 then True else False noto x = if x == True then "This is an even Number" else "This is an ODD number" main = do putStrLn "Example of Haskell Function composition" print ((noto.eveno)(16)) Here, in the main function, we are calling two functions, noto and eveno, simultaneously. The compiler will first call the function "eveno()" with 16 as an argument. Thereafter, the compiler will use the output of the eveno method as an input of noto() method. Its output would be as follows − Example of Haskell Function composition "This is an even Number" Since we are supplying the number 16 as the input (which is an even number), the eveno() function returns true, which becomes the input for the noto() function and returns the output: "This is an even Number". Print Add Notes Bookmark this page
[ { "code": null, "e": 2230, "s": 1915, "text": "Function Composition is the process of using the output of one function as an input of another function. It will be better if we learn the mathematics behind composition. In mathematics, composition is denoted by f{g(x)} where g() is a function and its output in used as an input of another function, that is, f()." }, { "code": null, "e": 2462, "s": 2230, "text": "Function composition can be implemented using any two functions, provided the output type of one function matches with the input type of the second function. We use the dot operator (.) to implement function composition in Haskell." }, { "code": null, "e": 2598, "s": 2462, "text": "Take a look at the following example code. Here, we have used function composition to calculate whether an input number is even or odd." }, { "code": null, "e": 2883, "s": 2598, "text": "eveno :: Int -> Bool \nnoto :: Bool -> String \n\neveno x = if x `rem` 2 == 0 \n then True \nelse False \nnoto x = if x == True \n then \"This is an even Number\" \nelse \"This is an ODD number\" \n\nmain = do \n putStrLn \"Example of Haskell Function composition\" \n print ((noto.eveno)(16))" }, { "code": null, "e": 3144, "s": 2883, "text": "Here, in the main function, we are calling two functions, noto and eveno, simultaneously. The compiler will first call the function \"eveno()\" with 16 as an argument. Thereafter, the compiler will use the output of the eveno method as an input of noto() method." }, { "code": null, "e": 3177, "s": 3144, "text": "Its output would be as follows −" }, { "code": null, "e": 3259, "s": 3177, "text": "Example of Haskell Function composition \n\"This is an even Number\"\n" }, { "code": null, "e": 3469, "s": 3259, "text": "Since we are supplying the number 16 as the input (which is an even number), the eveno() function returns true, which becomes the input for the noto() function and returns the output: \"This is an even Number\"." }, { "code": null, "e": 3476, "s": 3469, "text": " Print" }, { "code": null, "e": 3487, "s": 3476, "text": " Add Notes" } ]
RPAD() Function in MySQL - GeeksforGeeks
21 Jun, 2021 RPAD() function in MySQL is used to pad or add a string to the right side of the original string. Syntax : RPAD(str, len, padstr) Parameter : This function accepts three parameter as mentioned above and described below : str : The actual string which is to be padded. If the length of the original string is larger than the len parameter, this function removes the overfloating characters from string. len : This is the length of a final string after the right padding. padstr : String that to be added to the right side of the Original Str. Returns : It returns a new string of length len after padding. Example-1 : Applying RPAD() Function to a string to get a new padded string. SELECT RPAD("geeksforgeeks", 20, "*") AS RightPaddedString; Output : Example-2 : Applying RPAD() Function to a string when the original string is larger than the len parameter. SELECT RPAD("geeksforgeeks", 10, "*") AS RightPaddedString; Output : Example-3 : Applying RPAD() Function to a string column in a table : Table – Student_Details : SELECT RPAD(Name, 15, "#") AS RightPadStudentName FROM Student_Details; Output : abhishek0719kadiyan mysql DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Second Normal Form (2NF) Introduction of Relational Algebra in DBMS What is Temporary Table in SQL? Types of Functional dependencies in DBMS Difference between Where and Having Clause in SQL SQL | DDL, DQL, DML, DCL and TCL Commands How to find Nth highest salary from a table SQL | ALTER (RENAME) How to Update Multiple Columns in Single Update Statement in SQL? What is Temporary Table in SQL?
[ { "code": null, "e": 23913, "s": 23885, "text": "\n21 Jun, 2021" }, { "code": null, "e": 24012, "s": 23913, "text": "RPAD() function in MySQL is used to pad or add a string to the right side of the original string. " }, { "code": null, "e": 24023, "s": 24012, "text": "Syntax : " }, { "code": null, "e": 24046, "s": 24023, "text": "RPAD(str, len, padstr)" }, { "code": null, "e": 24139, "s": 24046, "text": "Parameter : This function accepts three parameter as mentioned above and described below : " }, { "code": null, "e": 24322, "s": 24139, "text": "str : The actual string which is to be padded. If the length of the original string is larger than the len parameter, this function removes the overfloating characters from string. " }, { "code": null, "e": 24394, "s": 24324, "text": "len : This is the length of a final string after the right padding. " }, { "code": null, "e": 24470, "s": 24396, "text": "padstr : String that to be added to the right side of the Original Str. " }, { "code": null, "e": 24534, "s": 24470, "text": "Returns : It returns a new string of length len after padding. " }, { "code": null, "e": 24613, "s": 24534, "text": "Example-1 : Applying RPAD() Function to a string to get a new padded string. " }, { "code": null, "e": 24673, "s": 24613, "text": "SELECT RPAD(\"geeksforgeeks\", 20, \"*\") AS RightPaddedString;" }, { "code": null, "e": 24683, "s": 24673, "text": "Output : " }, { "code": null, "e": 24795, "s": 24685, "text": "Example-2 : Applying RPAD() Function to a string when the original string is larger than the len parameter. " }, { "code": null, "e": 24855, "s": 24795, "text": "SELECT RPAD(\"geeksforgeeks\", 10, \"*\") AS RightPaddedString;" }, { "code": null, "e": 24865, "s": 24855, "text": "Output : " }, { "code": null, "e": 24937, "s": 24867, "text": "Example-3 : Applying RPAD() Function to a string column in a table : " }, { "code": null, "e": 24964, "s": 24937, "text": "Table – Student_Details : " }, { "code": null, "e": 25040, "s": 24968, "text": "SELECT RPAD(Name, 15, \"#\") AS RightPadStudentName\nFROM Student_Details;" }, { "code": null, "e": 25050, "s": 25040, "text": "Output : " }, { "code": null, "e": 25074, "s": 25054, "text": "abhishek0719kadiyan" }, { "code": null, "e": 25080, "s": 25074, "text": "mysql" }, { "code": null, "e": 25085, "s": 25080, "text": "DBMS" }, { "code": null, "e": 25089, "s": 25085, "text": "SQL" }, { "code": null, "e": 25094, "s": 25089, "text": "DBMS" }, { "code": null, "e": 25098, "s": 25094, "text": "SQL" }, { "code": null, "e": 25196, "s": 25098, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25205, "s": 25196, "text": "Comments" }, { "code": null, "e": 25218, "s": 25205, "text": "Old Comments" }, { "code": null, "e": 25243, "s": 25218, "text": "Second Normal Form (2NF)" }, { "code": null, "e": 25286, "s": 25243, "text": "Introduction of Relational Algebra in DBMS" }, { "code": null, "e": 25318, "s": 25286, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 25359, "s": 25318, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 25409, "s": 25359, "text": "Difference between Where and Having Clause in SQL" }, { "code": null, "e": 25451, "s": 25409, "text": "SQL | DDL, DQL, DML, DCL and TCL Commands" }, { "code": null, "e": 25495, "s": 25451, "text": "How to find Nth highest salary from a table" }, { "code": null, "e": 25516, "s": 25495, "text": "SQL | ALTER (RENAME)" }, { "code": null, "e": 25582, "s": 25516, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" } ]
How does MySQL handle out of range numeric values?
Handling of MySQL numeric value that is out of allowed range of column data type depends upon the SQL mode in following ways − (A) Enabled SQL strict mode - When strict SQL mode is enabled, MySQL returns the error on entering the put-of-range value. In this case, the insertion of some or all the values got failed. For example, we have created a table with two columns having TINYINT and UNSIGNED TINYINT as their data types on columns. mysql> Create table counting(Range1 Tinyint, Range2 Tinyint Unsigned); Query OK, 0 rows affected (0.14 sec) Now with the help of the following command, we enabled the strict SQL mode mysql> Set SQL_MODE ='traditional'; Query OK, 0 rows affected (0.00 sec) Now, if we will try to insert the out-of-range values into the columns, MySQL reflects the error and both the insertions failed which can be checked by the query below − mysql> Insert into Counting(Range1, Range2) Values(256,256); ERROR 1264 (22003): Out of range value for column 'Range1' at row 1 mysql> Select * from counting; Empty set (0.00 sec) (B) Disabled SQL strict mode - When the restrictive SQL mode is disabled, the value is clipped by MySQL up to the suitable endpoint of that column data type and accumulate the resulting value. MySQL reflects warnings which are the result of column-assignment conversion that occurs due to clipping. For example, if we will insert the values in the column after disabling the SQL strict mode, MySQL will reflect the warnings and stores the values after trimming them up to the suitable end-point. It can be understood with the queries below − mysql> Set SQL_MODE = ''; Query OK, 0 rows affected (0.00 sec) mysql> Insert Into Counting(Range1,Range2) values (256,256); Query OK, 1 row affected, 2 warnings (0.02 sec) mysql> Show Warnings; +---------+------+-------------------------------------------------+ | Level | Code | Message | +---------+------+-------------------------------------------------+ | Warning | 1264 | Out of range value for column 'Range1' at row 1 | | Warning | 1264 | Out of range value for column 'Range2' at row 1 | +---------+------+-------------------------------------------------+ 2 rows in set (0.00 sec) mysql> Select * from Counting; +--------+--------+ | Range1 | Range2 | +--------+--------+ | 127 | 255 | +--------+--------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1189, "s": 1062, "text": "Handling of MySQL numeric value that is out of allowed range of column data type depends upon the SQL mode in following ways −" }, { "code": null, "e": 1378, "s": 1189, "text": "(A) Enabled SQL strict mode - When strict SQL mode is enabled, MySQL returns the error on entering the put-of-range value. In this case, the insertion of some or all the values got failed." }, { "code": null, "e": 1500, "s": 1378, "text": "For example, we have created a table with two columns having TINYINT and UNSIGNED TINYINT as their data types on columns." }, { "code": null, "e": 1608, "s": 1500, "text": "mysql> Create table counting(Range1 Tinyint, Range2 Tinyint Unsigned);\nQuery OK, 0 rows affected (0.14 sec)" }, { "code": null, "e": 1683, "s": 1608, "text": "Now with the help of the following command, we enabled the strict SQL mode" }, { "code": null, "e": 1756, "s": 1683, "text": "mysql> Set SQL_MODE ='traditional';\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 1926, "s": 1756, "text": "Now, if we will try to insert the out-of-range values into the columns, MySQL reflects the error and both the insertions failed which can be checked by the query below −" }, { "code": null, "e": 2108, "s": 1926, "text": "mysql> Insert into Counting(Range1, Range2) Values(256,256);\nERROR 1264 (22003): Out of range value for column 'Range1' at row 1\n\nmysql> Select * from counting;\nEmpty set (0.00 sec)" }, { "code": null, "e": 2408, "s": 2108, "text": "(B) Disabled SQL strict mode - When the restrictive SQL mode is disabled, the value is clipped by MySQL up to the suitable endpoint of that column data type and accumulate the resulting value. MySQL reflects warnings which are the result of column-assignment conversion that occurs due to clipping." }, { "code": null, "e": 2651, "s": 2408, "text": "For example, if we will insert the values in the column after disabling the SQL strict mode, MySQL will reflect the warnings and stores the values after trimming them up to the suitable end-point. It can be understood with the queries below −" }, { "code": null, "e": 3442, "s": 2651, "text": "mysql> Set SQL_MODE = '';\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> Insert Into Counting(Range1,Range2) values (256,256);\nQuery OK, 1 row affected, 2 warnings (0.02 sec)\n\nmysql> Show Warnings;\n+---------+------+-------------------------------------------------+\n| Level | Code | Message |\n+---------+------+-------------------------------------------------+\n| Warning | 1264 | Out of range value for column 'Range1' at row 1 |\n| Warning | 1264 | Out of range value for column 'Range2' at row 1 |\n+---------+------+-------------------------------------------------+\n2 rows in set (0.00 sec)\n\nmysql> Select * from Counting;\n+--------+--------+\n| Range1 | Range2 |\n+--------+--------+\n| 127 | 255 |\n+--------+--------+\n1 row in set (0.00 sec)" } ]
Cassandra - Shell Commands
Cassandra provides documented shell commands in addition to CQL commands. Given below are the Cassandra documented shell commands. The HELP command displays a synopsis and a brief description of all cqlsh commands. Given below is the usage of help command. cqlsh> help Documented shell commands: =========================== CAPTURE COPY DESCRIBE EXPAND PAGING SOURCE CONSISTENCY DESC EXIT HELP SHOW TRACING. CQL help topics: ================ ALTER CREATE_TABLE_OPTIONS SELECT ALTER_ADD CREATE_TABLE_TYPES SELECT_COLUMNFAMILY ALTER_ALTER CREATE_USER SELECT_EXPR ALTER_DROP DELETE SELECT_LIMIT ALTER_RENAME DELETE_COLUMNS SELECT_TABLE This command captures the output of a command and adds it to a file. For example, take a look at the following code that captures the output to a file named Outputfile. cqlsh> CAPTURE '/home/hadoop/CassandraProgs/Outputfile' When we type any command in the terminal, the output will be captured by the file given. Given below is the command used and the snapshot of the output file. cqlsh:tutorialspoint> select * from emp; You can turn capturing off using the following command. cqlsh:tutorialspoint> capture off; This command shows the current consistency level, or sets a new consistency level. cqlsh:tutorialspoint> CONSISTENCY Current consistency level is 1. This command copies data to and from Cassandra to a file. Given below is an example to copy the table named emp to the file myfile. cqlsh:tutorialspoint> COPY emp (emp_id, emp_city, emp_name, emp_phone,emp_sal) TO ‘myfile’; 4 rows exported in 0.034 seconds. If you open and verify the file given, you can find the copied data as shown below. This command describes the current cluster of Cassandra and its objects. The variants of this command are explained below. Describe cluster − This command provides information about the cluster. cqlsh:tutorialspoint> describe cluster; Cluster: Test Cluster Partitioner: Murmur3Partitioner Range ownership: -658380912249644557 [127.0.0.1] -2833890865268921414 [127.0.0.1] -6792159006375935836 [127.0.0.1] Describe Keyspaces − This command lists all the keyspaces in a cluster. Given below is the usage of this command. cqlsh:tutorialspoint> describe keyspaces; system_traces system tp tutorialspoint Describe tables − This command lists all the tables in a keyspace. Given below is the usage of this command. cqlsh:tutorialspoint> describe tables; emp Describe table − This command provides the description of a table. Given below is the usage of this command. cqlsh:tutorialspoint> describe table emp; CREATE TABLE tutorialspoint.emp ( emp_id int PRIMARY KEY, emp_city text, emp_name text, emp_phone varint, emp_sal varint ) WITH bloom_filter_fp_chance = 0.01 AND caching = '{"keys":"ALL", "rows_per_partition":"NONE"}' AND comment = '' AND compaction = {'min_threshold': '4', 'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold': '32'} AND compression = {'sstable_compression': 'org.apache.cassandra.io.compress.LZ4Compressor'} AND dclocal_read_repair_chance = 0.1 AND default_time_to_live = 0 AND gc_grace_seconds = 864000 AND max_index_interval = 2048 AND memtable_flush_period_in_ms = 0 AND min_index_interval = 128 AND read_repair_chance = 0.0 AND speculative_retry = '99.0PERCENTILE'; CREATE INDEX emp_emp_sal_idx ON tutorialspoint.emp (emp_sal); This command is used to describe a user-defined data type. Given below is the usage of this command. cqlsh:tutorialspoint> describe type card_details; CREATE TYPE tutorialspoint.card_details ( num int, pin int, name text, cvv int, phone set<int>, mail text ); This command lists all the user-defined data types. Given below is the usage of this command. Assume there are two user-defined data types: card and card_details. cqlsh:tutorialspoint> DESCRIBE TYPES; card_details card This command is used to expand the output. Before using this command, you have to turn the expand command on. Given below is the usage of this command. cqlsh:tutorialspoint> expand on; cqlsh:tutorialspoint> select * from emp; @ Row 1 -----------+------------ emp_id | 1 emp_city | Hyderabad emp_name | ram emp_phone | 9848022338 emp_sal | 50000 @ Row 2 -----------+------------ emp_id | 2 emp_city | Delhi emp_name | robin emp_phone | 9848022339 emp_sal | 50000 @ Row 3 -----------+------------ emp_id | 4 emp_city | Pune emp_name | rajeev emp_phone | 9848022331 emp_sal | 30000 @ Row 4 -----------+------------ emp_id | 3 emp_city | Chennai emp_name | rahman emp_phone | 9848022330 emp_sal | 50000 (4 rows) Note − You can turn the expand option off using the following command. cqlsh:tutorialspoint> expand off; Disabled Expanded output. This command is used to terminate the cql shell. This command displays the details of current cqlsh session such as Cassandra version, host, or data type assumptions. Given below is the usage of this command. cqlsh:tutorialspoint> show host; Connected to Test Cluster at 127.0.0.1:9042. cqlsh:tutorialspoint> show version; [cqlsh 5.0.1 | Cassandra 2.1.2 | CQL spec 3.2.0 | Native protocol v3] Using this command, you can execute the commands in a file. Suppose our input file is as follows − Then you can execute the file containing the commands as shown below. cqlsh:tutorialspoint> source '/home/hadoop/CassandraProgs/inputfile'; emp_id | emp_city | emp_name | emp_phone | emp_sal --------+-----------+----------+------------+--------- 1 | Hyderabad | ram | 9848022338 | 50000 2 | Delhi | robin | 9848022339 | 50000 3 | Pune | rajeev | 9848022331 | 30000 4 | Chennai | rahman | 9848022330 | 50000 (4 rows) 27 Lectures 2 hours Navdeep Kaur 34 Lectures 1.5 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2418, "s": 2287, "text": "Cassandra provides documented shell commands in addition to CQL commands. Given below are the Cassandra documented shell commands." }, { "code": null, "e": 2544, "s": 2418, "text": "The HELP command displays a synopsis and a brief description of all cqlsh commands. Given below is the usage of help command." }, { "code": null, "e": 3013, "s": 2544, "text": "cqlsh> help\n\nDocumented shell commands:\n===========================\nCAPTURE COPY DESCRIBE EXPAND PAGING SOURCE\nCONSISTENCY DESC EXIT HELP SHOW TRACING.\n\nCQL help topics:\n================\nALTER CREATE_TABLE_OPTIONS SELECT\nALTER_ADD CREATE_TABLE_TYPES SELECT_COLUMNFAMILY\nALTER_ALTER CREATE_USER SELECT_EXPR\nALTER_DROP DELETE SELECT_LIMIT\nALTER_RENAME DELETE_COLUMNS SELECT_TABLE \n" }, { "code": null, "e": 3182, "s": 3013, "text": "This command captures the output of a command and adds it to a file. For example, take a look at the following code that captures the output to a file named Outputfile." }, { "code": null, "e": 3239, "s": 3182, "text": "cqlsh> CAPTURE '/home/hadoop/CassandraProgs/Outputfile'\n" }, { "code": null, "e": 3397, "s": 3239, "text": "When we type any command in the terminal, the output will be captured by the\nfile given. Given below is the command used and the snapshot of the output file." }, { "code": null, "e": 3439, "s": 3397, "text": "cqlsh:tutorialspoint> select * from emp;\n" }, { "code": null, "e": 3495, "s": 3439, "text": "You can turn capturing off using the following command." }, { "code": null, "e": 3531, "s": 3495, "text": "cqlsh:tutorialspoint> capture off;\n" }, { "code": null, "e": 3614, "s": 3531, "text": "This command shows the current consistency level, or sets a new consistency level." }, { "code": null, "e": 3681, "s": 3614, "text": "cqlsh:tutorialspoint> CONSISTENCY\nCurrent consistency level is 1.\n" }, { "code": null, "e": 3813, "s": 3681, "text": "This command copies data to and from Cassandra to a file. Given below is an example to copy the table named emp to the file myfile." }, { "code": null, "e": 3940, "s": 3813, "text": "cqlsh:tutorialspoint> COPY emp (emp_id, emp_city, emp_name, emp_phone,emp_sal) TO ‘myfile’;\n4 rows exported in 0.034 seconds.\n" }, { "code": null, "e": 4024, "s": 3940, "text": "If you open and verify the file given, you can find the copied data as shown below." }, { "code": null, "e": 4147, "s": 4024, "text": "This command describes the current cluster of Cassandra and its objects. The variants of this command are explained below." }, { "code": null, "e": 4219, "s": 4147, "text": "Describe cluster − This command provides information about the cluster." }, { "code": null, "e": 4486, "s": 4219, "text": "cqlsh:tutorialspoint> describe cluster;\n\nCluster: Test Cluster\nPartitioner: Murmur3Partitioner\n\nRange ownership:\n -658380912249644557 [127.0.0.1]\n -2833890865268921414 [127.0.0.1]\n -6792159006375935836 [127.0.0.1] \n" }, { "code": null, "e": 4600, "s": 4486, "text": "Describe Keyspaces − This command lists all the keyspaces in a cluster. Given below is the usage of this command." }, { "code": null, "e": 4683, "s": 4600, "text": "cqlsh:tutorialspoint> describe keyspaces;\n\nsystem_traces system tp tutorialspoint\n" }, { "code": null, "e": 4792, "s": 4683, "text": "Describe tables − This command lists all the tables in a keyspace. Given below is the usage of this command." }, { "code": null, "e": 4836, "s": 4792, "text": "cqlsh:tutorialspoint> describe tables;\nemp\n" }, { "code": null, "e": 4945, "s": 4836, "text": "Describe table − This command provides the description of a table. Given below is the usage of this command." }, { "code": null, "e": 5843, "s": 4945, "text": "cqlsh:tutorialspoint> describe table emp;\n\nCREATE TABLE tutorialspoint.emp (\n emp_id int PRIMARY KEY,\n emp_city text,\n emp_name text,\n emp_phone varint,\n emp_sal varint\n) WITH bloom_filter_fp_chance = 0.01\n AND caching = '{\"keys\":\"ALL\", \"rows_per_partition\":\"NONE\"}'\n AND comment = ''\n AND compaction = {'min_threshold': '4', 'class':\n 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy',\n 'max_threshold': '32'}\n\t\n AND compression = {'sstable_compression':\n 'org.apache.cassandra.io.compress.LZ4Compressor'}\n\t\n AND dclocal_read_repair_chance = 0.1\n AND default_time_to_live = 0\n AND gc_grace_seconds = 864000\n AND max_index_interval = 2048\n AND memtable_flush_period_in_ms = 0\n AND min_index_interval = 128\n AND read_repair_chance = 0.0\n AND speculative_retry = '99.0PERCENTILE';\nCREATE INDEX emp_emp_sal_idx ON tutorialspoint.emp (emp_sal);\n" }, { "code": null, "e": 5944, "s": 5843, "text": "This command is used to describe a user-defined data type. Given below is the\nusage of this command." }, { "code": null, "e": 6123, "s": 5944, "text": "cqlsh:tutorialspoint> describe type card_details;\n\nCREATE TYPE tutorialspoint.card_details (\n num int,\n pin int,\n name text,\n cvv int,\n phone set<int>,\n mail text\n);\n" }, { "code": null, "e": 6286, "s": 6123, "text": "This command lists all the user-defined data types. Given below is the usage of this command. Assume there are two user-defined data types: card and card_details." }, { "code": null, "e": 6344, "s": 6286, "text": "cqlsh:tutorialspoint> DESCRIBE TYPES;\n\ncard_details card\n" }, { "code": null, "e": 6496, "s": 6344, "text": "This command is used to expand the output. Before using this command, you have to turn the expand command on. Given below is the usage of this command." }, { "code": null, "e": 7111, "s": 6496, "text": "cqlsh:tutorialspoint> expand on;\ncqlsh:tutorialspoint> select * from emp;\n\n@ Row 1\n-----------+------------\n emp_id | 1\n emp_city | Hyderabad\n emp_name | ram\n emp_phone | 9848022338\n emp_sal | 50000\n \n@ Row 2\n-----------+------------\n emp_id | 2\n emp_city | Delhi\n emp_name | robin\n emp_phone | 9848022339\n emp_sal | 50000\n \n@ Row 3\n-----------+------------\n emp_id | 4\n emp_city | Pune\n emp_name | rajeev\n emp_phone | 9848022331\n emp_sal | 30000\n \n@ Row 4\n-----------+------------\n emp_id | 3\n emp_city | Chennai\n emp_name | rahman\n emp_phone | 9848022330\n emp_sal | 50000\n(4 rows)\n" }, { "code": null, "e": 7182, "s": 7111, "text": "Note − You can turn the expand option off using the following command." }, { "code": null, "e": 7243, "s": 7182, "text": "cqlsh:tutorialspoint> expand off;\nDisabled Expanded output.\n" }, { "code": null, "e": 7292, "s": 7243, "text": "This command is used to terminate the cql shell." }, { "code": null, "e": 7452, "s": 7292, "text": "This command displays the details of current cqlsh session such as Cassandra version, host, or data type assumptions. Given below is the usage of this command." }, { "code": null, "e": 7638, "s": 7452, "text": "cqlsh:tutorialspoint> show host;\nConnected to Test Cluster at 127.0.0.1:9042.\n\ncqlsh:tutorialspoint> show version;\n[cqlsh 5.0.1 | Cassandra 2.1.2 | CQL spec 3.2.0 | Native protocol v3]\n" }, { "code": null, "e": 7737, "s": 7638, "text": "Using this command, you can execute the commands in a file. Suppose our input file is as follows −" }, { "code": null, "e": 7807, "s": 7737, "text": "Then you can execute the file containing the commands as shown below." }, { "code": null, "e": 8205, "s": 7807, "text": "cqlsh:tutorialspoint> source '/home/hadoop/CassandraProgs/inputfile';\n\n emp_id | emp_city | emp_name | emp_phone | emp_sal\n--------+-----------+----------+------------+---------\n 1 | Hyderabad | ram | 9848022338 | 50000\n 2 | Delhi | robin | 9848022339 | 50000\n 3 | Pune | rajeev | 9848022331 | 30000\n 4 | Chennai | rahman | 9848022330 | 50000\n(4 rows)\n" }, { "code": null, "e": 8238, "s": 8205, "text": "\n 27 Lectures \n 2 hours \n" }, { "code": null, "e": 8252, "s": 8238, "text": " Navdeep Kaur" }, { "code": null, "e": 8287, "s": 8252, "text": "\n 34 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8305, "s": 8287, "text": " Bigdata Engineer" }, { "code": null, "e": 8312, "s": 8305, "text": " Print" }, { "code": null, "e": 8323, "s": 8312, "text": " Add Notes" } ]
Different Types of Normalization in Tensorflow | by Vardan Agarwal | Towards Data Science
When normalization was introduced in deep learning, it was the next big thing and improved performances considerably. Getting it right can be a crucial factor for your model. Ever had those questions whatever the hell is batch normalization and how does it improve performances. Also are there any substitutes for it? If you like me had these questions but never bothered and just used it for the sake of it in your models this article will clear it up. Batch Normalization Group Normalization Instance Normalization Layer Normalization Weight Normalization Implementation in Tensorflow The most widely used technique providing wonders to performance. What does it do? Well, Batch normalization is a normalization method that normalizes activations in a network across the mini-batch. It computes the mean and variance for each feature in a mini-batch. It then subtracts the mean and divides the feature by its mini-batch standard deviation. It also has two additional learnable parameters, the mean and magnitude of the activations. These are used to avoid the problems associated with having zero mean and unit standard deviation. All this seems simple enough but why did have such a big impact on the community and how does it do this? The answer is not figured out completely. Some say it improves the internal covariate shift while some disagree. But we do know that it makes the loss surface smoother and the activations of one layer can be controlled independently from other layers and prevent weights from flying all over the place. So it is so great why do we need others? When the batch size is small the mean/variance of the mini-batch can be far away from the global mean/variance. This introduces a lot of noise. If the batch size is 1 then batch normalization cannot be applied and it does not work in RNNs. It computes the mean and standard deviation over groups of channels for each training example. So it is essentially batch size independent. Group normalization matched the performance of batch normalization with a batch size of 32 on the ImageNet dataset and outperformed it on smaller batch sizes. When the image resolution is high and a big batch size can’t be used because of memory constraints group normalization is a very effective technique. Instance normalization and layer normalization (which we will discuss later) are both inferior to batch normalization for image recognition tasks, but not group normalization. Layer normalization considers all the channels while instance normalization considers only a single channel which leads to their downfall. All channels are not equally important, as the center of the image to its edges, while not being completely independent of each other. So technically group normalization combines the best of both worlds and leaves out their drawbacks. As discussed earlier it computes the mean/variance across each channel of each training image. It is used in style transfer applications and has also been suggested as a replacement to batch normalization in GANs. While batch normalization normalizes the inputs across the batch dimensions, layer normalization normalizes the inputs across the feature maps. Again like the group and instance normalization it works on a single image at a time, i.e. its mean/variance is calculated independent of other examples. Experimental results show that it performs well on RNNs. I think the best way to describe it would be to quote its papers abstract. By reparameterizing the weights in this way we improve the conditioning of the optimization problem and we speed up convergence of stochastic gradient descent. Our reparameterization is inspired by batch normalization but does not introduce any dependencies between the examples in a minibatch. This means that our method can also be applied successfully to recurrent models such as LSTMs and to noise-sensitive applications such as deep reinforcement learning or generative models, for which batch normalization is less well suited. Although our method is much simpler, it still provides much of the speed-up of full batch normalization. In addition, the computational overhead of our method is lower, permitting more optimization steps to be taken in the same amount of time. What’s the use of understanding the theory if we can’t implement it? So let’s see how to implement them in Tensorflow. Only batch normalization can be implemented using stable Tensorflow. For others, we need to install Tensorflow add-ons. pip install -q --no-deps tensorflow-addons~=0.7 Let’s create a model and add these different normalization layers. import tensorflow as tfimport tensorflow_addons as tfa#Batch Normalizationmodel.add(tf.keras.layers.BatchNormalization())#Group Normalizationmodel.add(tf.keras.layers.Conv2D(32, kernel_size=(3, 3), activation='relu'))model.add(tfa.layers.GroupNormalization(groups=8, axis=3))#Instance Normalizationmodel.add(tfa.layers.InstanceNormalization(axis=3, center=True, scale=True, beta_initializer="random_uniform", gamma_initializer="random_uniform"))#Layer Normalizationmodel.add(tf.keras.layers.LayerNormalization(axis=1 , center=True , scale=True))#Weight Normalizationmodel.add(tfa.layers.WeightNormalization(tf.keras.layers.Conv2D(32, kernel_size=(3, 3), activation='relu'))) When assigning the number of groups in group normalization make sure its value is a perfect divisor of the number of feature maps present at that time. In the above code that is 32 so its divisors can be used to denote the number of groups to divide into. Now we know how to use them why not try it out. We will use the MNIST dataset with a simple network architecture. model = tf.keras.models.Sequential()model.add(tf.keras.layers.Conv2D(16, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1)))model.add(tf.keras.layers.Conv2D(32, kernel_size=(3, 3), activation='relu'))#ADD a normalization layer heremodel.add(tf.keras.layers.Conv2D(32, kernel_size=(3, 3), activation='relu'))#ADD a normalization layer heremodel.add(tf.keras.layers.Flatten())model.add(tf.keras.layers.Dense(128, activation='relu'))model.add(tf.keras.layers.Dropout(0.2))model.add(tf.keras.layers.Dense(10, activation='softmax'))model.compile(loss=tf.keras.losses.categorical_crossentropy,optimizer='adam', metrics=['accuracy']) I tried all the normalizations with 5 different batch sizes namely 128, 64, 32, 16, and 8. The results are shown below. I won’t go into deep with the results because of discrepancies like dataset bias and luck! Train it again and we will see different results. If you want to read about these in more detail or discover more normalization techniques you can refer to this article which was a great help to me in writing this. If you would like to further improve your network then you can read this:
[ { "code": null, "e": 626, "s": 172, "text": "When normalization was introduced in deep learning, it was the next big thing and improved performances considerably. Getting it right can be a crucial factor for your model. Ever had those questions whatever the hell is batch normalization and how does it improve performances. Also are there any substitutes for it? If you like me had these questions but never bothered and just used it for the sake of it in your models this article will clear it up." }, { "code": null, "e": 646, "s": 626, "text": "Batch Normalization" }, { "code": null, "e": 666, "s": 646, "text": "Group Normalization" }, { "code": null, "e": 689, "s": 666, "text": "Instance Normalization" }, { "code": null, "e": 709, "s": 689, "text": "Layer Normalization" }, { "code": null, "e": 730, "s": 709, "text": "Weight Normalization" }, { "code": null, "e": 759, "s": 730, "text": "Implementation in Tensorflow" }, { "code": null, "e": 1305, "s": 759, "text": "The most widely used technique providing wonders to performance. What does it do? Well, Batch normalization is a normalization method that normalizes activations in a network across the mini-batch. It computes the mean and variance for each feature in a mini-batch. It then subtracts the mean and divides the feature by its mini-batch standard deviation. It also has two additional learnable parameters, the mean and magnitude of the activations. These are used to avoid the problems associated with having zero mean and unit standard deviation." }, { "code": null, "e": 1714, "s": 1305, "text": "All this seems simple enough but why did have such a big impact on the community and how does it do this? The answer is not figured out completely. Some say it improves the internal covariate shift while some disagree. But we do know that it makes the loss surface smoother and the activations of one layer can be controlled independently from other layers and prevent weights from flying all over the place." }, { "code": null, "e": 1995, "s": 1714, "text": "So it is so great why do we need others? When the batch size is small the mean/variance of the mini-batch can be far away from the global mean/variance. This introduces a lot of noise. If the batch size is 1 then batch normalization cannot be applied and it does not work in RNNs." }, { "code": null, "e": 2444, "s": 1995, "text": "It computes the mean and standard deviation over groups of channels for each training example. So it is essentially batch size independent. Group normalization matched the performance of batch normalization with a batch size of 32 on the ImageNet dataset and outperformed it on smaller batch sizes. When the image resolution is high and a big batch size can’t be used because of memory constraints group normalization is a very effective technique." }, { "code": null, "e": 2994, "s": 2444, "text": "Instance normalization and layer normalization (which we will discuss later) are both inferior to batch normalization for image recognition tasks, but not group normalization. Layer normalization considers all the channels while instance normalization considers only a single channel which leads to their downfall. All channels are not equally important, as the center of the image to its edges, while not being completely independent of each other. So technically group normalization combines the best of both worlds and leaves out their drawbacks." }, { "code": null, "e": 3208, "s": 2994, "text": "As discussed earlier it computes the mean/variance across each channel of each training image. It is used in style transfer applications and has also been suggested as a replacement to batch normalization in GANs." }, { "code": null, "e": 3563, "s": 3208, "text": "While batch normalization normalizes the inputs across the batch dimensions, layer normalization normalizes the inputs across the feature maps. Again like the group and instance normalization it works on a single image at a time, i.e. its mean/variance is calculated independent of other examples. Experimental results show that it performs well on RNNs." }, { "code": null, "e": 3638, "s": 3563, "text": "I think the best way to describe it would be to quote its papers abstract." }, { "code": null, "e": 4416, "s": 3638, "text": "By reparameterizing the weights in this way we improve the conditioning of the optimization problem and we speed up convergence of stochastic gradient descent. Our reparameterization is inspired by batch normalization but does not introduce any dependencies between the examples in a minibatch. This means that our method can also be applied successfully to recurrent models such as LSTMs and to noise-sensitive applications such as deep reinforcement learning or generative models, for which batch normalization is less well suited. Although our method is much simpler, it still provides much of the speed-up of full batch normalization. In addition, the computational overhead of our method is lower, permitting more optimization steps to be taken in the same amount of time." }, { "code": null, "e": 4655, "s": 4416, "text": "What’s the use of understanding the theory if we can’t implement it? So let’s see how to implement them in Tensorflow. Only batch normalization can be implemented using stable Tensorflow. For others, we need to install Tensorflow add-ons." }, { "code": null, "e": 4704, "s": 4655, "text": "pip install -q --no-deps tensorflow-addons~=0.7" }, { "code": null, "e": 4771, "s": 4704, "text": "Let’s create a model and add these different normalization layers." }, { "code": null, "e": 5446, "s": 4771, "text": "import tensorflow as tfimport tensorflow_addons as tfa#Batch Normalizationmodel.add(tf.keras.layers.BatchNormalization())#Group Normalizationmodel.add(tf.keras.layers.Conv2D(32, kernel_size=(3, 3), activation='relu'))model.add(tfa.layers.GroupNormalization(groups=8, axis=3))#Instance Normalizationmodel.add(tfa.layers.InstanceNormalization(axis=3, center=True, scale=True, beta_initializer=\"random_uniform\", gamma_initializer=\"random_uniform\"))#Layer Normalizationmodel.add(tf.keras.layers.LayerNormalization(axis=1 , center=True , scale=True))#Weight Normalizationmodel.add(tfa.layers.WeightNormalization(tf.keras.layers.Conv2D(32, kernel_size=(3, 3), activation='relu')))" }, { "code": null, "e": 5702, "s": 5446, "text": "When assigning the number of groups in group normalization make sure its value is a perfect divisor of the number of feature maps present at that time. In the above code that is 32 so its divisors can be used to denote the number of groups to divide into." }, { "code": null, "e": 5816, "s": 5702, "text": "Now we know how to use them why not try it out. We will use the MNIST dataset with a simple network architecture." }, { "code": null, "e": 6456, "s": 5816, "text": "model = tf.keras.models.Sequential()model.add(tf.keras.layers.Conv2D(16, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1)))model.add(tf.keras.layers.Conv2D(32, kernel_size=(3, 3), activation='relu'))#ADD a normalization layer heremodel.add(tf.keras.layers.Conv2D(32, kernel_size=(3, 3), activation='relu'))#ADD a normalization layer heremodel.add(tf.keras.layers.Flatten())model.add(tf.keras.layers.Dense(128, activation='relu'))model.add(tf.keras.layers.Dropout(0.2))model.add(tf.keras.layers.Dense(10, activation='softmax'))model.compile(loss=tf.keras.losses.categorical_crossentropy,optimizer='adam', metrics=['accuracy'])" }, { "code": null, "e": 6576, "s": 6456, "text": "I tried all the normalizations with 5 different batch sizes namely 128, 64, 32, 16, and 8. The results are shown below." }, { "code": null, "e": 6717, "s": 6576, "text": "I won’t go into deep with the results because of discrepancies like dataset bias and luck! Train it again and we will see different results." } ]
How to scrape ANY website with python and beautiful soup (static web) | by Patrick Collins | Towards Data Science
Note: This is a purely technical tutorial. Please check with the policies of the website before engaging in any scraping. For those who want to see it done in front of your eyes, check out my YouTube video at the bottom of the page. Scraping the web can be done for a TON of reasons. Do you want to get stats on your football team so you can algorithmically manage your fantasy team? Boom, make a web scraper that scrapes ESPN. Track your competitor's activity on different social media? Great, that’s covered here too. Or maybe you’re a Developer Advocate who is looking for good ways to measure his OKR of hackathon involvement and there is no current good tool out there so you want to build your own. That last one was oddly specific, and is what we are going to be looking for! This tutorial shows how you can get all the hackathons from devpost that are ending in the next 50 days, based on the keyword blockchain . Anyway, let’s jump right into how we can scrape anything with python. I’m going to assume you have space where you can code, and are familiar with how to work with python. The documentation for this is very strong, so be sure to check it out after this tutorial! Beautiful soup works great for static web pages. If you follow this and get weird/bad results, you’ll probably need a web driver to scrape the site. I published an ADVANCED version of doing this, but for 95% of cases, the following will do the trick. pip install requests pip install beautifulsoup Run those two so you can work with the packages. This one isn’t as cut-and-dry. If you’re looking to scrape through multiple web sites, you’ll need multiple URLs. This tutorial is focused on just scraping a single site. Once you understand how scraping a single page works, you can move to more pages. For our tutorial, we are going to be using: https://devpost.com/hackathons?utf8=%E2%9C%93&search=blockchain&challenge_type=all&sort_by=Submission+Deadline Since it gives us all of our parameters; the blockchain keyword and time till the hackathon is over. Every page is made of HTML/CSS/javascript (well... for the most part), and every bit of data that shows up on your screen shows up as text. You can every inspect this page! Just right click, and hit “inspect”. This will bring up all the code that the pages uses to render. This is the key to web scraping. Do you see the “Elements” tab? That has all the HTML/CSS code you need. Now you don’t need to know how HTML/CSS works (although, it can be really helpful if you do). The only thing that’s important to know is that you can think of every HTML tag as an object. These HTML tags have attributes that you can query, and each one is different. Each line of code in that image that starts with <footer> ,<script> , or <div> , these are the start of the tags, and they end with </footer> , </script>, or </div> respectfully. Everything that is in between these tags, are also queryable, and count as part of that tag. Once you have a tag, you can get anything inside that tag. So we start the scraping by pulling the website we want with the requests object: import requestsfrom bs4 import BeautifulSoupresult = requests.get("https://devpost.com/hackathons?utf8=%E2%9C%93&search=blockchain&challenge_type=all&sort_by=Submission+Deadline")src = result.contentsoup = BeautifulSoup(src, 'lxml') And we store the result in a BeautifulSoup object called soup above. This is just the boiler plate to any soup scraping, the next is the customizable part. You can now start to find out what tag you want, this is where you need to get a little creative, since you can generally approach the problem a number of different ways. For our example, we want to find all the hackathon listings, which we found they were all wrapped in an a tag, and had a featured_challenge attribute. Here is what their HTML code looked like: <a class=”clearfix” data-role=”featured_challenge” href=”https://utonhack.devpost.com/?ref_content=default&amp;ref_feature=challenge&amp;ref_medium=discover">...</a> The 3 . ‘s represent other tags inside this tag. We are going to ignore those for now, since the data we were looking for was right inside this tag. We want that URL. As you can see, this is an a tag since it starts with <a , and it has an attribute of data-role="featured_challenge" and that’s what we are going to use to identify it. We can use this to find a list of every single one of these by using the find_all function. featured_challenges = soup.find_all('a', attrs={'data-role': 'featured_challenge'}) The featured_challenges now is a list of a tag objects that we can get that URL from. If we loop through that list we can do something like: print(featured_challenge.attrs['href']) The attrs is a map of attributes each tag has. If you look back up at the a tag we pulled from, you saw there was an href attribute that holds the URL of the hackathon we are looking for, hooray! Each one of these tag objects counts as another HTML object, so you could do find_all on each one of the objects too! If you only want the first result, you can use the find function instead. Also, if you want to just get the text of the object, you can just look for the text attribute of the tag object, like so: featured_challenge.text And that’s it! If you want the code for a really simple scraper used in this demo, check it out here. Full code for multi-hackathon scraper with web driver
[ { "code": null, "e": 294, "s": 172, "text": "Note: This is a purely technical tutorial. Please check with the policies of the website before engaging in any scraping." }, { "code": null, "e": 405, "s": 294, "text": "For those who want to see it done in front of your eyes, check out my YouTube video at the bottom of the page." }, { "code": null, "e": 456, "s": 405, "text": "Scraping the web can be done for a TON of reasons." }, { "code": null, "e": 692, "s": 456, "text": "Do you want to get stats on your football team so you can algorithmically manage your fantasy team? Boom, make a web scraper that scrapes ESPN. Track your competitor's activity on different social media? Great, that’s covered here too." }, { "code": null, "e": 877, "s": 692, "text": "Or maybe you’re a Developer Advocate who is looking for good ways to measure his OKR of hackathon involvement and there is no current good tool out there so you want to build your own." }, { "code": null, "e": 1094, "s": 877, "text": "That last one was oddly specific, and is what we are going to be looking for! This tutorial shows how you can get all the hackathons from devpost that are ending in the next 50 days, based on the keyword blockchain ." }, { "code": null, "e": 1266, "s": 1094, "text": "Anyway, let’s jump right into how we can scrape anything with python. I’m going to assume you have space where you can code, and are familiar with how to work with python." }, { "code": null, "e": 1357, "s": 1266, "text": "The documentation for this is very strong, so be sure to check it out after this tutorial!" }, { "code": null, "e": 1608, "s": 1357, "text": "Beautiful soup works great for static web pages. If you follow this and get weird/bad results, you’ll probably need a web driver to scrape the site. I published an ADVANCED version of doing this, but for 95% of cases, the following will do the trick." }, { "code": null, "e": 1629, "s": 1608, "text": "pip install requests" }, { "code": null, "e": 1655, "s": 1629, "text": "pip install beautifulsoup" }, { "code": null, "e": 1704, "s": 1655, "text": "Run those two so you can work with the packages." }, { "code": null, "e": 1957, "s": 1704, "text": "This one isn’t as cut-and-dry. If you’re looking to scrape through multiple web sites, you’ll need multiple URLs. This tutorial is focused on just scraping a single site. Once you understand how scraping a single page works, you can move to more pages." }, { "code": null, "e": 2001, "s": 1957, "text": "For our tutorial, we are going to be using:" }, { "code": null, "e": 2112, "s": 2001, "text": "https://devpost.com/hackathons?utf8=%E2%9C%93&search=blockchain&challenge_type=all&sort_by=Submission+Deadline" }, { "code": null, "e": 2213, "s": 2112, "text": "Since it gives us all of our parameters; the blockchain keyword and time till the hackathon is over." }, { "code": null, "e": 2423, "s": 2213, "text": "Every page is made of HTML/CSS/javascript (well... for the most part), and every bit of data that shows up on your screen shows up as text. You can every inspect this page! Just right click, and hit “inspect”." }, { "code": null, "e": 2591, "s": 2423, "text": "This will bring up all the code that the pages uses to render. This is the key to web scraping. Do you see the “Elements” tab? That has all the HTML/CSS code you need." }, { "code": null, "e": 2858, "s": 2591, "text": "Now you don’t need to know how HTML/CSS works (although, it can be really helpful if you do). The only thing that’s important to know is that you can think of every HTML tag as an object. These HTML tags have attributes that you can query, and each one is different." }, { "code": null, "e": 3189, "s": 2858, "text": "Each line of code in that image that starts with <footer> ,<script> , or <div> , these are the start of the tags, and they end with </footer> , </script>, or </div> respectfully. Everything that is in between these tags, are also queryable, and count as part of that tag. Once you have a tag, you can get anything inside that tag." }, { "code": null, "e": 3271, "s": 3189, "text": "So we start the scraping by pulling the website we want with the requests object:" }, { "code": null, "e": 3504, "s": 3271, "text": "import requestsfrom bs4 import BeautifulSoupresult = requests.get(\"https://devpost.com/hackathons?utf8=%E2%9C%93&search=blockchain&challenge_type=all&sort_by=Submission+Deadline\")src = result.contentsoup = BeautifulSoup(src, 'lxml')" }, { "code": null, "e": 3573, "s": 3504, "text": "And we store the result in a BeautifulSoup object called soup above." }, { "code": null, "e": 3660, "s": 3573, "text": "This is just the boiler plate to any soup scraping, the next is the customizable part." }, { "code": null, "e": 4024, "s": 3660, "text": "You can now start to find out what tag you want, this is where you need to get a little creative, since you can generally approach the problem a number of different ways. For our example, we want to find all the hackathon listings, which we found they were all wrapped in an a tag, and had a featured_challenge attribute. Here is what their HTML code looked like:" }, { "code": null, "e": 4190, "s": 4024, "text": "<a class=”clearfix” data-role=”featured_challenge” href=”https://utonhack.devpost.com/?ref_content=default&amp;ref_feature=challenge&amp;ref_medium=discover\">...</a>" }, { "code": null, "e": 4526, "s": 4190, "text": "The 3 . ‘s represent other tags inside this tag. We are going to ignore those for now, since the data we were looking for was right inside this tag. We want that URL. As you can see, this is an a tag since it starts with <a , and it has an attribute of data-role=\"featured_challenge\" and that’s what we are going to use to identify it." }, { "code": null, "e": 4618, "s": 4526, "text": "We can use this to find a list of every single one of these by using the find_all function." }, { "code": null, "e": 4702, "s": 4618, "text": "featured_challenges = soup.find_all('a', attrs={'data-role': 'featured_challenge'})" }, { "code": null, "e": 4788, "s": 4702, "text": "The featured_challenges now is a list of a tag objects that we can get that URL from." }, { "code": null, "e": 4843, "s": 4788, "text": "If we loop through that list we can do something like:" }, { "code": null, "e": 4883, "s": 4843, "text": "print(featured_challenge.attrs['href'])" }, { "code": null, "e": 5079, "s": 4883, "text": "The attrs is a map of attributes each tag has. If you look back up at the a tag we pulled from, you saw there was an href attribute that holds the URL of the hackathon we are looking for, hooray!" }, { "code": null, "e": 5271, "s": 5079, "text": "Each one of these tag objects counts as another HTML object, so you could do find_all on each one of the objects too! If you only want the first result, you can use the find function instead." }, { "code": null, "e": 5394, "s": 5271, "text": "Also, if you want to just get the text of the object, you can just look for the text attribute of the tag object, like so:" }, { "code": null, "e": 5418, "s": 5394, "text": "featured_challenge.text" }, { "code": null, "e": 5433, "s": 5418, "text": "And that’s it!" }, { "code": null, "e": 5520, "s": 5433, "text": "If you want the code for a really simple scraper used in this demo, check it out here." } ]
5 Techniques to work with Imbalanced Data in Machine Learning | by Satyam Kumar | Towards Data Science
For classification tasks, one may encounter situations where the target class label is un-equally distributed across various classes. Such conditions are termed as an Imbalanced target class. Modeling an imbalanced dataset is a major challenge faced by data scientists, as due to the presence of an imbalance in the data the model becomes biased towards the majority class prediction. Hence, handling the imbalance in the dataset is essential prior to model training. There are various things to keep in mind while working with imbalanced data. In this article, we will discuss various techniques to handle class imbalance to train a robust and well-fit machine learning model. Checklist:1) Upsampling Minority Class2) Downsampling Majority Class3) Generate Synthetic Data4) Combine Upsampling & Downsampling Techniques 5) Balanced Class Weight Before processing to discuss the 5 above-mentioned techniques, let’s focus on choosing the right metric for an Imbalanced dataset task. Choosing an incorrect metric such as Accuracy seems to perform well but actually is biased towards the majority class label. The alternate choice of performance metrics can be: AUC-ROC Score Precision, Recall, and F1-score Confusion Matrix for visualization of TP, FP, FN, TN After choosing the right metric for your case study, one can employ various techniques to handle the imbalance in the dataset. Upsampling or Oversampling refers to the technique to create artificial or duplicate data points or of the minority class sample to balance the class label. There are various oversampling techniques that can be used to create artificial data points. Read the below mentioned article to get better understanding of 7 such oversampling techniques: towardsdatascience.com Downsampling or Undersampling refers to remove or reduce the majority of class samples to balance the class label. There are various undersampling techniques implemented in the imblearn package including: Random Under Sampling Tomek Links NearMiss Sampling ENN (Edited Nearest Neighbours) and many more. Follow the imblearn documentation to get implementation of each of the above-mentioned techniques: imbalanced-learn.org Undersampling techniques are not recommended as it removes the majority class data points. Generating synthetic data points of minority samples is a type of oversampling technique. The idea is to generate synthetic data points of minority class samples in the nearby region or neighborhood of minority class samples. SMOTE (Synthetic Minority Over-Sampling Technique) is a popular synthetic data generation oversampling technique that utilizes the k-nearest neighbor algorithm to create synthetic data. There are various variations of SMOTE including: SMOTENC: SMOTE variant for continuous and categorical features. SMOTEN: SMOTE variant for data with only categorical features. Borderline SMOTE: New Synthetic samples will be generated using the borderline samples. SVMSMOTE: Use an SVM algorithm to detect samples to use for generating new synthetic samples. KMeansSMOTE: Over-sample using k-Means clustering prior to oversample using SMOTE. Adaptive Synthetic (ADASYN): Similar to SMOTE but it generates a different number of samples depending on an estimate of the local distribution of the class to be oversampled. Follow Imblearn documentation for the implementation of above-discussed SMOTE techniques: Undersampling techniques is not recommended as it removes the majority class data points. Oversampling techniques are often considered better than undersampling techniques. The idea is to combine the undersampling and oversampling techniques to create a robust balanced dataset fit for model training. The idea is to first use an oversampling technique to create duplicate and artificial data points and use undersampling techniques to remove noise or unnecessary generated data points. Imblearn library comes with the implementation of combined Oversampling and Undersampling techniques such as: Smote-Tomek: Smote (Oversampler) combined with TomekLinks (Undersampler). Smote-ENN: Smote (Oversampler) combined with ENN (Undersampler). Follow Imblearn documentation for the implementation of Smote-Tomek and Smote-ENN techniques. The undersampling technique removes the majority class data points which results in data loss, whereas upsampling creates artificial data points of the minority class. During the training of machine learning, one can use class_weight parameter to handle the imbalance in the dataset. Scikit-learn comes with the class_weight parameters for all the machine learning algorithms. class weight — balanced: The class weight is inversely proportional to class frequencies in the input data. Computation Formula:n_samples / (n_classes * np.bincount(y)) {class_label: weight}: Let’s say, target class labels are 0 and 1. Passing input as class_weight={0:2, 1:1} means class 0 has weight 2 and class 1 has weight 1. The presence of a class imbalance in the data can be a major challenge while training a robust model. The 5 above-discussed techniques can be used to handle the class imbalance prior to train a machine learning model. One can also employ cost-sensitive learning or penalize the algorithms that increase the cost of classification of majority classes. Also, Decision Trees and Random Forest should be preferred over other machine learning algorithms as they tend to perform well on imbalanced data. [1.] Imblearn Documentation: https://imbalanced-learn.org/stable/index.html Loved the article? Become a Medium member to continue learning without limits. I’ll receive a small portion of your membership fee if you use the following link, with no extra cost to you. satyam-kumar.medium.com Thank You for Reading
[ { "code": null, "e": 557, "s": 172, "text": "For classification tasks, one may encounter situations where the target class label is un-equally distributed across various classes. Such conditions are termed as an Imbalanced target class. Modeling an imbalanced dataset is a major challenge faced by data scientists, as due to the presence of an imbalance in the data the model becomes biased towards the majority class prediction." }, { "code": null, "e": 850, "s": 557, "text": "Hence, handling the imbalance in the dataset is essential prior to model training. There are various things to keep in mind while working with imbalanced data. In this article, we will discuss various techniques to handle class imbalance to train a robust and well-fit machine learning model." }, { "code": null, "e": 1017, "s": 850, "text": "Checklist:1) Upsampling Minority Class2) Downsampling Majority Class3) Generate Synthetic Data4) Combine Upsampling & Downsampling Techniques 5) Balanced Class Weight" }, { "code": null, "e": 1330, "s": 1017, "text": "Before processing to discuss the 5 above-mentioned techniques, let’s focus on choosing the right metric for an Imbalanced dataset task. Choosing an incorrect metric such as Accuracy seems to perform well but actually is biased towards the majority class label. The alternate choice of performance metrics can be:" }, { "code": null, "e": 1344, "s": 1330, "text": "AUC-ROC Score" }, { "code": null, "e": 1376, "s": 1344, "text": "Precision, Recall, and F1-score" }, { "code": null, "e": 1429, "s": 1376, "text": "Confusion Matrix for visualization of TP, FP, FN, TN" }, { "code": null, "e": 1556, "s": 1429, "text": "After choosing the right metric for your case study, one can employ various techniques to handle the imbalance in the dataset." }, { "code": null, "e": 1806, "s": 1556, "text": "Upsampling or Oversampling refers to the technique to create artificial or duplicate data points or of the minority class sample to balance the class label. There are various oversampling techniques that can be used to create artificial data points." }, { "code": null, "e": 1902, "s": 1806, "text": "Read the below mentioned article to get better understanding of 7 such oversampling techniques:" }, { "code": null, "e": 1925, "s": 1902, "text": "towardsdatascience.com" }, { "code": null, "e": 2130, "s": 1925, "text": "Downsampling or Undersampling refers to remove or reduce the majority of class samples to balance the class label. There are various undersampling techniques implemented in the imblearn package including:" }, { "code": null, "e": 2152, "s": 2130, "text": "Random Under Sampling" }, { "code": null, "e": 2164, "s": 2152, "text": "Tomek Links" }, { "code": null, "e": 2182, "s": 2164, "text": "NearMiss Sampling" }, { "code": null, "e": 2214, "s": 2182, "text": "ENN (Edited Nearest Neighbours)" }, { "code": null, "e": 2229, "s": 2214, "text": "and many more." }, { "code": null, "e": 2328, "s": 2229, "text": "Follow the imblearn documentation to get implementation of each of the above-mentioned techniques:" }, { "code": null, "e": 2349, "s": 2328, "text": "imbalanced-learn.org" }, { "code": null, "e": 2666, "s": 2349, "text": "Undersampling techniques are not recommended as it removes the majority class data points. Generating synthetic data points of minority samples is a type of oversampling technique. The idea is to generate synthetic data points of minority class samples in the nearby region or neighborhood of minority class samples." }, { "code": null, "e": 2852, "s": 2666, "text": "SMOTE (Synthetic Minority Over-Sampling Technique) is a popular synthetic data generation oversampling technique that utilizes the k-nearest neighbor algorithm to create synthetic data." }, { "code": null, "e": 2901, "s": 2852, "text": "There are various variations of SMOTE including:" }, { "code": null, "e": 2965, "s": 2901, "text": "SMOTENC: SMOTE variant for continuous and categorical features." }, { "code": null, "e": 3028, "s": 2965, "text": "SMOTEN: SMOTE variant for data with only categorical features." }, { "code": null, "e": 3116, "s": 3028, "text": "Borderline SMOTE: New Synthetic samples will be generated using the borderline samples." }, { "code": null, "e": 3210, "s": 3116, "text": "SVMSMOTE: Use an SVM algorithm to detect samples to use for generating new synthetic samples." }, { "code": null, "e": 3293, "s": 3210, "text": "KMeansSMOTE: Over-sample using k-Means clustering prior to oversample using SMOTE." }, { "code": null, "e": 3469, "s": 3293, "text": "Adaptive Synthetic (ADASYN): Similar to SMOTE but it generates a different number of samples depending on an estimate of the local distribution of the class to be oversampled." }, { "code": null, "e": 3559, "s": 3469, "text": "Follow Imblearn documentation for the implementation of above-discussed SMOTE techniques:" }, { "code": null, "e": 3861, "s": 3559, "text": "Undersampling techniques is not recommended as it removes the majority class data points. Oversampling techniques are often considered better than undersampling techniques. The idea is to combine the undersampling and oversampling techniques to create a robust balanced dataset fit for model training." }, { "code": null, "e": 4046, "s": 3861, "text": "The idea is to first use an oversampling technique to create duplicate and artificial data points and use undersampling techniques to remove noise or unnecessary generated data points." }, { "code": null, "e": 4156, "s": 4046, "text": "Imblearn library comes with the implementation of combined Oversampling and Undersampling techniques such as:" }, { "code": null, "e": 4230, "s": 4156, "text": "Smote-Tomek: Smote (Oversampler) combined with TomekLinks (Undersampler)." }, { "code": null, "e": 4295, "s": 4230, "text": "Smote-ENN: Smote (Oversampler) combined with ENN (Undersampler)." }, { "code": null, "e": 4389, "s": 4295, "text": "Follow Imblearn documentation for the implementation of Smote-Tomek and Smote-ENN techniques." }, { "code": null, "e": 4673, "s": 4389, "text": "The undersampling technique removes the majority class data points which results in data loss, whereas upsampling creates artificial data points of the minority class. During the training of machine learning, one can use class_weight parameter to handle the imbalance in the dataset." }, { "code": null, "e": 4766, "s": 4673, "text": "Scikit-learn comes with the class_weight parameters for all the machine learning algorithms." }, { "code": null, "e": 4874, "s": 4766, "text": "class weight — balanced: The class weight is inversely proportional to class frequencies in the input data." }, { "code": null, "e": 4935, "s": 4874, "text": "Computation Formula:n_samples / (n_classes * np.bincount(y))" }, { "code": null, "e": 5096, "s": 4935, "text": "{class_label: weight}: Let’s say, target class labels are 0 and 1. Passing input as class_weight={0:2, 1:1} means class 0 has weight 2 and class 1 has weight 1." }, { "code": null, "e": 5314, "s": 5096, "text": "The presence of a class imbalance in the data can be a major challenge while training a robust model. The 5 above-discussed techniques can be used to handle the class imbalance prior to train a machine learning model." }, { "code": null, "e": 5594, "s": 5314, "text": "One can also employ cost-sensitive learning or penalize the algorithms that increase the cost of classification of majority classes. Also, Decision Trees and Random Forest should be preferred over other machine learning algorithms as they tend to perform well on imbalanced data." }, { "code": null, "e": 5670, "s": 5594, "text": "[1.] Imblearn Documentation: https://imbalanced-learn.org/stable/index.html" }, { "code": null, "e": 5859, "s": 5670, "text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a small portion of your membership fee if you use the following link, with no extra cost to you." }, { "code": null, "e": 5883, "s": 5859, "text": "satyam-kumar.medium.com" } ]
Statistics is dead, long live statistics! | Towards Data Science
Estimating confidence intervals and hypothesis testing are two common statistical tasks. They have an air of mystery around them as they rely on math accompanied by complex and case-specific assumptions. While this is still the way many people do stats, I argue it is not the best way. Modern computing power allows us to take advantage of resampling methods that are easier to understand and free of assumptions and approximations. Back in the old days, when computing power was a fraction of what we have today, statisticians had no choice but to turn to mathematical functions such as the t-distribution to approximate sampling distributions. You will see the t-statistics everywhere, from assessing regression coefficients’ significance, through calculating confidence intervals, to A/B testing. These days, however, we can turn away from this assumptions-heavy approach in favor of the resampling methods. Resampling boils down to repeatedly sampling values from the data in order to assess random variability in statistics calculated from these data. It comes in two main flavors: Bootstrapping, which is used to assess the reliability of an estimate or prediction. It can be used to compute confidence intervals or prediction intervals (don’t confuse the two!), to improve the accuracy of machine learning models (as in bagging, or bootstrap aggregating, the basis of random forests and many boosting models), or to estimate the uncertainty from imputing missing data. Permuting, which is used for hypothesis testing. Let’s look at each of them and how to use them to solve common problems in a math-and-assumption-free, standardized, error-prone way. Bootstrapping simply means taking many samples from the original data with replacement. These are called bootstrap samples, and since we are drawing with replacement, the same data point may appear multiple times in a single bootstrap sample. The point of this is to mimic obtaining many samples from a hypothetical population so that we can observe sampling uncertainty. We then perform the desired calculations on each bootstrap sample in isolation and combine the results into a distribution of some statistic of interest that reflects its variability.(quote from my article on bootstrapping confidence intervals) The bootstrap is a unified and standardized approach. Whatever it is you want to achieve, you always follow the same steps: draw many samples with replacement, calculate whatever you care about on each sample, combine the results from all samples into a distribution, and use this distribution to learn about the variability in your estimate. Let’s look at some examples. Bootstrap takes samples with replacement from the data to measure sampling uncertainty. It has a myriad of use cases. Are the houses in south California more expansive than in the northern part of the state? Let’s run an A/B test based on the California housing data! To do this, we can split the data by the median latitude and compare the average house price in the south ($222k) to the average price in the north ($191k), to get the difference of $31k. Note the dataset, and so the prices, are from 1997 — wish these were today’s prices, don’t we? Is this difference significant? Or maybe, had we collected another portion of data, we would get a different number, perhaps even a negative one? Confidence interval is the answer. A 95% CI tells us that if we had collected many other data sets on houses in California and had run such an A/B test on each of them, in 95% of the cases the true average difference between the southern and northern prices (which we would know should we have data on all houses in California) would be covered by the interval. Here is how to compute the 95% CI for our A/B test via bootstrapping: Mean diff: 0.3080677771202604695% CI: [0.28223704 0.33397099] We can be 95% sure that the interval $28k — $33k contains the true difference, so yes, houses in the south are pretty likely more expensive. And thanks to the bootstrap, we can say so without assuming that prices follow a normal distribution (which they obviously don’t). This is due to the magic of the Central Limit Theorem — bootstrap samples are random, hence independent, and so the difference in their means is normally distributed. Let’s continue playing with the California housing data to find what was the mean house age in the state back in 1997, and what was its standard error. We can calculate the average house age in the data to be 28.6 years, but how accurate is this sample estimate with regards to the Californian houses in general? Let’s bootstrap to see! Average mean: 28.6383311627907Standard error: 0.08733193966359917 The bootstrap estimate of the average house age corresponds to what we observe in our data, and we also got a bootstrapped standard error of 0.08 years, which is close to one month. This suggests our estimate of the mean age is pretty accurate! In my last article, I have written about the difference between confidence and prediction intervals. The post includes code to bootstrap both in the context of regression models — don’t hesitate to take a detour to check it out! towardsdatascience.com It is a common practice, when tackling incomplete data, to fill in the missing values using some imputation method or another, and then run the analyses or train the models on such a filled-in dataset. This is a terrible practice! Such an approach completely ignores the fact that imputed values are just estimates that come with some uncertainty and this uncertainty transfers to any model or analysis built on top of imputed data. In other words, any model prediction or statistical estimate that we report should be accompanied by some variability measure that incorporates the uncertainty from imputation. I have written about it here (an R example) and here (general remarks on handling missing data). And once again, bootstrap to the rescue! We need to take bootstrap samples from the incomplete dataset, impute each of them in isolation, train a model on each of them separately, and then combine the predictions from all these models into a distribution. We can then compute intervals or standard deviations based on this distribution to quantify the uncertainty in the predictions that partly comes from imputation. Bootstrapping seems to work like magic. It lets us approximate any quantity we want, even those for which classical statistics knows no formulas, and informs us about the uncertainty in its estimates, all of this assumption-free. But don’t forget that the bootstrap doesn’t create more data or compensate for a small sample. It only works if the data we have is representative of the population of interest. If that’s the case, then bootstrapping tells us what would have been, had we collected more data. Next to bootstrapping, the second resampling method is permuting. In probability theory, a permutation of some set of items is simply a reordering of the items in this set. For example, the set of numbers [1, 2, 3] can be permuted in five different ways to obtain the following sets: [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2] and [3, 2, 1]. This simple idea enables us to perform hypothesis testing in a formula-free manner, in a way that is easy to interpret and understand and without relying on distributional assumptions, which is typically the case in the classical approach to testing. To understand how permutation testing works, we need a quick refresher on classical hypothesis testing (for a more in-depth elaboration, check out this article). To stay down-to-eath, we will look at the California housing data again. This time, let’s test if the house prices in the east and in the west of the state are the same. The test that we want to conduct is a test for the difference in means: we want to know whether the mean house price in the east ($215k in the data) is the same as the mean house price in the west ($199k in the data). Is the observed difference of $16k a result of random chance, or were the houses in the east really more expensive, on average? This use case is well-served by the t-test. Let’s walk through the testing procedure step by step. First, we need to set up our hypotheses. The null hypothesis will be that the average house price in the east is equal to the average house price in the west, and we will try to reject it in favor of the alternative hypothesis that they are not equal.Next, we need something called the test statistic. A test statistic is a single number calculated according to some formula, specific to the test we are conducting. It has to fulfill two conditions: it needs to be calculatable from the data and we need to know its distribution assuming the null hypothesis is true. Luckily, the case of our test for the difference in means has been well-researched ages ago and we know that if the average prices are equal (the null hypothesis is true) and we observe some difference in the averages only due to chance, then the following test statistic has a t-distribution. First, we need to set up our hypotheses. The null hypothesis will be that the average house price in the east is equal to the average house price in the west, and we will try to reject it in favor of the alternative hypothesis that they are not equal. Next, we need something called the test statistic. A test statistic is a single number calculated according to some formula, specific to the test we are conducting. It has to fulfill two conditions: it needs to be calculatable from the data and we need to know its distribution assuming the null hypothesis is true. Luckily, the case of our test for the difference in means has been well-researched ages ago and we know that if the average prices are equal (the null hypothesis is true) and we observe some difference in the averages only due to chance, then the following test statistic has a t-distribution. 3. The Xs with dashes on top of them denote the mean prices in the two groups (east and west), the s2 are the variances in the prices, and n is the number of observations, assumed the same in both groups. We can use this formula to compute our test statistic. t-stat: 9.627149556121305 4. Finally, we need to use the fact that we know that if the null hypothesis is true, then our t-statistic has a t-distribution with (2*n)-2 degrees of freedom. It looks like this: From this, we conclude that if the null hypothesis was true (if the average prices were the same in the east and the west), then the value of the t-statistic we have obtained would be nearly impossible to get. This means that most likely, the null is false and we should reject it: the average prices differ. 5. We can quantify this decision by calculating the p-value. The p-value is the probability that, given the null is true, we can get the test statistic that we actually got from the data (or even a more extreme one). In other words, it is the percentage of the blue mass that is located to the right of the dashed line, which in this case seems to be close to zero. Let’s compute it, this time using a scipy function. Calling scipy.stats.ttest_ind(price_east, price_west) gives us the following output: Ttest_indResult( statistic=9.627692430826853, pvalue=6.791637088718439e-22) You can see that the test statistic of 9.627 matches our manual calculation and that the p-value is virtually zero. Hence, we reject the null hypothesis. Phew! Notice how we have relied on the approximating formula for the t-statistic, which is based on multiple assumptions. We have implicitly assumed that the variances and the number of observations are the same for western and eastern prices. We have also assumed that these two data subsamples are independent and normally distributed. And finally, that the sample size is large enough. We are at five assumptions already, some of them clearly not holding (prices are rarely normally distributed!). Classical hypothesis tests come with tonnes of case-specific assumptions. In more complex cases, ready formulas might be unavailable. Permutation testing fixes both these issues. Sure, you can adjust the formula to meet your needs, but firstly, another formula will come with another set of hidden assumptions, and secondly, in cases more complex than a simple t-test, closed-form formulas might not even be known for your specific use case. Enters permutation testing! The general idea behind permutation testing is to take all available data and permute it randomly. This corresponds to the null hypothesis that there is no effect. Next, we repeatedly draw samples (without replacement) from this combined and permuted dataset, calculate the quantities of interest and combine them into a distribution. We know that this distribution embodies variation that is produced by chance alone due to the permutation step. Finally, we compare the quantity of interest we observe in our data to the distribution of its random variation. If it is located well within this distribution, we haven’t proved anything — there is no evidence to reject the null hypothesis since our result might have been produced by chance. If, however, our observed value finds itself far away from the distribution, we have grounds to say it’s unlikely that it was produced by chance and we reject the null hypothesis. We can also calculate the p-value, just like in classical testing. Let’s see it in practice! In our east-west price test, we will need to combine all prices, repeatedly permute them, create two groups of sizes matching the original groups, and compute the differences in average prices. This way, we get the distribution of the differences produced by chance. Let’s compare it to our observed difference of $16k. The difference in average prices between the east and the west that we observed is much larger than what might be produced by chance, so we will reject the null hypothesis. Let’s quantify it by calculating the p-value. Since the p-value is the proportion of the blue mass to the right of the red line, we can easily compute it as follows. In this pretty evident case, the p-value is of course zero, just like in the classical test. In a pretty similar fashion, we can run A/B/C testing known as the analysis of variance, or ANOVA. Say we are testing different color themes for our website with the goal to engage the users. As part of the experiment, we have randomly shown the users different website variants and we calculated the time they spent on the website. Below are the data for 15 users (five were shown the yellow version, another five the blue one, and the last five the green one). Naturally, for such an experiment to be valid, we would need many more than 15 users, this is just a demonstration. We are interested in the extent to which the differences between the means are larger than what might have been produced by random chance. If they are significantly larger, then we might conclude that the color indeed impacts the time spent on the website.(quote from my article on probability distributions) While we could do it based on the statistical theory and the F-distribution (check the F-distribution section in this article to see how to do this), we can also use permutation testing. p-value: 0.00844 Let’s visualize the observed variance on top of the permuted ones. You will find that the p-value is very close to what we would get had we followed the classical F-test approach. Since it is rather small, we conclude that the color does impact the website’s stickiness. The χ2 or chi-square test is in some sense a version of ANOVA for discrete data. Consider the three colors of the website once again. This time, instead of time spent on the site (a continuous variable), we have measured the number of purchases made through the site (a discrete variable). We want to know which color leads to the most purchases. Each color has been displayed to 1000 users, and here are the results: We could run a classical chi2 test (see how to do it here) but an assumption-free permutation test might be a better option. The first step is to assume that the three website versions generate the same number of purchases, on average (our null hypothesis). If that was true, we would expect the same number of purchases for each version, and it would be (17+9+14)/3, or 13.33 purchases.(quote from my article on probability distributions) Hence, in our permutation test, we generate a distribution of chance-generated statistics by assuming 40 purchases and 2960 non-purchases across all website colors, and we sample from this. The chi2-statistic we are interested in is the sum of squared differences between the permuted purchases and the expected purchases. p-value: 0.270826 The high p-value leads us to conclude that the differences in the number of purchases for differently-colored websites can be caused by random chance alone. Interestingly, the χ2 distribution used in a classical chi-2 test is actually only an approximation of the real distribution of the test statistic. For this reason, the resampled p-value value from our permutation test is slightly different than the one we could get from a classical test (we got 0.3 there). This is yet another piece of evidence in favor of the resampling approach — no approximations are needed here. Some of the ideas and code in this article are based on:Bruce, Bruce & Gedeck (2020), Practical Statistics for Data Scientists, 2nd edition, O’Reilly Thanks for reading! If you liked this post, why don’t you subscribe for email updates on my new articles? And by becoming a Medium member, you can support my writing and get unlimited access to all stories by other authors and myself. Need consulting? You can ask me anything or book me for a 1:1 here. You can also try one of my other articles. Can’t choose? Pick one of these:
[ { "code": null, "e": 604, "s": 171, "text": "Estimating confidence intervals and hypothesis testing are two common statistical tasks. They have an air of mystery around them as they rely on math accompanied by complex and case-specific assumptions. While this is still the way many people do stats, I argue it is not the best way. Modern computing power allows us to take advantage of resampling methods that are easier to understand and free of assumptions and approximations." }, { "code": null, "e": 1082, "s": 604, "text": "Back in the old days, when computing power was a fraction of what we have today, statisticians had no choice but to turn to mathematical functions such as the t-distribution to approximate sampling distributions. You will see the t-statistics everywhere, from assessing regression coefficients’ significance, through calculating confidence intervals, to A/B testing. These days, however, we can turn away from this assumptions-heavy approach in favor of the resampling methods." }, { "code": null, "e": 1258, "s": 1082, "text": "Resampling boils down to repeatedly sampling values from the data in order to assess random variability in statistics calculated from these data. It comes in two main flavors:" }, { "code": null, "e": 1647, "s": 1258, "text": "Bootstrapping, which is used to assess the reliability of an estimate or prediction. It can be used to compute confidence intervals or prediction intervals (don’t confuse the two!), to improve the accuracy of machine learning models (as in bagging, or bootstrap aggregating, the basis of random forests and many boosting models), or to estimate the uncertainty from imputing missing data." }, { "code": null, "e": 1696, "s": 1647, "text": "Permuting, which is used for hypothesis testing." }, { "code": null, "e": 1830, "s": 1696, "text": "Let’s look at each of them and how to use them to solve common problems in a math-and-assumption-free, standardized, error-prone way." }, { "code": null, "e": 2447, "s": 1830, "text": "Bootstrapping simply means taking many samples from the original data with replacement. These are called bootstrap samples, and since we are drawing with replacement, the same data point may appear multiple times in a single bootstrap sample. The point of this is to mimic obtaining many samples from a hypothetical population so that we can observe sampling uncertainty. We then perform the desired calculations on each bootstrap sample in isolation and combine the results into a distribution of some statistic of interest that reflects its variability.(quote from my article on bootstrapping confidence intervals)" }, { "code": null, "e": 2819, "s": 2447, "text": "The bootstrap is a unified and standardized approach. Whatever it is you want to achieve, you always follow the same steps: draw many samples with replacement, calculate whatever you care about on each sample, combine the results from all samples into a distribution, and use this distribution to learn about the variability in your estimate. Let’s look at some examples." }, { "code": null, "e": 2937, "s": 2819, "text": "Bootstrap takes samples with replacement from the data to measure sampling uncertainty. It has a myriad of use cases." }, { "code": null, "e": 3087, "s": 2937, "text": "Are the houses in south California more expansive than in the northern part of the state? Let’s run an A/B test based on the California housing data!" }, { "code": null, "e": 3370, "s": 3087, "text": "To do this, we can split the data by the median latitude and compare the average house price in the south ($222k) to the average price in the north ($191k), to get the difference of $31k. Note the dataset, and so the prices, are from 1997 — wish these were today’s prices, don’t we?" }, { "code": null, "e": 3878, "s": 3370, "text": "Is this difference significant? Or maybe, had we collected another portion of data, we would get a different number, perhaps even a negative one? Confidence interval is the answer. A 95% CI tells us that if we had collected many other data sets on houses in California and had run such an A/B test on each of them, in 95% of the cases the true average difference between the southern and northern prices (which we would know should we have data on all houses in California) would be covered by the interval." }, { "code": null, "e": 3948, "s": 3878, "text": "Here is how to compute the 95% CI for our A/B test via bootstrapping:" }, { "code": null, "e": 4010, "s": 3948, "text": "Mean diff: 0.3080677771202604695% CI: [0.28223704 0.33397099]" }, { "code": null, "e": 4449, "s": 4010, "text": "We can be 95% sure that the interval $28k — $33k contains the true difference, so yes, houses in the south are pretty likely more expensive. And thanks to the bootstrap, we can say so without assuming that prices follow a normal distribution (which they obviously don’t). This is due to the magic of the Central Limit Theorem — bootstrap samples are random, hence independent, and so the difference in their means is normally distributed." }, { "code": null, "e": 4786, "s": 4449, "text": "Let’s continue playing with the California housing data to find what was the mean house age in the state back in 1997, and what was its standard error. We can calculate the average house age in the data to be 28.6 years, but how accurate is this sample estimate with regards to the Californian houses in general? Let’s bootstrap to see!" }, { "code": null, "e": 4852, "s": 4786, "text": "Average mean: 28.6383311627907Standard error: 0.08733193966359917" }, { "code": null, "e": 5097, "s": 4852, "text": "The bootstrap estimate of the average house age corresponds to what we observe in our data, and we also got a bootstrapped standard error of 0.08 years, which is close to one month. This suggests our estimate of the mean age is pretty accurate!" }, { "code": null, "e": 5326, "s": 5097, "text": "In my last article, I have written about the difference between confidence and prediction intervals. The post includes code to bootstrap both in the context of regression models — don’t hesitate to take a detour to check it out!" }, { "code": null, "e": 5349, "s": 5326, "text": "towardsdatascience.com" }, { "code": null, "e": 5580, "s": 5349, "text": "It is a common practice, when tackling incomplete data, to fill in the missing values using some imputation method or another, and then run the analyses or train the models on such a filled-in dataset. This is a terrible practice!" }, { "code": null, "e": 6056, "s": 5580, "text": "Such an approach completely ignores the fact that imputed values are just estimates that come with some uncertainty and this uncertainty transfers to any model or analysis built on top of imputed data. In other words, any model prediction or statistical estimate that we report should be accompanied by some variability measure that incorporates the uncertainty from imputation. I have written about it here (an R example) and here (general remarks on handling missing data)." }, { "code": null, "e": 6474, "s": 6056, "text": "And once again, bootstrap to the rescue! We need to take bootstrap samples from the incomplete dataset, impute each of them in isolation, train a model on each of them separately, and then combine the predictions from all these models into a distribution. We can then compute intervals or standard deviations based on this distribution to quantify the uncertainty in the predictions that partly comes from imputation." }, { "code": null, "e": 6704, "s": 6474, "text": "Bootstrapping seems to work like magic. It lets us approximate any quantity we want, even those for which classical statistics knows no formulas, and informs us about the uncertainty in its estimates, all of this assumption-free." }, { "code": null, "e": 6980, "s": 6704, "text": "But don’t forget that the bootstrap doesn’t create more data or compensate for a small sample. It only works if the data we have is representative of the population of interest. If that’s the case, then bootstrapping tells us what would have been, had we collected more data." }, { "code": null, "e": 7573, "s": 6980, "text": "Next to bootstrapping, the second resampling method is permuting. In probability theory, a permutation of some set of items is simply a reordering of the items in this set. For example, the set of numbers [1, 2, 3] can be permuted in five different ways to obtain the following sets: [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2] and [3, 2, 1]. This simple idea enables us to perform hypothesis testing in a formula-free manner, in a way that is easy to interpret and understand and without relying on distributional assumptions, which is typically the case in the classical approach to testing." }, { "code": null, "e": 7905, "s": 7573, "text": "To understand how permutation testing works, we need a quick refresher on classical hypothesis testing (for a more in-depth elaboration, check out this article). To stay down-to-eath, we will look at the California housing data again. This time, let’s test if the house prices in the east and in the west of the state are the same." }, { "code": null, "e": 8350, "s": 7905, "text": "The test that we want to conduct is a test for the difference in means: we want to know whether the mean house price in the east ($215k in the data) is the same as the mean house price in the west ($199k in the data). Is the observed difference of $16k a result of random chance, or were the houses in the east really more expensive, on average? This use case is well-served by the t-test. Let’s walk through the testing procedure step by step." }, { "code": null, "e": 9211, "s": 8350, "text": "First, we need to set up our hypotheses. The null hypothesis will be that the average house price in the east is equal to the average house price in the west, and we will try to reject it in favor of the alternative hypothesis that they are not equal.Next, we need something called the test statistic. A test statistic is a single number calculated according to some formula, specific to the test we are conducting. It has to fulfill two conditions: it needs to be calculatable from the data and we need to know its distribution assuming the null hypothesis is true. Luckily, the case of our test for the difference in means has been well-researched ages ago and we know that if the average prices are equal (the null hypothesis is true) and we observe some difference in the averages only due to chance, then the following test statistic has a t-distribution." }, { "code": null, "e": 9463, "s": 9211, "text": "First, we need to set up our hypotheses. The null hypothesis will be that the average house price in the east is equal to the average house price in the west, and we will try to reject it in favor of the alternative hypothesis that they are not equal." }, { "code": null, "e": 10073, "s": 9463, "text": "Next, we need something called the test statistic. A test statistic is a single number calculated according to some formula, specific to the test we are conducting. It has to fulfill two conditions: it needs to be calculatable from the data and we need to know its distribution assuming the null hypothesis is true. Luckily, the case of our test for the difference in means has been well-researched ages ago and we know that if the average prices are equal (the null hypothesis is true) and we observe some difference in the averages only due to chance, then the following test statistic has a t-distribution." }, { "code": null, "e": 10333, "s": 10073, "text": "3. The Xs with dashes on top of them denote the mean prices in the two groups (east and west), the s2 are the variances in the prices, and n is the number of observations, assumed the same in both groups. We can use this formula to compute our test statistic." }, { "code": null, "e": 10359, "s": 10333, "text": "t-stat: 9.627149556121305" }, { "code": null, "e": 10540, "s": 10359, "text": "4. Finally, we need to use the fact that we know that if the null hypothesis is true, then our t-statistic has a t-distribution with (2*n)-2 degrees of freedom. It looks like this:" }, { "code": null, "e": 10849, "s": 10540, "text": "From this, we conclude that if the null hypothesis was true (if the average prices were the same in the east and the west), then the value of the t-statistic we have obtained would be nearly impossible to get. This means that most likely, the null is false and we should reject it: the average prices differ." }, { "code": null, "e": 11352, "s": 10849, "text": "5. We can quantify this decision by calculating the p-value. The p-value is the probability that, given the null is true, we can get the test statistic that we actually got from the data (or even a more extreme one). In other words, it is the percentage of the blue mass that is located to the right of the dashed line, which in this case seems to be close to zero. Let’s compute it, this time using a scipy function. Calling scipy.stats.ttest_ind(price_east, price_west) gives us the following output:" }, { "code": null, "e": 11435, "s": 11352, "text": "Ttest_indResult( statistic=9.627692430826853, pvalue=6.791637088718439e-22)" }, { "code": null, "e": 11595, "s": 11435, "text": "You can see that the test statistic of 9.627 matches our manual calculation and that the p-value is virtually zero. Hence, we reject the null hypothesis. Phew!" }, { "code": null, "e": 12090, "s": 11595, "text": "Notice how we have relied on the approximating formula for the t-statistic, which is based on multiple assumptions. We have implicitly assumed that the variances and the number of observations are the same for western and eastern prices. We have also assumed that these two data subsamples are independent and normally distributed. And finally, that the sample size is large enough. We are at five assumptions already, some of them clearly not holding (prices are rarely normally distributed!)." }, { "code": null, "e": 12269, "s": 12090, "text": "Classical hypothesis tests come with tonnes of case-specific assumptions. In more complex cases, ready formulas might be unavailable. Permutation testing fixes both these issues." }, { "code": null, "e": 12560, "s": 12269, "text": "Sure, you can adjust the formula to meet your needs, but firstly, another formula will come with another set of hidden assumptions, and secondly, in cases more complex than a simple t-test, closed-form formulas might not even be known for your specific use case. Enters permutation testing!" }, { "code": null, "e": 13574, "s": 12560, "text": "The general idea behind permutation testing is to take all available data and permute it randomly. This corresponds to the null hypothesis that there is no effect. Next, we repeatedly draw samples (without replacement) from this combined and permuted dataset, calculate the quantities of interest and combine them into a distribution. We know that this distribution embodies variation that is produced by chance alone due to the permutation step. Finally, we compare the quantity of interest we observe in our data to the distribution of its random variation. If it is located well within this distribution, we haven’t proved anything — there is no evidence to reject the null hypothesis since our result might have been produced by chance. If, however, our observed value finds itself far away from the distribution, we have grounds to say it’s unlikely that it was produced by chance and we reject the null hypothesis. We can also calculate the p-value, just like in classical testing. Let’s see it in practice!" }, { "code": null, "e": 13894, "s": 13574, "text": "In our east-west price test, we will need to combine all prices, repeatedly permute them, create two groups of sizes matching the original groups, and compute the differences in average prices. This way, we get the distribution of the differences produced by chance. Let’s compare it to our observed difference of $16k." }, { "code": null, "e": 14233, "s": 13894, "text": "The difference in average prices between the east and the west that we observed is much larger than what might be produced by chance, so we will reject the null hypothesis. Let’s quantify it by calculating the p-value. Since the p-value is the proportion of the blue mass to the right of the red line, we can easily compute it as follows." }, { "code": null, "e": 14326, "s": 14233, "text": "In this pretty evident case, the p-value is of course zero, just like in the classical test." }, { "code": null, "e": 14518, "s": 14326, "text": "In a pretty similar fashion, we can run A/B/C testing known as the analysis of variance, or ANOVA. Say we are testing different color themes for our website with the goal to engage the users." }, { "code": null, "e": 15214, "s": 14518, "text": "As part of the experiment, we have randomly shown the users different website variants and we calculated the time they spent on the website. Below are the data for 15 users (five were shown the yellow version, another five the blue one, and the last five the green one). Naturally, for such an experiment to be valid, we would need many more than 15 users, this is just a demonstration. We are interested in the extent to which the differences between the means are larger than what might have been produced by random chance. If they are significantly larger, then we might conclude that the color indeed impacts the time spent on the website.(quote from my article on probability distributions)" }, { "code": null, "e": 15401, "s": 15214, "text": "While we could do it based on the statistical theory and the F-distribution (check the F-distribution section in this article to see how to do this), we can also use permutation testing." }, { "code": null, "e": 15418, "s": 15401, "text": "p-value: 0.00844" }, { "code": null, "e": 15485, "s": 15418, "text": "Let’s visualize the observed variance on top of the permuted ones." }, { "code": null, "e": 15689, "s": 15485, "text": "You will find that the p-value is very close to what we would get had we followed the classical F-test approach. Since it is rather small, we conclude that the color does impact the website’s stickiness." }, { "code": null, "e": 16107, "s": 15689, "text": "The χ2 or chi-square test is in some sense a version of ANOVA for discrete data. Consider the three colors of the website once again. This time, instead of time spent on the site (a continuous variable), we have measured the number of purchases made through the site (a discrete variable). We want to know which color leads to the most purchases. Each color has been displayed to 1000 users, and here are the results:" }, { "code": null, "e": 16232, "s": 16107, "text": "We could run a classical chi2 test (see how to do it here) but an assumption-free permutation test might be a better option." }, { "code": null, "e": 16547, "s": 16232, "text": "The first step is to assume that the three website versions generate the same number of purchases, on average (our null hypothesis). If that was true, we would expect the same number of purchases for each version, and it would be (17+9+14)/3, or 13.33 purchases.(quote from my article on probability distributions)" }, { "code": null, "e": 16870, "s": 16547, "text": "Hence, in our permutation test, we generate a distribution of chance-generated statistics by assuming 40 purchases and 2960 non-purchases across all website colors, and we sample from this. The chi2-statistic we are interested in is the sum of squared differences between the permuted purchases and the expected purchases." }, { "code": null, "e": 16888, "s": 16870, "text": "p-value: 0.270826" }, { "code": null, "e": 17045, "s": 16888, "text": "The high p-value leads us to conclude that the differences in the number of purchases for differently-colored websites can be caused by random chance alone." }, { "code": null, "e": 17465, "s": 17045, "text": "Interestingly, the χ2 distribution used in a classical chi-2 test is actually only an approximation of the real distribution of the test statistic. For this reason, the resampled p-value value from our permutation test is slightly different than the one we could get from a classical test (we got 0.3 there). This is yet another piece of evidence in favor of the resampling approach — no approximations are needed here." }, { "code": null, "e": 17615, "s": 17465, "text": "Some of the ideas and code in this article are based on:Bruce, Bruce & Gedeck (2020), Practical Statistics for Data Scientists, 2nd edition, O’Reilly" }, { "code": null, "e": 17635, "s": 17615, "text": "Thanks for reading!" }, { "code": null, "e": 17850, "s": 17635, "text": "If you liked this post, why don’t you subscribe for email updates on my new articles? And by becoming a Medium member, you can support my writing and get unlimited access to all stories by other authors and myself." }, { "code": null, "e": 17918, "s": 17850, "text": "Need consulting? You can ask me anything or book me for a 1:1 here." } ]
Word Break - Part 2 | Practice | GeeksforGeeks
Given a string s and a dictionary of words dict of length n, add spaces in s to construct a sentence where each word is a valid dictionary word. Each dictionary word can be used more than once. Return all such possible sentences. Follow examples for better understanding. Example 1: Input: s = "catsanddog", n = 5 dict = {"cats", "cat", "and", "sand", "dog"} Output: (cats and dog)(cat sand dog) Explanation: All the words in the given sentences are present in the dictionary. Example 2: Input: s = "catsandog", n = 5 dict = {"cats", "cat", "and", "sand", "dog"} Output: Empty Explanation: There is no possible breaking of the string s where all the words are present in dict. Your Task: You do not need to read input or print anything. Your task is to complete the function wordBreak() which takes n, dict and s as input parameters and returns a list of possible sentences. If no sentence is possible it returns an empty list. Expected Time Complexity: O(N2*n) where N = |s| Expected Auxiliary Space: O(N2) Constraints: 1 ≤ n ≤ 20 1 ≤ dict[i] ≤ 15 1 ≤ |s| ≤ 500 0 pranavkhandare45451 week ago //simple java code static List<String> wordBreak(int n, List<String> dict, String s) { // code here List<String> list = new ArrayList<>(); helper(list, s, dict, new StringBuilder()); return list; } static void helper(List<String> list, String s, List<String> dict, StringBuilder str){ if(s.length() == 0){ str.deleteCharAt(str.length()-1); list.add(str.toString()); return; } for(int i = 0; i <= s.length(); i++){ String sub = s.substring(0,i); int l = str.length(); if(dict.contains(sub)){ str.append(sub+ " "); helper(list, s.substring(i), dict, str); str.delete(l, str.length()); } } 0 phenomenal11 week ago JAVA Solution: class Solution{ static List<String> wordBreak(int n, List<String> dict, String s) { List<String> ans = new ArrayList<>(); String res=""; solve(s,dict,res,ans); return ans; } static void solve(String s,List<String> dict,String res,List<String> ans) { if(s.length()==0) { res=res.trim(); ans.add(res); return; } for(int i=0;i<s.length();i++) { if(dict.contains(s.substring(0,i+1))) { solve(s.substring(i+1),dict,res+s.substring(0,i+1)+" ",ans); } } } } 0 sandeep55212 weeks ago C++ (DP+Backtracking) Solution (Time taken 0.01) bool func(string &s,int b,int n, unordered_set<string> &us,string &a,vector<string> &ans,vector<int> &dp){ if(b==n){ a.pop_back(); ans.push_back(a); return true; } if(dp[b]!=-1 and !dp[b]) return dp[b]; string t,p; p=a; int flag=1; for(int i=b;i<n;i++){ t.push_back(s[i]); if(us.find(t)==us.end()) continue; a+=t;a+=" "; if(func(s,i+1,n,us,a,ans,dp)) flag=0; a=p; // backtracking } if(flag) return dp[b]=false; return dp[b]=true; } vector<string> wordBreak(int n, vector<string>& wordDict, string &s) { // code here unordered_set<string> us; string a; vector<string> ans; n=s.size(); vector<int> dp(n,-1); for(auto i:wordDict) us.insert(i); func(s,0,n,us,a,ans,dp); return ans; } 0 shilsoumyadip2 weeks ago class Solution{public: vector<string> v;void solve ( int i , vector<string> dict, string s, string temp){ string sum = ""; for (int j=i; j< s.length(); j++) { sum+= s[j];if (find(dict.begin(), dict.end(), sum) != dict.end()){ solve( j+1 , dict, s, temp+sum+" "); } } if (i >= s.length()){ temp.pop_back(); v.push_back (temp); } } vector<string> wordBreak(int n, vector<string>& dict, string s) { solve( 0 , dict, s,""); return v; } }; 0 gaurabhkumarjha271020014 weeks ago // in c++ vector<string> v; void solve (vector<string> dict, string s, string temp, int i){ if (i >= s.length()){ temp.pop_back(); v.push_back (temp); } string str; for (int j=i; j< s.length(); j++){ str+= s[j]; if (find(dict.begin(), dict.end(), str) != dict.end()){ solve(dict, s, temp+str+' ', j+1); } } } vector<string> wordBreak(int n, vector<string>& dict, string s) { solve(dict, s, "", 0); return v; } 0 harrypotter01 month ago ## Word Break -2 def helper(n, curr, ans, dict,s ,n1): if len(s)==0: x = curr[:len(curr)-1] ans.add(x) return for i in range(n1+1): left = s[:i] if left in dict: right = s[i:] curr = curr + (s[:i]+" ") helper(n, curr, ans, dict, right, n1) curr = curr[::-1].replace(str(s[:i]+" ")[::-1], "",1)[::-1] return ans class Solution: def wordBreak(self, n, dict, s): ans = helper(n, "", set(), dict, s, len(s)) return list(ans) 0 parikhsharan61 month ago // Java solution 0.3s class Solution{ private static List<String> words = null; static List<String> wordBreak(int n, List<String> dict, String s) { words = new ArrayList<>(); wordBreak(n, dict, s, ""); return words; } private static void wordBreak(int n, List<String> dict, String s, String word) { if(s.length() <= 0) { words.add(word.trim()); return; } for(int i = 1; i <= s.length(); i++) { String temp = s.substring(0, i); if(dict.contains(temp)) { if(i == s.length()) { wordBreak(n, dict, "", word + " " + temp); } else { wordBreak(n, dict, s.substring(i, s.length()), word + " " + temp); } } } }} 0 blank551k2 months ago static void word(ArrayList<String> a, ArrayList<String> dict, String s, String curr, int i){ if(i>=s.length()){ if(dict.contains(curr)){ // s = "(" + s + ")"; a.add(s); } return ; } if(dict.contains(curr)){ String temp=s.substring(0,i)+" "+s.substring(i); word(a,dict,temp,""+s.charAt(i),i+2); } word(a,dict,s,curr+s.charAt(i),i+1); } static List<String> wordBreak(int n, List<String> mydict, String s) { ArrayList<String> dict= new ArrayList<String>(mydict); ArrayList<String> a = new ArrayList<String>(); word(a,dict,s,"",0); return a; } +1 aloksinghbais022 months ago C++ solution using backtracking is as follows :- Execution Time :- 0.0 / 1.1 sec unordered_map<string,bool> mp; vector<string> helper(string str,int i,int j){ vector<string> ans; string temp = str.substr(i,j-i+1); if(mp[temp]) ans.push_back(temp); for(int k = i; k < j; k++){ string left = str.substr(i,k-i+1); if(mp[left]){ vector<string> v = helper(str,k+1,j); for(auto right: v){ ans.push_back(left + " " + right); } } } return (ans); } vector<string> wordBreak(int n, vector<string>& dict, string s){ for(auto str: dict){ mp[str] = true; } return helper(s,0,s.length()-1); } +1 choudharymanojloul8442 months ago public:vector<string> ans; map<string,int>mp; void solve(string &s,string &v,int pos) { if(pos==s.size()) { v.pop_back(); ans.push_back(v); return; } string temp=""; for(int i=pos;i<s.size();++i) { temp+=s[i]; if(mp.find(s.substr(pos,i-pos+1))!=mp.end()) { string p=v+temp+" "; solve(s,p,i+1); } } } vector<string> wordBreak(int n, vector<string>& dict, string s) { // code here for(int i=0;i<n;++i) mp[dict[i]]++; string str; solve(s,str,0); // cout<<endl; return ans; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 468, "s": 238, "text": "Given a string s and a dictionary of words dict of length n, add spaces in s to construct a sentence where each word is a valid dictionary word. Each dictionary word can be used more than once. Return all such possible sentences." }, { "code": null, "e": 510, "s": 468, "text": "Follow examples for better understanding." }, { "code": null, "e": 521, "s": 510, "text": "Example 1:" }, { "code": null, "e": 717, "s": 521, "text": "Input: s = \"catsanddog\", n = 5 \ndict = {\"cats\", \"cat\", \"and\", \"sand\", \"dog\"}\nOutput: (cats and dog)(cat sand dog)\nExplanation: All the words in the given \nsentences are present in the dictionary." }, { "code": null, "e": 728, "s": 717, "text": "Example 2:" }, { "code": null, "e": 919, "s": 728, "text": "Input: s = \"catsandog\", n = 5\ndict = {\"cats\", \"cat\", \"and\", \"sand\", \"dog\"}\nOutput: Empty\nExplanation: There is no possible breaking \nof the string s where all the words are present \nin dict." }, { "code": null, "e": 1170, "s": 919, "text": "Your Task:\nYou do not need to read input or print anything. Your task is to complete the function wordBreak() which takes n, dict and s as input parameters and returns a list of possible sentences. If no sentence is possible it returns an empty list." }, { "code": null, "e": 1250, "s": 1170, "text": "Expected Time Complexity: O(N2*n) where N = |s|\nExpected Auxiliary Space: O(N2)" }, { "code": null, "e": 1306, "s": 1250, "text": "Constraints:\n1 ≤ n ≤ 20\n1 ≤ dict[i] ≤ 15\n1 ≤ |s| ≤ 500 " }, { "code": null, "e": 1308, "s": 1306, "text": "0" }, { "code": null, "e": 1337, "s": 1308, "text": "pranavkhandare45451 week ago" }, { "code": null, "e": 1357, "s": 1337, "text": "//simple java code " }, { "code": null, "e": 1789, "s": 1357, "text": "static List<String> wordBreak(int n, List<String> dict, String s) { // code here List<String> list = new ArrayList<>(); helper(list, s, dict, new StringBuilder()); return list; } static void helper(List<String> list, String s, List<String> dict, StringBuilder str){ if(s.length() == 0){ str.deleteCharAt(str.length()-1); list.add(str.toString());" }, { "code": null, "e": 2149, "s": 1789, "text": " return; } for(int i = 0; i <= s.length(); i++){ String sub = s.substring(0,i); int l = str.length(); if(dict.contains(sub)){ str.append(sub+ \" \"); helper(list, s.substring(i), dict, str); str.delete(l, str.length()); } }" }, { "code": null, "e": 2151, "s": 2149, "text": "0" }, { "code": null, "e": 2173, "s": 2151, "text": "phenomenal11 week ago" }, { "code": null, "e": 2188, "s": 2173, "text": "JAVA Solution:" }, { "code": null, "e": 2863, "s": 2188, "text": "class Solution{\n static List<String> wordBreak(int n, List<String> dict, String s)\n {\n List<String> ans = new ArrayList<>();\n String res=\"\";\n solve(s,dict,res,ans);\n \n return ans;\n }\n \n static void solve(String s,List<String> dict,String res,List<String> ans)\n {\n \n if(s.length()==0)\n {\n res=res.trim();\n ans.add(res);\n return;\n }\n \n for(int i=0;i<s.length();i++)\n {\n if(dict.contains(s.substring(0,i+1)))\n {\n solve(s.substring(i+1),dict,res+s.substring(0,i+1)+\" \",ans);\n }\n }\n }\n}" }, { "code": null, "e": 2865, "s": 2863, "text": "0" }, { "code": null, "e": 2888, "s": 2865, "text": "sandeep55212 weeks ago" }, { "code": null, "e": 2937, "s": 2888, "text": "C++ (DP+Backtracking) Solution (Time taken 0.01)" }, { "code": null, "e": 3850, "s": 2937, "text": "bool func(string &s,int b,int n, unordered_set<string> &us,string &a,vector<string> &ans,vector<int> &dp){\n if(b==n){\n a.pop_back();\n ans.push_back(a);\n return true;\n }\n if(dp[b]!=-1 and !dp[b]) return dp[b];\n string t,p;\n p=a;\n int flag=1;\n for(int i=b;i<n;i++){\n t.push_back(s[i]);\n if(us.find(t)==us.end()) continue;\n a+=t;a+=\" \";\n if(func(s,i+1,n,us,a,ans,dp)) flag=0;\n a=p; // backtracking\n }\n if(flag) return dp[b]=false;\n return dp[b]=true;\n }\n vector<string> wordBreak(int n, vector<string>& wordDict, string &s)\n {\n // code here\n unordered_set<string> us;\n string a;\n vector<string> ans;\n n=s.size();\n vector<int> dp(n,-1);\n for(auto i:wordDict) us.insert(i);\n func(s,0,n,us,a,ans,dp);\n return ans;\n }" }, { "code": null, "e": 3852, "s": 3850, "text": "0" }, { "code": null, "e": 3877, "s": 3852, "text": "shilsoumyadip2 weeks ago" }, { "code": null, "e": 4462, "s": 3877, "text": "class Solution{public: vector<string> v;void solve ( int i , vector<string> dict, string s, string temp){ string sum = \"\"; for (int j=i; j< s.length(); j++) { sum+= s[j];if (find(dict.begin(), dict.end(), sum) != dict.end()){ solve( j+1 , dict, s, temp+sum+\" \"); } } if (i >= s.length()){ temp.pop_back(); v.push_back (temp); } } vector<string> wordBreak(int n, vector<string>& dict, string s) { solve( 0 , dict, s,\"\"); return v; } };" }, { "code": null, "e": 4464, "s": 4462, "text": "0" }, { "code": null, "e": 4499, "s": 4464, "text": "gaurabhkumarjha271020014 weeks ago" }, { "code": null, "e": 5097, "s": 4499, "text": "// in c++\n vector<string> v;\n void solve (vector<string> dict, string s, string temp, int i){\n \n if (i >= s.length()){\n temp.pop_back();\n v.push_back (temp);\n }\n \n string str;\n for (int j=i; j< s.length(); j++){\n str+= s[j];\n if (find(dict.begin(), dict.end(), str) != dict.end()){\n solve(dict, s, temp+str+' ', j+1);\n }\n }\n }\n vector<string> wordBreak(int n, vector<string>& dict, string s)\n {\n solve(dict, s, \"\", 0);\n return v;\n \n } " }, { "code": null, "e": 5099, "s": 5097, "text": "0" }, { "code": null, "e": 5123, "s": 5099, "text": "harrypotter01 month ago" }, { "code": null, "e": 6081, "s": 5123, "text": "## Word Break -2 def helper(n, curr, ans, dict,s ,n1): if len(s)==0: x = curr[:len(curr)-1] ans.add(x) return for i in range(n1+1): left = s[:i] if left in dict: right = s[i:] curr = curr + (s[:i]+\" \") helper(n, curr, ans, dict, right, n1) curr = curr[::-1].replace(str(s[:i]+\" \")[::-1], \"\",1)[::-1] return ans " }, { "code": null, "e": 6287, "s": 6081, "text": "class Solution: def wordBreak(self, n, dict, s): ans = helper(n, \"\", set(), dict, s, len(s)) return list(ans) " }, { "code": null, "e": 6289, "s": 6287, "text": "0" }, { "code": null, "e": 6314, "s": 6289, "text": "parikhsharan61 month ago" }, { "code": null, "e": 6336, "s": 6314, "text": "// Java solution 0.3s" }, { "code": null, "e": 7149, "s": 6338, "text": "class Solution{ private static List<String> words = null; static List<String> wordBreak(int n, List<String> dict, String s) { words = new ArrayList<>(); wordBreak(n, dict, s, \"\"); return words; } private static void wordBreak(int n, List<String> dict, String s, String word) { if(s.length() <= 0) { words.add(word.trim()); return; } for(int i = 1; i <= s.length(); i++) { String temp = s.substring(0, i); if(dict.contains(temp)) { if(i == s.length()) { wordBreak(n, dict, \"\", word + \" \" + temp); } else { wordBreak(n, dict, s.substring(i, s.length()), word + \" \" + temp); } } } }}" }, { "code": null, "e": 7153, "s": 7151, "text": "0" }, { "code": null, "e": 7175, "s": 7153, "text": "blank551k2 months ago" }, { "code": null, "e": 7891, "s": 7175, "text": " static void word(ArrayList<String> a, ArrayList<String> dict, String s, String curr, int i){\n if(i>=s.length()){\n if(dict.contains(curr)){\n // s = \"(\" + s + \")\";\n a.add(s);\n }\n return ;\n }\n if(dict.contains(curr)){\n String temp=s.substring(0,i)+\" \"+s.substring(i);\n word(a,dict,temp,\"\"+s.charAt(i),i+2);\n }\n word(a,dict,s,curr+s.charAt(i),i+1);\n }\n \n static List<String> wordBreak(int n, List<String> mydict, String s)\n {\n ArrayList<String> dict= new ArrayList<String>(mydict);\n ArrayList<String> a = new ArrayList<String>();\n word(a,dict,s,\"\",0);\n return a;\n \n }" }, { "code": null, "e": 7894, "s": 7891, "text": "+1" }, { "code": null, "e": 7922, "s": 7894, "text": "aloksinghbais022 months ago" }, { "code": null, "e": 7972, "s": 7922, "text": "C++ solution using backtracking is as follows :- " }, { "code": null, "e": 8006, "s": 7974, "text": "Execution Time :- 0.0 / 1.1 sec" }, { "code": null, "e": 8695, "s": 8008, "text": "unordered_map<string,bool> mp; vector<string> helper(string str,int i,int j){ vector<string> ans; string temp = str.substr(i,j-i+1); if(mp[temp]) ans.push_back(temp); for(int k = i; k < j; k++){ string left = str.substr(i,k-i+1); if(mp[left]){ vector<string> v = helper(str,k+1,j); for(auto right: v){ ans.push_back(left + \" \" + right); } } } return (ans); } vector<string> wordBreak(int n, vector<string>& dict, string s){ for(auto str: dict){ mp[str] = true; } return helper(s,0,s.length()-1); }" }, { "code": null, "e": 8698, "s": 8695, "text": "+1" }, { "code": null, "e": 8732, "s": 8698, "text": "choudharymanojloul8442 months ago" }, { "code": null, "e": 9442, "s": 8732, "text": "public:vector<string> ans;\n map<string,int>mp; \n void solve(string &s,string &v,int pos)\n {\n if(pos==s.size())\n {\n v.pop_back();\n ans.push_back(v);\n return;\n }\n \n string temp=\"\";\n for(int i=pos;i<s.size();++i)\n {\n temp+=s[i];\n if(mp.find(s.substr(pos,i-pos+1))!=mp.end())\n {\n string p=v+temp+\" \";\n solve(s,p,i+1);\n \n }\n }\n }\n vector<string> wordBreak(int n, vector<string>& dict, string s)\n {\n // code here\n for(int i=0;i<n;++i)\n mp[dict[i]]++;\n string str;\n solve(s,str,0);\n // cout<<endl;\n return ans;\n }" }, { "code": null, "e": 9588, "s": 9442, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 9624, "s": 9588, "text": " Login to access your submissions. " }, { "code": null, "e": 9634, "s": 9624, "text": "\nProblem\n" }, { "code": null, "e": 9644, "s": 9634, "text": "\nContest\n" }, { "code": null, "e": 9707, "s": 9644, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 9855, "s": 9707, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 10063, "s": 9855, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 10169, "s": 10063, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to Create Publication-Ready Plots with LaTeX | by Aruna Pisharody | Towards Data Science
If you’ve ever written an article in a scientific journal, chances are that you’ve used a LaTeX template for preparing your manuscript. It is after all the industry standard in typesetting documents. However, how many of you have considered LaTeX as a plotting tool? LaTeX offers a powerful visualization library, PGFPlots, based on its graphics system, PGF/TikZ. This makes it effortless to include plots directly within your .tex document. It has a simple user-interface that even amateur programmers can comfortably master. However, there is a staggering variety of other plotting options available to us online; be it popular data science programming languages such as Python and R, who boast of their own impressive data visualization libraries, or plotting software such as Origin, Veusz, GraphRobot, and Orange. Most such options also afford the flexibility to work with very large datasets and execute complex mathematical computations, which, unfortunately, the PGFPlots library does not. However, if these drawbacks do not pose an issue for you, the PGFPlots library will assuredly render you the highest quality plots compared to most other options available today. However, although not as steep as other languages/tools, plotting with LaTeX also comes with its own learning curve. PGFPlots does provide its own comprehensive manual, but you need to know what to search for to find your answers in there! And, often times, we are looking for abstract ideas rather than a complete picture. And this is where sites like tex.stackexchange.com comes to the rescue. Even so, I still had to dig through tons of stackexchange posts and suffer through numerous trial-and-error before I struck gold. Ergo my decision to write this article. I hope to introduce you to the basics of plotting in LaTeX by working through 5 types of fundamental plots one may encounter in a scientific publication. Each plot will be focused on different types of customization available in the PGFPlots library. You will need only a basic familiarity with LaTeX to understand this article. Of course, this is just to kick off your journey into plotting with LaTeX. I hope to dive into more complex plots in future articles, so consider this as setting the scene for a series of articles. So without further ado, let’s get started! Let’s begin by setting the document preamble for plotting in LaTeX. As with any .tex file, we’ll begin by defining our document type using the \documentclass command. We’ll also add the recommended encoding package for our document. Since we are plotting using PGFPlots, we’ll be calling the PGFPlots package. The \pgfplotsset command in the next line is used to define a particular set of options for the entire document (or, as we’ll see later, a part of the document). In this case, we are setting the compatibility option for the entire document to be PGFPlots 1.9 to ensure backward compatibility. Note: it is a good practice to always include this line in your preamble to avoid changes in your output due to version updates. \documentclass[12pt, a4paper]{article}\usepackage[utf8]{inputenc}\usepackage{pgfplots}\pgfplotsset{compat=1.9} Next, let us set some common style specifications for our plots using the \pgfplotsset command (named myplotstyle). Note: if needed, we can always override these styles within a particular axis environment. \pgfplotsset{ myplotstyle/.style={ legend style={draw=none, font=\small}, legend cell align=left, legend pos=north east, ylabel style={align=center, font=\bfseries\boldmath}, xlabel style={align=center, font=\bfseries\boldmath}, x tick label style={font=\bfseries\boldmath}, y tick label style={font=\bfseries\boldmath}, scaled ticks=false, every axis plot/.append style={thick}, },} A brief description of the styling options mentioned above: legend style , legend cell align , and legend pos : used for legend styling; in this case, sets a legend without border, \small font, left-aligned text, and positioned to the north-east of the plotxlabel style and ylabel style : used to change x-axis and y-axis label styles; here, they are used to bold the axes labels (\bfseries for text and \boldmath for numerical axes labels) and align them to the center of the axesx tick label style and y tick label style : used to set axes tick label styles; here, the tick font is set to be bold for both text and numerical tick labelsevery axis plot./append style : used to set styles for every axis within a plot; here, thickness of lines and markers in the plot is set to be thick . Note: here, I have used every axis plot option to change the line widths for the plots onlyscaled y ticks=false : used to prevent PGFPlots from factoring out common exponents for axes tick labels legend style , legend cell align , and legend pos : used for legend styling; in this case, sets a legend without border, \small font, left-aligned text, and positioned to the north-east of the plot xlabel style and ylabel style : used to change x-axis and y-axis label styles; here, they are used to bold the axes labels (\bfseries for text and \boldmath for numerical axes labels) and align them to the center of the axes x tick label style and y tick label style : used to set axes tick label styles; here, the tick font is set to be bold for both text and numerical tick labels every axis plot./append style : used to set styles for every axis within a plot; here, thickness of lines and markers in the plot is set to be thick . Note: here, I have used every axis plot option to change the line widths for the plots only scaled y ticks=false : used to prevent PGFPlots from factoring out common exponents for axes tick labels Now, let us define a simple plotting environment styled using myplotstyle to check how it looks! The code for this purpose is given below: \begin{tikzpicture}\begin{axis}[ myplotstyle,]\end{axis}\end{tikzpicture} Since PGFPlots is based on PGF/TikZ, each plot should be placed within a picture environment given by \begin{tikzpicture} ... \end{tikzpicture}. Within this, we will define a normal axis environment and set our preferred stylings for it. On the right hand side, we can see how our simple axes plot looks like! Note: I have added a comma after my last styling option, myplotstyle . Although this is not a requirement, it is a good practice to follow. This way you can mitigate any potential errors that may surface when introducing additional styling options at a later point in time. Next, let’s move on and check out how to use datasets for creating plots. For larger datasets, it would be prudent to save the .csv files externally. However, in the case of smaller datasets, as I have used in the present article, you can always define them locally within the .tex file outside the \begin{document} ... \end{document} tags. This can be done using the following code: \begin{filecontents*}{filename.csv}...\end{filecontents*} In either case, we can use the same method described in the following section to add data for plotting. Looks like we’re all set to move forward with plotting now. Let’s get plotting! The first plot that we’ll be creating is a simple line plot (in our case, with markers). The dataset I’ll be using for this purpose is shown below. Note: for brevity, I’m only using the first four months for my explanation; I have, however, also added a figure for how our plot will look like when including the entire dataset. Now, let’s start plotting our dataset. The format for plotting columns from a dataset is as shown below: \addplot+[<options>] table[x=colname,y=colname, col sep=sep] {filename.csv}; It is required to add a ; after each \addplot command. Note: you can also use \addplot[<options>] instead of \addplot+[<options] . The difference between the two is only in whether you wish to append your <options> to the default cycle list (options controlling line styles) or ignore the cycle list completely. For details regarding the different cycle list available in PGFPlots, you may refer to Chapter 4, Section 4.7.7 in the PGFPlots manual. Let’s just combine all that we learnt till now to create a simple line plot using our dataset. The code so far is shown below: \begin{tikzpicture}\begin{axis}[ myplotstyle,]\addplot+[] table[x=year,y=Jan, col sep=comma] {Fig_lineplot.csv};\addplot+[] table[x=year,y=Feb, col sep=comma] {Fig_lineplot.csv};\addplot+[] table[x=year,y=Mar, col sep=comma] {Fig_lineplot.csv};\addplot+[] table[x=year,y=Apr, col sep=comma] {Fig_lineplot.csv};\end{axis}\end{tikzpicture} As we can see from the figure on the left hand side, significant work is still required to make this plot appealing. Let’s tackle the x-axis and y-axis labels first! Adding the axes labels is very straightforward. Simply add xlabel={Year} and ylabel={No. of passengers} within the axis options. Another obvious styling is adding the legend keys. This can be done by adding legend entries={Jan, Feb, Mar, Apr} . Also, myplotstlye positions the legend to the north-east of our plot. As can be observed from our plot, that would block the plot content in this case. Therefore, let’s move our legend for this plot to the south-east using legend pos=south east . Other options available for legend pos are south west, north east, and north west . You can also add the legend keys outside the plot by using the option outer north east. There is a glaring mistake in the plotted figure; each x-tick label is a year, but is displayed with a comma separator. This can be fixed by changing the number format of the x-tick label as: x tick label style={/pgf/number format/.cd, set thousands separator={}} I would also like the x-tick label to be rotated by 90 degrees, so I’ll also add rotate=90 to the x-tick label styling. The final axis options are as follows: \begin{axis}[ myplotstyle, legend pos=south east, legend entries={Jan, Feb, Mar, Apr}, xlabel={Year}, ylabel={No. of passengers}, x tick label style={rotate=90, /pgf/number format/.cd, set thousands separator={}}, ]} Let’s start styling our lines and markers now. These style options are to be included within the \addplot+[<options>] . Let’s add the following options for lines/markers: smooth : interpolates between two points to make the transition smooth smooth : interpolates between two points to make the transition smooth 2. mark= : you can either specify your preferred marker style (an extensive list of marks option is provided in the PGFPlots manual) or use the default line styles in the cycle list . Adding a * at the end (say, triangle*) signifies that the marker needs to be filled with the corresponding line color 3. mark options={} : here, you can specify marker size , whether you wish to scale the marker size, fill it with a specific color, etc. A sample \addplot command with options will look like this: \addplot+[smooth, mark=diamond*, mark options={scale=2,fill=white}] table[x=year,y=Jan, col sep=comma] {Fig_lineplot.csv}; And it’s as simple as that! The final code put together will look like this: \begin{tikzpicture}\begin{axis}[ myplotstyle, legend pos=south east, legend entries={Jan, Feb, Mar, Apr}, xlabel={Year}, ylabel={No. of passengers}, x tick label style={rotate=90, /pgf/number format/.cd, set thousands separator={}},]\addplot+[smooth, mark=diamond*, mark options={scale=2,fill=white}] table[x=year,y=Jan, col sep=comma] {Fig_lineplot.csv};\addplot+[smooth, mark=*, mark options={scale=1.5,fill=white}] table[x=year,y=Feb, col sep=comma] {Fig_lineplot.csv};\addplot+[smooth,, mark=triangle*, mark options={scale=2,fill=white}] table[x=year,y=Mar, col sep=comma] {Fig_lineplot.csv};\addplot+[smooth, mark=square*, mark options={scale=1.5,fill=white}] table[x=year,y=Apr, col sep=comma] {Fig_lineplot.csv};\end{axis}\end{tikzpicture} And this is the final plot outcome: A sample plot using the entire dataset is also shown below: The next plot we’re going to generate is a simple logarithmic plot. We’ll use this plot to explore two customizations: How to plot a log-log or semi-log plot using PGFPlots?How to use column data from .csv files as axis tick labels? How to plot a log-log or semi-log plot using PGFPlots? How to use column data from .csv files as axis tick labels? The dataset used for this plot is shown below. As we can see from the dataset, it has two columns: month and corresponding number of confirmed COVID-19 cases in the state of Maharashtra in India for the year 2020. Only one of these columns needs to be plotted; the other column is to be used as the x-axis tick labels. So how do we go about plotting this using PGFPlots? Let’s first create a simple plot based on what we have learnt so far: \begin{tikzpicture}\begin{axis}[ myplotstyle, xlabel={Month $(2020)$}, ylabel={No. of confirmed cases},]\addplot+[mark=o,mark options={scale=1.5}] table[x expr=\coordindex, y=confirmed, col sep=comma] {Fig_semilogplot.csv};\end{axis}\end{tikzpicture} Here, since we do not have any column to be plotted on the x-axis, we use x expr=\coordindex to plot the y-axis data against coordinate index. The plot that we get is shown on the left hand side. It is difficult to correctly infer the pandemic behavior from this plot. In such cases, it is more prudent to rearrange this information on a log-log axis (in our case, a semi-log axis). In order to change our plot from normal to semi-log, we’ll need to modify the axis environment from begin{axis} ... \end{axis} to \begin{semilogyaxis} ... \end{semilogyaxis} (since we want to change only our y-axis to logarithmic scale). Other options for logarithmic axis environments include semilogxaxis and loglogaxis . As can be seen from this figure, we can infer the trend with greater clarity using the semi-log feature in our plot. However, there are still many issues with the plot. Taking a look at the x-axis tick labels, we can see that no information can be gained from the default ticks provided by x expr=\coordindex . To use the month column values in the .csv file as x-axis tick labels, we will add the following axis options: table/col sep=comma,xticklabels from table={filename.csv}{colname} First, we need to specify the column separator for our .csv file using the table/col sep option. Then, we can direct PGFPlots to retrieve the x-tick labels from a particular column in the table using the command xticklabels from table . Another styling preference is how to display the logarithmic axis tick labels. Some prefer to display it using scientific notation, while others would like the numbers to be displayed as is. If you wish to display the logarithmic axis tick labels as a fixed number, then you can use the command log ticks with fixed point to display all logarithmic axes with fixed number notations. Since a semi-log plot has only a single logarithmic axis, this is quite straightforward to use. However, if you’re plotting a log-log figure and wish to modify only a single logarithmic axis to fixed number notations, then this post on stackexchange can help! We’re almost done with our styling! Let’s rotate the x-tick labels by 90 degrees using the command that we learnt before. Also, we’ll use xtick option to specify tick positions for our plot. The possible values for the xtick option are \empty , data , or {<list of coordinates>}. \empty will produce no tick marks and {<list of coordinates>} will produce tick marks at the provided coordinates. Since we are specifying our x-axis tick labels from .csv file, we will use xtick=data to produce tick marks at every coordinate of our plot. And one final modification before we are done; since we’re using discrete data points for plotting, we will remove the line joining the markers. For this purpose, PGFPlots provides us with the only marks option that can be added to the \addplot command. Note: in contrast, if you wish to show only lines without markers, you can use the no marks option. And that’s it! Our final code for the semi-log plot will look like this: \begin{tikzpicture}\begin{semilogyaxis}[ myplotstyle, table/col sep=comma, xticklabels from table={Fig_loglog_lineplot.csv}{month}, xtick=data, x tick label style={rotate=90}, xlabel={Month $(2020)$}, ylabel={No. of confirmed cases}, log ticks with fixed point,]\addplot+[only marks, mark=o, mark options={scale=1.5}] table[x expr=\coordindex, y=confirmed, col sep=comma] {Fig_loglog_lineplot.csv};\end{semilogyaxis}\end{tikzpicture} Here, we can see how our corresponding plot looks like: Moving on to our next plot now! Let’s take a look at how to plot a secondary y-axis. For ease of plotting, I have modified the tips dataset provided by seaborn (Python plotting library) into two separate .csv files (tip amount during lunch hour and tip amount during dinner hour). Note: you can also use multiple columns within a single .csv file to plot the same. We’ll begin by writing down the specifications for the two axes environments that we’re interested in. \begin{tikzpicture}%% axis 1 %%\begin{axis}[ myplotstyle, scale only axis, axis y line*=left, xlabel={Total bill $(\$)$}, ylabel={Tips $(\$)$},]\addplot+[only marks, mark=*, mark options={scale=1.5, fill=white}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_1.csv};\end{axis}%% axis 2 %%\begin{axis}[ myplotstyle, scale only axis, axis y line*=right, axis x line=none, ylabel={Tips $(\$)$},]\addplot+[only marks, mark=triangle*, mark options={scale=1.5, fill=white}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_2.csv};\end{axis}\end{tikzpicture} Now, we’ll layer the two environments over each other. For this, we will use the \pgfplotsset{set layers} option right after \begin{tikzpicture}. Some additional styling options also need to be specified: axis y line*=left/right : specifies which dataset is shown on which y-axis. Note: the * signifies that axes will not have arrow headsaxis x line=none : hides x-axis line for the second plotscale only axis : forces both y-axes dimensions to be the same axis y line*=left/right : specifies which dataset is shown on which y-axis. Note: the * signifies that axes will not have arrow heads axis x line=none : hides x-axis line for the second plot scale only axis : forces both y-axes dimensions to be the same The combined code now looks like this: \begin{tikzpicture}\pgfplotsset{set layers}%% axis 1 %%\begin{axis}[ myplotstyle, scale only axis, axis y line*=left, xlabel={Total bill $(\$)$}, ylabel={Tips $(\$)$},]\addplot+[only marks, mark=*, mark options={scale=1.5, fill=white}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_1.csv};\end{axis}%% axis 2 %%\begin{axis}[ myplotstyle, scale only axis, axis y line*=right, axis x line=none, ylabel={Tips $(\$)$},]\addplot+[only marks, mark=triangle*, mark options={scale=1.5, fill=white}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_2.csv};\end{axis}\end{tikzpicture} The initial plot based on these specifications is shown below: What styling options can we add to make this plot more appealing? Let’s start by making both the y-axes limits to be the same. This can be done adding ymin and ymax for both axes. Let us also change the color of the left ordinate to blue and right to red. We do this by setting the options y axis line style , y tick label style , and ylabel style for both axes. We’ll also match the marker color to their corresponding axis color. The code thus far is: \begin{tikzpicture}\pgfplotsset{set layers}%% axis 1 %%\begin{axis}[ myplotstyle, scale only axis, axis y line*=left, ymin=0, ymax=7, y axis line style={blue}, y tick label style={blue}, ylabel style={blue}, xlabel={Total bill $(\$)$}, ylabel={Tips $(\$)$},]\addplot+[only marks, mark=*, mark options={scale=1.5, fill=white}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_1.csv};\end{axis}%% axis 2%%\begin{axis}[ myplotstyle, scale only axis, axis y line*=right, ymin=0, ymax=7, axis x line=none, y axis line style={red}, tick label style={red}, ylabel style={red}, ylabel={Tips $(\$)$},]\addplot+[only marks, mark=triangle*, color=red, mark options={scale=1.5, fill=white}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_2.csv};\end{axis}\end{tikzpicture} This is how our plot looks like now: Since our y-axes labels are the same, it would be prudent to also add a legend to make this plot more informative. We’ll need some tweaking to render a single legend for both axes environments. I used the workaround proposed on stackexchange for this purpose. We’ll add a label to the first plot and use this label to create a legend entry for the first plot inside the second axis environment. The final code put together will look like this: \begin{tikzpicture}\pgfplotsset{set layers}\begin{axis}[ myplotstyle, scale only axis, axis y line*=left, ymin=0, ymax=7, y axis line style={blue}, y tick label style={blue}, ylabel style={blue}, xlabel={Total bill $(\$)$}, ylabel={Tips $(\$)$},]\addplot+[only marks, mark=*, mark options={scale=1.5, fill=white}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_1.csv};\label{multiplot:plot1}\end{axis}\begin{axis}[ myplotstyle, scale only axis, axis y line*=right, ymin=0, ymax=7, axis x line=none, y axis line style={red}, y tick label style={red}, ylabel style={red}, ylabel={Tips $(\$)$}, legend pos=south east,]\addlegendimage{/pgfplots/refstyle=multiplot:plot1}\addlegendentry{Tips during lunch hour}\addplot+[only marks, mark=triangle*, color=red, mark options={scale=1.5, fill=white}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_2.csv};\addlegendentry{Tips during dinner hour}\end{axis}\end{tikzpicture} As we can see from the code above, another way to add a legend entry is using the \addlegendentry[<options>]{text} after the \addplot command. I have used \addlegendimage{} command with it for referencing the line style of the first plot. We will then add the legend for the plot in this axis environment after its corresponding \addplot command. Note: I have added the legend of the first plot before the \addplot command in the second plot to preserve order. And there we have it! This is our final plot: The next scenario we’re going to tackle is how to add text within plots. For this, let’s once again use the tips dataset (both lunch and dinner hour datasets combined) to create a mean plot. As always, let’s begin by using what we have learnt so far to create a basic plot: \begin{tikzpicture}\begin{axis}[ myplotstyle, xlabel={Total bill ($\$$)}, ylabel={Tips ($\$$)},]\addplot+[only marks, mark=square, color=red, mark options={scale=2}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_1.csv};\addplot+[only marks, mark=square, color=red, mark options={scale=2}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_2.csv};\end{axis}\end{tikzpicture} This is what we’re starting off with: Now, we need to add a mean line and two standard deviation lines (mean + 2σ and mean-2σ; I have calculated the necessary values beforehand). To plot constant values, we can either use the format \addplot+[]{constant} (in which case, we’ll have to specify the domain in which the line needs to be plotted) or \addplot+[] coordinates{(x,y)} . Note: I have used both the options for reference. I have also specified the domain for constant value plots. Since adding a domain can cause changes in the axis limits, I have added xmin , xmax, xtick, and ytick . This is our code so far: \begin{tikzpicture}\begin{axis}[ myplotstyle, xlabel={Total bill ($\$$)}, ylabel={Tips ($\$$)}, xmin=0, xmax=40, xtick={5,10,15,20,25,30,35}, ytick={1,2,3,4,5,6}, domain=5:35,]\addplot+[smooth, only marks, mark=square, mark options={scale=2,fill=white}, color=red] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_1.csv};\addplot+[smooth, only marks, mark=square, mark options={scale=2,fill=white}, color=red] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_2.csv};\addplot+[smooth, no marks, color=black, dashdotted] {2.97};\addplot+[smooth, no marks, color=black, solid] {0.62};\addplot+[smooth, no marks, color=black, solid] coordinates {(5, 5.32) (35, 5.32)};\end{axis}\end{tikzpicture} And the corresponding plot output is: The plot is incomplete until we add in the descriptions for each of the constant lines. The method I’m going to use here is to add a node at desired locations. I’ll be positioning my text based on rel axis cs (or, relative axis coordinate system; see figure below for details). The format followed for adding a node is: \node[<options>] at (rel axis cs: x,y) {text}; The final code after adding in the text descriptions will look this: \begin{tikzpicture}\begin{axis}[ myplotstyle, xlabel={Total bill ($\$$)}, ylabel={Tips ($\$$)}, xmin=0, xmax=40, xtick={5,10,15,20,25,30,35}, ytick={1,2,3,4,5,6}, domain=5:35,]\addplot+[smooth, only marks, mark=square, mark options={scale=2,fill=white}, color=red] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_1.csv};\addplot+[smooth, only marks, mark=square, mark options={scale=2,fill=white}, color=red] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_2.csv};\addplot+[smooth, no marks, color=black, dashdotted] {2.97};\node [] at (rel axis cs: 0.2,0.51) {Mean};\addplot+[smooth, no marks, color=black, solid] coordinates {(5, 5.32) (35, 5.32)};\node [] at (rel axis cs: 0.24,0.87) {Mean + $2\sigma$};\addplot+[smooth, no marks, color=black, solid] {0.62};\node [] at (rel axis cs: 0.23,0.13) {Mean - $2\sigma$};\end{axis}\end{tikzpicture} And we have our final plot as shown below: Now, the last plot I’ll be tackling in this article is a plot overlaid on an image. I’ll be using the image shown below for this purpose. Note: I’ll be removing the axes and tick labels provided in the chart below and instead adding in my own axes and tick labels. I’ll be using a fictitious weights dataset for this plot (see below). Let’s first create a simple plot based on our dataset. The code so far with the corresponding plot is given below: \begin{tikzpicture}\begin{axis}[ myplotstyle, legend pos=south east, legend entries={{\large Child 1}, {\large Child 2}}, xlabel={Age (in years)}, ylabel={Weight (in $kg$)},]\addplot+[only marks, mark options={scale=1.5}, mark=triangle,color=blue] table[x=age,y=weight1, col sep=comma] {Fig_overlaidplot.csv};\addplot+[only marks, mark options={scale=1.5}, mark=square,color=red] table[x=age,y=weight2, col sep=comma] {Fig_overlaidplot.csv};\end{axis}\end{tikzpicture} We’ll modify few things to have matching dimensions and axes tick labels for both our plot and the image: We’ll add width and height options to change dimension of our plotWe’ll use xmin, xmax , ymin , and ymax options to align our axis limits with the imageFinally, we’ll add xtick and ytick options to match our plot axes tick labels with those of the image (I have specified the weight for y-axis only in the metric unit) We’ll add width and height options to change dimension of our plot We’ll use xmin, xmax , ymin , and ymax options to align our axis limits with the image Finally, we’ll add xtick and ytick options to match our plot axes tick labels with those of the image (I have specified the weight for y-axis only in the metric unit) Our code put together will look like this: \begin{tikzpicture}\begin{axis}[ myplotstyle, legend pos=south east, legend entries={{\large Child 1}, {\large Child 2}}, xlabel={Age (in years)}, ylabel={Weight (in $kg$)}, ymin=5, ymax=105, ytick={10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100}, xmin=2, xmax=21, xtick={2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}, width=13cm, height=15cm,]\addplot+[only marks, mark options={scale=1.5}, mark=triangle,color=blue] table[x=age,y=weight1, col sep=comma] {Fig_overlaidplot.csv};\addplot+[only marks, mark options={scale=1.5}, mark=square,color=red] table[x=age,y=weight2, col sep=comma] {Fig_overlaidplot.csv};\end{axis}\end{tikzpicture} And the corresponding plot for this will be: Now, the command to add in graphics to the plot is: \addplot graphics[<options>] {figure.png}; The central idea behind this plot is to fit the graphics within our plot axes coordinates. Therefore, we’ll have to add the \addplot graphics command with options xmin , xmax , ymin , and ymax matching those of the main plot. I have also added the axis on top option to have the axis lines and ticks positioned over the image. And it’s as simple as that! The final code will be: \begin{tikzpicture}\begin{axis}[ myplotstyle, legend pos=south east, legend entries={{\large Child 1}, {\large Child 2}}, xlabel={Age (in years)}, ylabel={Weight (in $kg$)}, ymin=5, ymax=105, ytick={10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100}, xmin=2, xmax=21, xtick={2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}, axis on top, width=13cm, height=15cm,]\addplot+[only marks, mark options={scale=1.5}, mark=triangle,color=blue] table[x=age,y=weight1, col sep=comma] {Fig_overlaidplot.csv};\addplot+[only marks, mark options={scale=1.5}, mark=square,color=red] table[x=age,y=weight2, col sep=comma] {Fig_overlaidplot.csv};\addplot graphics[ymin=5, ymax=105, xmin=2, xmax=21] {Fig_comparisons.png};\end{axis}\end{tikzpicture} And our overlaid plot will look like this: And that’s a wrap... for this article! Of course, this is just a sliver of the whole scope that LaTeX presents to us! Plotting with LaTeX might look daunting to a beginner. My hope is that this article will help a newbie from getting overwhelmed by the wealth of information available to them and encourage them to use this amazing tool. I will even consider this article a success if it has persuaded you to at least give plotting with LaTeX a try!
[ { "code": null, "e": 439, "s": 172, "text": "If you’ve ever written an article in a scientific journal, chances are that you’ve used a LaTeX template for preparing your manuscript. It is after all the industry standard in typesetting documents. However, how many of you have considered LaTeX as a plotting tool?" }, { "code": null, "e": 1349, "s": 439, "text": "LaTeX offers a powerful visualization library, PGFPlots, based on its graphics system, PGF/TikZ. This makes it effortless to include plots directly within your .tex document. It has a simple user-interface that even amateur programmers can comfortably master. However, there is a staggering variety of other plotting options available to us online; be it popular data science programming languages such as Python and R, who boast of their own impressive data visualization libraries, or plotting software such as Origin, Veusz, GraphRobot, and Orange. Most such options also afford the flexibility to work with very large datasets and execute complex mathematical computations, which, unfortunately, the PGFPlots library does not. However, if these drawbacks do not pose an issue for you, the PGFPlots library will assuredly render you the highest quality plots compared to most other options available today." }, { "code": null, "e": 2442, "s": 1349, "text": "However, although not as steep as other languages/tools, plotting with LaTeX also comes with its own learning curve. PGFPlots does provide its own comprehensive manual, but you need to know what to search for to find your answers in there! And, often times, we are looking for abstract ideas rather than a complete picture. And this is where sites like tex.stackexchange.com comes to the rescue. Even so, I still had to dig through tons of stackexchange posts and suffer through numerous trial-and-error before I struck gold. Ergo my decision to write this article. I hope to introduce you to the basics of plotting in LaTeX by working through 5 types of fundamental plots one may encounter in a scientific publication. Each plot will be focused on different types of customization available in the PGFPlots library. You will need only a basic familiarity with LaTeX to understand this article. Of course, this is just to kick off your journey into plotting with LaTeX. I hope to dive into more complex plots in future articles, so consider this as setting the scene for a series of articles." }, { "code": null, "e": 2485, "s": 2442, "text": "So without further ado, let’s get started!" }, { "code": null, "e": 3217, "s": 2485, "text": "Let’s begin by setting the document preamble for plotting in LaTeX. As with any .tex file, we’ll begin by defining our document type using the \\documentclass command. We’ll also add the recommended encoding package for our document. Since we are plotting using PGFPlots, we’ll be calling the PGFPlots package. The \\pgfplotsset command in the next line is used to define a particular set of options for the entire document (or, as we’ll see later, a part of the document). In this case, we are setting the compatibility option for the entire document to be PGFPlots 1.9 to ensure backward compatibility. Note: it is a good practice to always include this line in your preamble to avoid changes in your output due to version updates." }, { "code": null, "e": 3328, "s": 3217, "text": "\\documentclass[12pt, a4paper]{article}\\usepackage[utf8]{inputenc}\\usepackage{pgfplots}\\pgfplotsset{compat=1.9}" }, { "code": null, "e": 3535, "s": 3328, "text": "Next, let us set some common style specifications for our plots using the \\pgfplotsset command (named myplotstyle). Note: if needed, we can always override these styles within a particular axis environment." }, { "code": null, "e": 3952, "s": 3535, "text": "\\pgfplotsset{ myplotstyle/.style={ legend style={draw=none, font=\\small}, legend cell align=left, legend pos=north east, ylabel style={align=center, font=\\bfseries\\boldmath}, xlabel style={align=center, font=\\bfseries\\boldmath}, x tick label style={font=\\bfseries\\boldmath}, y tick label style={font=\\bfseries\\boldmath}, scaled ticks=false, every axis plot/.append style={thick}, },}" }, { "code": null, "e": 4012, "s": 3952, "text": "A brief description of the styling options mentioned above:" }, { "code": null, "e": 4937, "s": 4012, "text": "legend style , legend cell align , and legend pos : used for legend styling; in this case, sets a legend without border, \\small font, left-aligned text, and positioned to the north-east of the plotxlabel style and ylabel style : used to change x-axis and y-axis label styles; here, they are used to bold the axes labels (\\bfseries for text and \\boldmath for numerical axes labels) and align them to the center of the axesx tick label style and y tick label style : used to set axes tick label styles; here, the tick font is set to be bold for both text and numerical tick labelsevery axis plot./append style : used to set styles for every axis within a plot; here, thickness of lines and markers in the plot is set to be thick . Note: here, I have used every axis plot option to change the line widths for the plots onlyscaled y ticks=false : used to prevent PGFPlots from factoring out common exponents for axes tick labels" }, { "code": null, "e": 5135, "s": 4937, "text": "legend style , legend cell align , and legend pos : used for legend styling; in this case, sets a legend without border, \\small font, left-aligned text, and positioned to the north-east of the plot" }, { "code": null, "e": 5360, "s": 5135, "text": "xlabel style and ylabel style : used to change x-axis and y-axis label styles; here, they are used to bold the axes labels (\\bfseries for text and \\boldmath for numerical axes labels) and align them to the center of the axes" }, { "code": null, "e": 5518, "s": 5360, "text": "x tick label style and y tick label style : used to set axes tick label styles; here, the tick font is set to be bold for both text and numerical tick labels" }, { "code": null, "e": 5761, "s": 5518, "text": "every axis plot./append style : used to set styles for every axis within a plot; here, thickness of lines and markers in the plot is set to be thick . Note: here, I have used every axis plot option to change the line widths for the plots only" }, { "code": null, "e": 5866, "s": 5761, "text": "scaled y ticks=false : used to prevent PGFPlots from factoring out common exponents for axes tick labels" }, { "code": null, "e": 6005, "s": 5866, "text": "Now, let us define a simple plotting environment styled using myplotstyle to check how it looks! The code for this purpose is given below:" }, { "code": null, "e": 6082, "s": 6005, "text": "\\begin{tikzpicture}\\begin{axis}[ myplotstyle,]\\end{axis}\\end{tikzpicture}" }, { "code": null, "e": 6666, "s": 6082, "text": "Since PGFPlots is based on PGF/TikZ, each plot should be placed within a picture environment given by \\begin{tikzpicture} ... \\end{tikzpicture}. Within this, we will define a normal axis environment and set our preferred stylings for it. On the right hand side, we can see how our simple axes plot looks like! Note: I have added a comma after my last styling option, myplotstyle . Although this is not a requirement, it is a good practice to follow. This way you can mitigate any potential errors that may surface when introducing additional styling options at a later point in time." }, { "code": null, "e": 7050, "s": 6666, "text": "Next, let’s move on and check out how to use datasets for creating plots. For larger datasets, it would be prudent to save the .csv files externally. However, in the case of smaller datasets, as I have used in the present article, you can always define them locally within the .tex file outside the \\begin{document} ... \\end{document} tags. This can be done using the following code:" }, { "code": null, "e": 7108, "s": 7050, "text": "\\begin{filecontents*}{filename.csv}...\\end{filecontents*}" }, { "code": null, "e": 7212, "s": 7108, "text": "In either case, we can use the same method described in the following section to add data for plotting." }, { "code": null, "e": 7292, "s": 7212, "text": "Looks like we’re all set to move forward with plotting now. Let’s get plotting!" }, { "code": null, "e": 7620, "s": 7292, "text": "The first plot that we’ll be creating is a simple line plot (in our case, with markers). The dataset I’ll be using for this purpose is shown below. Note: for brevity, I’m only using the first four months for my explanation; I have, however, also added a figure for how our plot will look like when including the entire dataset." }, { "code": null, "e": 7725, "s": 7620, "text": "Now, let’s start plotting our dataset. The format for plotting columns from a dataset is as shown below:" }, { "code": null, "e": 7802, "s": 7725, "text": "\\addplot+[<options>] table[x=colname,y=colname, col sep=sep] {filename.csv};" }, { "code": null, "e": 8250, "s": 7802, "text": "It is required to add a ; after each \\addplot command. Note: you can also use \\addplot[<options>] instead of \\addplot+[<options] . The difference between the two is only in whether you wish to append your <options> to the default cycle list (options controlling line styles) or ignore the cycle list completely. For details regarding the different cycle list available in PGFPlots, you may refer to Chapter 4, Section 4.7.7 in the PGFPlots manual." }, { "code": null, "e": 8377, "s": 8250, "text": "Let’s just combine all that we learnt till now to create a simple line plot using our dataset. The code so far is shown below:" }, { "code": null, "e": 8718, "s": 8377, "text": "\\begin{tikzpicture}\\begin{axis}[ myplotstyle,]\\addplot+[] table[x=year,y=Jan, col sep=comma] {Fig_lineplot.csv};\\addplot+[] table[x=year,y=Feb, col sep=comma] {Fig_lineplot.csv};\\addplot+[] table[x=year,y=Mar, col sep=comma] {Fig_lineplot.csv};\\addplot+[] table[x=year,y=Apr, col sep=comma] {Fig_lineplot.csv};\\end{axis}\\end{tikzpicture}" }, { "code": null, "e": 8835, "s": 8718, "text": "As we can see from the figure on the left hand side, significant work is still required to make this plot appealing." }, { "code": null, "e": 9548, "s": 8835, "text": "Let’s tackle the x-axis and y-axis labels first! Adding the axes labels is very straightforward. Simply add xlabel={Year} and ylabel={No. of passengers} within the axis options. Another obvious styling is adding the legend keys. This can be done by adding legend entries={Jan, Feb, Mar, Apr} . Also, myplotstlye positions the legend to the north-east of our plot. As can be observed from our plot, that would block the plot content in this case. Therefore, let’s move our legend for this plot to the south-east using legend pos=south east . Other options available for legend pos are south west, north east, and north west . You can also add the legend keys outside the plot by using the option outer north east." }, { "code": null, "e": 9740, "s": 9548, "text": "There is a glaring mistake in the plotted figure; each x-tick label is a year, but is displayed with a comma separator. This can be fixed by changing the number format of the x-tick label as:" }, { "code": null, "e": 9832, "s": 9740, "text": "x tick label style={/pgf/number format/.cd, set thousands separator={}}" }, { "code": null, "e": 9991, "s": 9832, "text": "I would also like the x-tick label to be rotated by 90 degrees, so I’ll also add rotate=90 to the x-tick label styling. The final axis options are as follows:" }, { "code": null, "e": 10232, "s": 9991, "text": "\\begin{axis}[ myplotstyle, legend pos=south east, legend entries={Jan, Feb, Mar, Apr}, xlabel={Year}, ylabel={No. of passengers}, x tick label style={rotate=90, /pgf/number format/.cd, set thousands separator={}}, ]}" }, { "code": null, "e": 10403, "s": 10232, "text": "Let’s start styling our lines and markers now. These style options are to be included within the \\addplot+[<options>] . Let’s add the following options for lines/markers:" }, { "code": null, "e": 10474, "s": 10403, "text": "smooth : interpolates between two points to make the transition smooth" }, { "code": null, "e": 10545, "s": 10474, "text": "smooth : interpolates between two points to make the transition smooth" }, { "code": null, "e": 10847, "s": 10545, "text": "2. mark= : you can either specify your preferred marker style (an extensive list of marks option is provided in the PGFPlots manual) or use the default line styles in the cycle list . Adding a * at the end (say, triangle*) signifies that the marker needs to be filled with the corresponding line color" }, { "code": null, "e": 10983, "s": 10847, "text": "3. mark options={} : here, you can specify marker size , whether you wish to scale the marker size, fill it with a specific color, etc." }, { "code": null, "e": 11043, "s": 10983, "text": "A sample \\addplot command with options will look like this:" }, { "code": null, "e": 11166, "s": 11043, "text": "\\addplot+[smooth, mark=diamond*, mark options={scale=2,fill=white}] table[x=year,y=Jan, col sep=comma] {Fig_lineplot.csv};" }, { "code": null, "e": 11243, "s": 11166, "text": "And it’s as simple as that! The final code put together will look like this:" }, { "code": null, "e": 12008, "s": 11243, "text": "\\begin{tikzpicture}\\begin{axis}[ myplotstyle, legend pos=south east, legend entries={Jan, Feb, Mar, Apr}, xlabel={Year}, ylabel={No. of passengers}, x tick label style={rotate=90, /pgf/number format/.cd, set thousands separator={}},]\\addplot+[smooth, mark=diamond*, mark options={scale=2,fill=white}] table[x=year,y=Jan, col sep=comma] {Fig_lineplot.csv};\\addplot+[smooth, mark=*, mark options={scale=1.5,fill=white}] table[x=year,y=Feb, col sep=comma] {Fig_lineplot.csv};\\addplot+[smooth,, mark=triangle*, mark options={scale=2,fill=white}] table[x=year,y=Mar, col sep=comma] {Fig_lineplot.csv};\\addplot+[smooth, mark=square*, mark options={scale=1.5,fill=white}] table[x=year,y=Apr, col sep=comma] {Fig_lineplot.csv};\\end{axis}\\end{tikzpicture}" }, { "code": null, "e": 12044, "s": 12008, "text": "And this is the final plot outcome:" }, { "code": null, "e": 12104, "s": 12044, "text": "A sample plot using the entire dataset is also shown below:" }, { "code": null, "e": 12223, "s": 12104, "text": "The next plot we’re going to generate is a simple logarithmic plot. We’ll use this plot to explore two customizations:" }, { "code": null, "e": 12337, "s": 12223, "text": "How to plot a log-log or semi-log plot using PGFPlots?How to use column data from .csv files as axis tick labels?" }, { "code": null, "e": 12392, "s": 12337, "text": "How to plot a log-log or semi-log plot using PGFPlots?" }, { "code": null, "e": 12452, "s": 12392, "text": "How to use column data from .csv files as axis tick labels?" }, { "code": null, "e": 12823, "s": 12452, "text": "The dataset used for this plot is shown below. As we can see from the dataset, it has two columns: month and corresponding number of confirmed COVID-19 cases in the state of Maharashtra in India for the year 2020. Only one of these columns needs to be plotted; the other column is to be used as the x-axis tick labels. So how do we go about plotting this using PGFPlots?" }, { "code": null, "e": 12893, "s": 12823, "text": "Let’s first create a simple plot based on what we have learnt so far:" }, { "code": null, "e": 13153, "s": 12893, "text": "\\begin{tikzpicture}\\begin{axis}[ myplotstyle, xlabel={Month $(2020)$}, ylabel={No. of confirmed cases},]\\addplot+[mark=o,mark options={scale=1.5}] table[x expr=\\coordindex, y=confirmed, col sep=comma] {Fig_semilogplot.csv};\\end{axis}\\end{tikzpicture}" }, { "code": null, "e": 13977, "s": 13153, "text": "Here, since we do not have any column to be plotted on the x-axis, we use x expr=\\coordindex to plot the y-axis data against coordinate index. The plot that we get is shown on the left hand side. It is difficult to correctly infer the pandemic behavior from this plot. In such cases, it is more prudent to rearrange this information on a log-log axis (in our case, a semi-log axis). In order to change our plot from normal to semi-log, we’ll need to modify the axis environment from begin{axis} ... \\end{axis} to \\begin{semilogyaxis} ... \\end{semilogyaxis} (since we want to change only our y-axis to logarithmic scale). Other options for logarithmic axis environments include semilogxaxis and loglogaxis . As can be seen from this figure, we can infer the trend with greater clarity using the semi-log feature in our plot." }, { "code": null, "e": 14282, "s": 13977, "text": "However, there are still many issues with the plot. Taking a look at the x-axis tick labels, we can see that no information can be gained from the default ticks provided by x expr=\\coordindex . To use the month column values in the .csv file as x-axis tick labels, we will add the following axis options:" }, { "code": null, "e": 14349, "s": 14282, "text": "table/col sep=comma,xticklabels from table={filename.csv}{colname}" }, { "code": null, "e": 14586, "s": 14349, "text": "First, we need to specify the column separator for our .csv file using the table/col sep option. Then, we can direct PGFPlots to retrieve the x-tick labels from a particular column in the table using the command xticklabels from table ." }, { "code": null, "e": 15229, "s": 14586, "text": "Another styling preference is how to display the logarithmic axis tick labels. Some prefer to display it using scientific notation, while others would like the numbers to be displayed as is. If you wish to display the logarithmic axis tick labels as a fixed number, then you can use the command log ticks with fixed point to display all logarithmic axes with fixed number notations. Since a semi-log plot has only a single logarithmic axis, this is quite straightforward to use. However, if you’re plotting a log-log figure and wish to modify only a single logarithmic axis to fixed number notations, then this post on stackexchange can help!" }, { "code": null, "e": 16119, "s": 15229, "text": "We’re almost done with our styling! Let’s rotate the x-tick labels by 90 degrees using the command that we learnt before. Also, we’ll use xtick option to specify tick positions for our plot. The possible values for the xtick option are \\empty , data , or {<list of coordinates>}. \\empty will produce no tick marks and {<list of coordinates>} will produce tick marks at the provided coordinates. Since we are specifying our x-axis tick labels from .csv file, we will use xtick=data to produce tick marks at every coordinate of our plot. And one final modification before we are done; since we’re using discrete data points for plotting, we will remove the line joining the markers. For this purpose, PGFPlots provides us with the only marks option that can be added to the \\addplot command. Note: in contrast, if you wish to show only lines without markers, you can use the no marks option." }, { "code": null, "e": 16192, "s": 16119, "text": "And that’s it! Our final code for the semi-log plot will look like this:" }, { "code": null, "e": 16650, "s": 16192, "text": "\\begin{tikzpicture}\\begin{semilogyaxis}[ myplotstyle, table/col sep=comma, xticklabels from table={Fig_loglog_lineplot.csv}{month}, xtick=data, x tick label style={rotate=90}, xlabel={Month $(2020)$}, ylabel={No. of confirmed cases}, log ticks with fixed point,]\\addplot+[only marks, mark=o, mark options={scale=1.5}] table[x expr=\\coordindex, y=confirmed, col sep=comma] {Fig_loglog_lineplot.csv};\\end{semilogyaxis}\\end{tikzpicture}" }, { "code": null, "e": 16706, "s": 16650, "text": "Here, we can see how our corresponding plot looks like:" }, { "code": null, "e": 17071, "s": 16706, "text": "Moving on to our next plot now! Let’s take a look at how to plot a secondary y-axis. For ease of plotting, I have modified the tips dataset provided by seaborn (Python plotting library) into two separate .csv files (tip amount during lunch hour and tip amount during dinner hour). Note: you can also use multiple columns within a single .csv file to plot the same." }, { "code": null, "e": 17174, "s": 17071, "text": "We’ll begin by writing down the specifications for the two axes environments that we’re interested in." }, { "code": null, "e": 17780, "s": 17174, "text": "\\begin{tikzpicture}%% axis 1 %%\\begin{axis}[ myplotstyle, scale only axis, axis y line*=left, xlabel={Total bill $(\\$)$}, ylabel={Tips $(\\$)$},]\\addplot+[only marks, mark=*, mark options={scale=1.5, fill=white}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_1.csv};\\end{axis}%% axis 2 %%\\begin{axis}[ myplotstyle, scale only axis, axis y line*=right, axis x line=none, ylabel={Tips $(\\$)$},]\\addplot+[only marks, mark=triangle*, mark options={scale=1.5, fill=white}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_2.csv};\\end{axis}\\end{tikzpicture}" }, { "code": null, "e": 17985, "s": 17780, "text": "Now, we’ll layer the two environments over each other. For this, we will use the \\pgfplotsset{set layers} option right after \\begin{tikzpicture}. Some additional styling options also need to be specified:" }, { "code": null, "e": 18237, "s": 17985, "text": "axis y line*=left/right : specifies which dataset is shown on which y-axis. Note: the * signifies that axes will not have arrow headsaxis x line=none : hides x-axis line for the second plotscale only axis : forces both y-axes dimensions to be the same" }, { "code": null, "e": 18371, "s": 18237, "text": "axis y line*=left/right : specifies which dataset is shown on which y-axis. Note: the * signifies that axes will not have arrow heads" }, { "code": null, "e": 18428, "s": 18371, "text": "axis x line=none : hides x-axis line for the second plot" }, { "code": null, "e": 18491, "s": 18428, "text": "scale only axis : forces both y-axes dimensions to be the same" }, { "code": null, "e": 18530, "s": 18491, "text": "The combined code now looks like this:" }, { "code": null, "e": 19161, "s": 18530, "text": "\\begin{tikzpicture}\\pgfplotsset{set layers}%% axis 1 %%\\begin{axis}[ myplotstyle, scale only axis, axis y line*=left, xlabel={Total bill $(\\$)$}, ylabel={Tips $(\\$)$},]\\addplot+[only marks, mark=*, mark options={scale=1.5, fill=white}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_1.csv};\\end{axis}%% axis 2 %%\\begin{axis}[ myplotstyle, scale only axis, axis y line*=right, axis x line=none, ylabel={Tips $(\\$)$},]\\addplot+[only marks, mark=triangle*, mark options={scale=1.5, fill=white}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_2.csv};\\end{axis}\\end{tikzpicture}" }, { "code": null, "e": 19224, "s": 19161, "text": "The initial plot based on these specifications is shown below:" }, { "code": null, "e": 19656, "s": 19224, "text": "What styling options can we add to make this plot more appealing? Let’s start by making both the y-axes limits to be the same. This can be done adding ymin and ymax for both axes. Let us also change the color of the left ordinate to blue and right to red. We do this by setting the options y axis line style , y tick label style , and ylabel style for both axes. We’ll also match the marker color to their corresponding axis color." }, { "code": null, "e": 19678, "s": 19656, "text": "The code thus far is:" }, { "code": null, "e": 20517, "s": 19678, "text": "\\begin{tikzpicture}\\pgfplotsset{set layers}%% axis 1 %%\\begin{axis}[ myplotstyle, scale only axis, axis y line*=left, ymin=0, ymax=7, y axis line style={blue}, y tick label style={blue}, ylabel style={blue}, xlabel={Total bill $(\\$)$}, ylabel={Tips $(\\$)$},]\\addplot+[only marks, mark=*, mark options={scale=1.5, fill=white}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_1.csv};\\end{axis}%% axis 2%%\\begin{axis}[ myplotstyle, scale only axis, axis y line*=right, ymin=0, ymax=7, axis x line=none, y axis line style={red}, tick label style={red}, ylabel style={red}, ylabel={Tips $(\\$)$},]\\addplot+[only marks, mark=triangle*, color=red, mark options={scale=1.5, fill=white}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_2.csv};\\end{axis}\\end{tikzpicture}" }, { "code": null, "e": 20554, "s": 20517, "text": "This is how our plot looks like now:" }, { "code": null, "e": 20998, "s": 20554, "text": "Since our y-axes labels are the same, it would be prudent to also add a legend to make this plot more informative. We’ll need some tweaking to render a single legend for both axes environments. I used the workaround proposed on stackexchange for this purpose. We’ll add a label to the first plot and use this label to create a legend entry for the first plot inside the second axis environment. The final code put together will look like this:" }, { "code": null, "e": 21995, "s": 20998, "text": "\\begin{tikzpicture}\\pgfplotsset{set layers}\\begin{axis}[ myplotstyle, scale only axis, axis y line*=left, ymin=0, ymax=7, y axis line style={blue}, y tick label style={blue}, ylabel style={blue}, xlabel={Total bill $(\\$)$}, ylabel={Tips $(\\$)$},]\\addplot+[only marks, mark=*, mark options={scale=1.5, fill=white}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_1.csv};\\label{multiplot:plot1}\\end{axis}\\begin{axis}[ myplotstyle, scale only axis, axis y line*=right, ymin=0, ymax=7, axis x line=none, y axis line style={red}, y tick label style={red}, ylabel style={red}, ylabel={Tips $(\\$)$}, legend pos=south east,]\\addlegendimage{/pgfplots/refstyle=multiplot:plot1}\\addlegendentry{Tips during lunch hour}\\addplot+[only marks, mark=triangle*, color=red, mark options={scale=1.5, fill=white}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_2.csv};\\addlegendentry{Tips during dinner hour}\\end{axis}\\end{tikzpicture}" }, { "code": null, "e": 22456, "s": 21995, "text": "As we can see from the code above, another way to add a legend entry is using the \\addlegendentry[<options>]{text} after the \\addplot command. I have used \\addlegendimage{} command with it for referencing the line style of the first plot. We will then add the legend for the plot in this axis environment after its corresponding \\addplot command. Note: I have added the legend of the first plot before the \\addplot command in the second plot to preserve order." }, { "code": null, "e": 22502, "s": 22456, "text": "And there we have it! This is our final plot:" }, { "code": null, "e": 22693, "s": 22502, "text": "The next scenario we’re going to tackle is how to add text within plots. For this, let’s once again use the tips dataset (both lunch and dinner hour datasets combined) to create a mean plot." }, { "code": null, "e": 22776, "s": 22693, "text": "As always, let’s begin by using what we have learnt so far to create a basic plot:" }, { "code": null, "e": 23183, "s": 22776, "text": "\\begin{tikzpicture}\\begin{axis}[ myplotstyle, xlabel={Total bill ($\\$$)}, ylabel={Tips ($\\$$)},]\\addplot+[only marks, mark=square, color=red, mark options={scale=2}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_1.csv};\\addplot+[only marks, mark=square, color=red, mark options={scale=2}] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_2.csv};\\end{axis}\\end{tikzpicture}" }, { "code": null, "e": 23221, "s": 23183, "text": "This is what we’re starting off with:" }, { "code": null, "e": 23801, "s": 23221, "text": "Now, we need to add a mean line and two standard deviation lines (mean + 2σ and mean-2σ; I have calculated the necessary values beforehand). To plot constant values, we can either use the format \\addplot+[]{constant} (in which case, we’ll have to specify the domain in which the line needs to be plotted) or \\addplot+[] coordinates{(x,y)} . Note: I have used both the options for reference. I have also specified the domain for constant value plots. Since adding a domain can cause changes in the axis limits, I have added xmin , xmax, xtick, and ytick . This is our code so far:" }, { "code": null, "e": 24536, "s": 23801, "text": "\\begin{tikzpicture}\\begin{axis}[ myplotstyle, xlabel={Total bill ($\\$$)}, ylabel={Tips ($\\$$)}, xmin=0, xmax=40, xtick={5,10,15,20,25,30,35}, ytick={1,2,3,4,5,6}, domain=5:35,]\\addplot+[smooth, only marks, mark=square, mark options={scale=2,fill=white}, color=red] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_1.csv};\\addplot+[smooth, only marks, mark=square, mark options={scale=2,fill=white}, color=red] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_2.csv};\\addplot+[smooth, no marks, color=black, dashdotted] {2.97};\\addplot+[smooth, no marks, color=black, solid] {0.62};\\addplot+[smooth, no marks, color=black, solid] coordinates {(5, 5.32) (35, 5.32)};\\end{axis}\\end{tikzpicture}" }, { "code": null, "e": 24574, "s": 24536, "text": "And the corresponding plot output is:" }, { "code": null, "e": 24852, "s": 24574, "text": "The plot is incomplete until we add in the descriptions for each of the constant lines. The method I’m going to use here is to add a node at desired locations. I’ll be positioning my text based on rel axis cs (or, relative axis coordinate system; see figure below for details)." }, { "code": null, "e": 24894, "s": 24852, "text": "The format followed for adding a node is:" }, { "code": null, "e": 24941, "s": 24894, "text": "\\node[<options>] at (rel axis cs: x,y) {text};" }, { "code": null, "e": 25010, "s": 24941, "text": "The final code after adding in the text descriptions will look this:" }, { "code": null, "e": 25900, "s": 25010, "text": "\\begin{tikzpicture}\\begin{axis}[ myplotstyle, xlabel={Total bill ($\\$$)}, ylabel={Tips ($\\$$)}, xmin=0, xmax=40, xtick={5,10,15,20,25,30,35}, ytick={1,2,3,4,5,6}, domain=5:35,]\\addplot+[smooth, only marks, mark=square, mark options={scale=2,fill=white}, color=red] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_1.csv};\\addplot+[smooth, only marks, mark=square, mark options={scale=2,fill=white}, color=red] table[x=total_bill,y=tip, col sep=comma] {Fig_multiaxisplot_2.csv};\\addplot+[smooth, no marks, color=black, dashdotted] {2.97};\\node [] at (rel axis cs: 0.2,0.51) {Mean};\\addplot+[smooth, no marks, color=black, solid] coordinates {(5, 5.32) (35, 5.32)};\\node [] at (rel axis cs: 0.24,0.87) {Mean + $2\\sigma$};\\addplot+[smooth, no marks, color=black, solid] {0.62};\\node [] at (rel axis cs: 0.23,0.13) {Mean - $2\\sigma$};\\end{axis}\\end{tikzpicture}" }, { "code": null, "e": 25943, "s": 25900, "text": "And we have our final plot as shown below:" }, { "code": null, "e": 26208, "s": 25943, "text": "Now, the last plot I’ll be tackling in this article is a plot overlaid on an image. I’ll be using the image shown below for this purpose. Note: I’ll be removing the axes and tick labels provided in the chart below and instead adding in my own axes and tick labels." }, { "code": null, "e": 26278, "s": 26208, "text": "I’ll be using a fictitious weights dataset for this plot (see below)." }, { "code": null, "e": 26393, "s": 26278, "text": "Let’s first create a simple plot based on our dataset. The code so far with the corresponding plot is given below:" }, { "code": null, "e": 26877, "s": 26393, "text": "\\begin{tikzpicture}\\begin{axis}[ myplotstyle, legend pos=south east, legend entries={{\\large Child 1}, {\\large Child 2}}, xlabel={Age (in years)}, ylabel={Weight (in $kg$)},]\\addplot+[only marks, mark options={scale=1.5}, mark=triangle,color=blue] table[x=age,y=weight1, col sep=comma] {Fig_overlaidplot.csv};\\addplot+[only marks, mark options={scale=1.5}, mark=square,color=red] table[x=age,y=weight2, col sep=comma] {Fig_overlaidplot.csv};\\end{axis}\\end{tikzpicture}" }, { "code": null, "e": 26983, "s": 26877, "text": "We’ll modify few things to have matching dimensions and axes tick labels for both our plot and the image:" }, { "code": null, "e": 27302, "s": 26983, "text": "We’ll add width and height options to change dimension of our plotWe’ll use xmin, xmax , ymin , and ymax options to align our axis limits with the imageFinally, we’ll add xtick and ytick options to match our plot axes tick labels with those of the image (I have specified the weight for y-axis only in the metric unit)" }, { "code": null, "e": 27369, "s": 27302, "text": "We’ll add width and height options to change dimension of our plot" }, { "code": null, "e": 27456, "s": 27369, "text": "We’ll use xmin, xmax , ymin , and ymax options to align our axis limits with the image" }, { "code": null, "e": 27623, "s": 27456, "text": "Finally, we’ll add xtick and ytick options to match our plot axes tick labels with those of the image (I have specified the weight for y-axis only in the metric unit)" }, { "code": null, "e": 27666, "s": 27623, "text": "Our code put together will look like this:" }, { "code": null, "e": 28350, "s": 27666, "text": "\\begin{tikzpicture}\\begin{axis}[ myplotstyle, legend pos=south east, legend entries={{\\large Child 1}, {\\large Child 2}}, xlabel={Age (in years)}, ylabel={Weight (in $kg$)}, ymin=5, ymax=105, ytick={10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100}, xmin=2, xmax=21, xtick={2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}, width=13cm, height=15cm,]\\addplot+[only marks, mark options={scale=1.5}, mark=triangle,color=blue] table[x=age,y=weight1, col sep=comma] {Fig_overlaidplot.csv};\\addplot+[only marks, mark options={scale=1.5}, mark=square,color=red] table[x=age,y=weight2, col sep=comma] {Fig_overlaidplot.csv};\\end{axis}\\end{tikzpicture}" }, { "code": null, "e": 28395, "s": 28350, "text": "And the corresponding plot for this will be:" }, { "code": null, "e": 28447, "s": 28395, "text": "Now, the command to add in graphics to the plot is:" }, { "code": null, "e": 28490, "s": 28447, "text": "\\addplot graphics[<options>] {figure.png};" }, { "code": null, "e": 28817, "s": 28490, "text": "The central idea behind this plot is to fit the graphics within our plot axes coordinates. Therefore, we’ll have to add the \\addplot graphics command with options xmin , xmax , ymin , and ymax matching those of the main plot. I have also added the axis on top option to have the axis lines and ticks positioned over the image." }, { "code": null, "e": 28869, "s": 28817, "text": "And it’s as simple as that! The final code will be:" }, { "code": null, "e": 29641, "s": 28869, "text": "\\begin{tikzpicture}\\begin{axis}[ myplotstyle, legend pos=south east, legend entries={{\\large Child 1}, {\\large Child 2}}, xlabel={Age (in years)}, ylabel={Weight (in $kg$)}, ymin=5, ymax=105, ytick={10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100}, xmin=2, xmax=21, xtick={2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}, axis on top, width=13cm, height=15cm,]\\addplot+[only marks, mark options={scale=1.5}, mark=triangle,color=blue] table[x=age,y=weight1, col sep=comma] {Fig_overlaidplot.csv};\\addplot+[only marks, mark options={scale=1.5}, mark=square,color=red] table[x=age,y=weight2, col sep=comma] {Fig_overlaidplot.csv};\\addplot graphics[ymin=5, ymax=105, xmin=2, xmax=21] {Fig_comparisons.png};\\end{axis}\\end{tikzpicture}" }, { "code": null, "e": 29684, "s": 29641, "text": "And our overlaid plot will look like this:" }, { "code": null, "e": 29723, "s": 29684, "text": "And that’s a wrap... for this article!" } ]
Convert from any base to decimal and vice versa in C++
In this tutorial, we will be discussing a program to convert from any base to a decimal and vice versa. For this we will be provided with an integer and its base. Our task is to convert the number to its decimal equivalent. Further we will also be performing the reverse of this procedure as well. Live Demo #include <stdio.h> #include <string.h> //returning values of a character int val(char c) { if (c >= '0' && c <= '9') return (int)c - '0'; else return (int)c - 'A' + 10; } //converting number to decimal equivalent int convert_decimal(char *str, int base) { int len = strlen(str); int power = 1; int num = 0; int i; for (i = len - 1; i >= 0; i--) { if (val(str[i]) >= base) { printf("Invalid Number"); return -1; } num += val(str[i]) * power; power = power * base; } return num; } int main() { char str[] = "11A"; int base = 16; printf("Decimal equivalent of %s in base %d is " " %d\n", str, base, convert_decimal(str, base)); return 0; } Decimal equivalent of 11A in base 16 is 282 Now performing the reverse of the operation. Live Demo #include <stdio.h> #include <string.h> //returning values of a character char reVal(int num) { if (num <= 0 && num >= 9) return (char)(num + '0'); else return (char)(num - 10 + 'A'); } //reversing a given string void reverse_string(char *str) { int len = strlen(str); int i; for (i = 0; i < len/2; i++) { char temp = str[i]; str[i] = str[len-i-1]; str[len-i-1] = temp; } } //converting to equivalent number with base 'b' char* convert_base(char res[], int base, int inputNum) { int index = 0; while (inputNum > 0) { res[index++] = reVal(inputNum % base); inputNum /= base; } res[index] = '\0'; //reversing the result reverse_string(res); return res; } int main() { int inputNum = 282, base = 16; char res[100]; printf("Equivalent of %d in base %d is "" %s\n", inputNum, base, convert_base(res, base, inputNum)); return 0; } Equivalent of 282 in base 16 is 11A
[ { "code": null, "e": 1166, "s": 1062, "text": "In this tutorial, we will be discussing a program to convert from any base to a decimal and vice versa." }, { "code": null, "e": 1360, "s": 1166, "text": "For this we will be provided with an integer and its base. Our task is to convert the number to its decimal equivalent. Further we will also be performing the reverse of this procedure as well." }, { "code": null, "e": 1371, "s": 1360, "text": " Live Demo" }, { "code": null, "e": 2101, "s": 1371, "text": "#include <stdio.h>\n#include <string.h>\n//returning values of a character\nint val(char c) {\n if (c >= '0' && c <= '9')\n return (int)c - '0';\n else\n return (int)c - 'A' + 10;\n}\n//converting number to decimal equivalent\nint convert_decimal(char *str, int base) {\n int len = strlen(str);\n int power = 1;\n int num = 0;\n int i;\n for (i = len - 1; i >= 0; i--) {\n if (val(str[i]) >= base) {\n printf(\"Invalid Number\");\n return -1;\n }\n num += val(str[i]) * power;\n power = power * base;\n }\n return num;\n}\nint main() {\n char str[] = \"11A\";\n int base = 16;\n printf(\"Decimal equivalent of %s in base %d is \" \" %d\\n\", str, base, convert_decimal(str, base));\n return 0;\n}" }, { "code": null, "e": 2145, "s": 2101, "text": "Decimal equivalent of 11A in base 16 is 282" }, { "code": null, "e": 2190, "s": 2145, "text": "Now performing the reverse of the operation." }, { "code": null, "e": 2201, "s": 2190, "text": " Live Demo" }, { "code": null, "e": 3118, "s": 2201, "text": "#include <stdio.h>\n#include <string.h>\n//returning values of a character\nchar reVal(int num) {\n if (num <= 0 && num >= 9)\n return (char)(num + '0');\n else\n return (char)(num - 10 + 'A');\n}\n//reversing a given string\nvoid reverse_string(char *str) {\n int len = strlen(str);\n int i;\n for (i = 0; i < len/2; i++) {\n char temp = str[i];\n str[i] = str[len-i-1];\n str[len-i-1] = temp;\n }\n}\n//converting to equivalent number with base 'b'\nchar* convert_base(char res[], int base, int inputNum) {\n int index = 0;\n while (inputNum > 0) {\n res[index++] = reVal(inputNum % base);\n inputNum /= base;\n }\n res[index] = '\\0';\n //reversing the result\n reverse_string(res);\n return res;\n}\nint main() {\n int inputNum = 282, base = 16;\n char res[100];\n printf(\"Equivalent of %d in base %d is \"\" %s\\n\", inputNum, base, convert_base(res, base, inputNum));\n return 0;\n}" }, { "code": null, "e": 3154, "s": 3118, "text": "Equivalent of 282 in base 16 is 11A" } ]
How to dynamically set the height and width of a div element using jQuery ? - GeeksforGeeks
03 Aug, 2021 Set the height of a div element using jQuery The content height of a div can dynamically set or change using height(), innerHeight(), and outerHeight() methods depending upon the user requirement. If the user wants to change the content height of a div dynamically, it includes changing the actual height, actual height with padding, and actual height with padding and border, then the user can use any of the following methods that will dynamically set the height of the content of an element. Using height() method Using innerHeight() method Using outerHeight() method Example 1: Content Height of div using height() method will change the height of the content of an element excluding the padding, border, and margin of the element. HTML <!DOCTYPE html> <html> <head> <title> How to dynamically set the height of a div element using jQuery? </title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"> </script> <style> #div1 { height: 50px; width: 300px; border: 2px solid black; } h1 { color: green; } .box{ background: green; border: 1px solid #ccc; color: white; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Dynamically set the height of a div element using jQuery</h3> <div id="div1" class="box"> Dynamically set content height of a div on GeeksforGeek.<br> GeeksforGeeks is a computer science portal which helps students to learn various programming language and master data structures and algorithms. There are various courses available to learn new skills. </div> <br> <form> <input type="text" class="geeks1"> <button type="button" class="geeks2"> Set Height </button> </form> <p id="p1"></p> <p id="p2"></p> </center> <script> $(document).ready(function(){ $(".geeks2").click(function(){ var demo ="Previous-height: "+ $("#div1").height(); + "px"; $("#p1").text(demo); var newHeight = $(".geeks1").val(); $(".box").height(newHeight); demo = "New-height: "+ $("#div1").height(); + "px"; $("#p2").text(demo); }); }); </script> </body> </html> Output: Example 2: Content Height of div using innerHeight() method will change the height of the content of an element including the padding of the element. HTML <!DOCTYPE html> <html> <head> <title> How to dynamically set the height of a div element using jQuery? </title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"> </script> <style> #div1 { height: 50px; width: 300px; border: 2px solid black; padding : 10px; } h1 { color: green; } .box{ background: green; border: 1px solid #ccc; color: white; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Dynamically set the height of a div element using jQuery</h3> <div id="div1" class="box"> Dynamically set content height of a div on GeeksforGeek.<br> GeeksforGeeks is a computer science portal which helps students to learn various programming language and master data structures and algorithms. There are various courses available to learn new skills. </div> <br> <form> <input type="text" class="geeks1"> <button type="button" class="geeks2"> Set Height </button> </form> <p id="p1"></p> <p id="p2"></p> </center> <script> $(document).ready(function(){ $(".geeks2").click(function(){ var demo ="Previous-height(+Padding) : " + $("#div1").innerHeight(); + "px"; $("#p1").text(demo); var newHeight = $(".geeks1").val(); $(".box").innerHeight(newHeight); demo = "New-height(+Padding) : "+ $("#div1").innerHeight(); + "px"; $("#p2").text(demo); }); }); </script> </body> </html> Output: Example 3: Content Height of div using outerHeight() method will change the height of the content of an element including the padding and border of the element. HTML <!DOCTYPE html> <html> <head> <title> How to dynamically set the height of a div element using jQuery? </title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"> </script> <style> #div1 { height: 50px; width: 300px; border: 2px solid black; padding : 10px; } h1 { color: green; } .box{ background: green; border: 1px solid #ccc; color: white; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Dynamically set the height of a div element using jQuery</h3> <div id="div1" class="box"> Dynamically set content height of a div on GeeksforGeek.<br> GeeksforGeeks is a computer science portal which helps students to learn various programming language and master data structures and algorithms. There are various courses available to learn new skills. </div> <br> <form> <input type="text" class="geeks1"> <button type="button" class="geeks2"> Set Height </button> </form> <p id="p1"></p> <p id="p2"></p> </center> <script> $(document).ready(function(){ $(".geeks2").click(function(){ var demo ="Previous-height(border+Padding) : " + $("#div1").outerHeight(); + "px"; $("#p1").text(demo); var newHeight = $(".geeks1").val(); $(".box").outerHeight(newHeight); demo = "New-height(border+Padding) : " + $("#div1").outerHeight(); + "px"; $("#p2").text(demo); }); }); </script> </body> </html> Output: Set the width of a div element using jQuery The content width of a div can dynamically set or change using width(), innerWidth(), and outerWidth() methods depending upon the user requirement. If the user wants to change the content width of a div dynamically, it includes changing the actual width, actual width with padding, and actual width with padding and border, then the user can use any of the following methods that will dynamically set the width of the content of an element. Using width() method Using innerWidth() method Using outerWidth() method Example 1: Content Width of div using width() method will change the width of the content of an element excluding the padding, border, and margin of the element. HTML <!DOCTYPE html> <html> <head> <title> How to dynamically set the width of a div element using jQuery? </title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"> </script> <style> #div1 { height: 100px; width: 200px; border: 2px solid black; padding : 10px; } h1 { color: green; } .box{ background: green; border: 1px solid #ccc; color: white; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Dynamically set the width of a div element using jQuery</h3> <div id="div1" class="box"> Dynamically set content width of a div on GeeksforGeek.<br> GeeksforGeeks is a computer science portal which helps students to learn various programming language and master data structures and algorithms. There are various courses available to learn new skills. </div> <br> <form> <input type="text" class="geeks1"> <button type="button" class="geeks2"> Set Width </button> </form> <p id="p1"></p> <p id="p2"></p> </center> <script> $(document).ready(function(){ $(".geeks2").click(function(){ var demo ="Previous-width : "+ $("#div1").width(); + "px"; $("#p1").text(demo); var newWidth = $(".geeks1").val(); $(".box").width(newWidth); demo = "New-width : "+ $("#div1").width(); + "px"; $("#p2").text(demo); }); }); </script> </body> </html> Output: Example 2: Content Width of div using innerWidth() method will change the width of the content of an element including the padding of the element. HTML <!DOCTYPE html> <html> <head> <title> How to dynamically set the width of a div element using jQuery? </title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"> </script> <style> #div1 { height: 100px; width: 200px; border: 2px solid black; padding : 10px; } h1 { color: green; } .box{ background: green; border: 1px solid #ccc; color: white; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Dynamically set the width of a div element using jQuery</h3> <div id="div1" class="box"> Dynamically set content width of a div on GeeksforGeek.<br> GeeksforGeeks is a computer science portal which helps students to learn various programming language and master data structures and algorithms. There are various courses available to learn new skills. </div> <br> <form> <input type="text" class="geeks1"> <button type="button" class="geeks2"> Set Width </button> </form> <p id="p1"></p> <p id="p2"></p> </center> <script> $(document).ready(function(){ $(".geeks2").click(function(){ var demo ="Previous-width(+Padding) : "+ $("#div1").innerWidth(); + "px"; $("#p1").text(demo); var newWidth = $(".geeks1").val(); $(".box").innerWidth(newWidth); demo = "New-width(+Padding) : "+ $("#div1").innerWidth(); + "px"; $("#p2").text(demo); }); }); </script> </body> </html> Output: Example 3: Content Width of div using outerWidth() method will change the width of the content of an element including the padding and border of the element. HTML <!DOCTYPE html> <html> <head> <title> How to dynamically set the width of a div element using jQuery? </title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"> </script> <style> #div1 { height: 100px; width: 200px; border: 2px solid black; padding : 10px; } h1 { color: green; } .box{ background: green; border: 1px solid #ccc; color: white; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Dynamically set the width of a div element using jQuery</h3> <div id="div1" class="box"> Dynamically set content width of a div on GeeksforGeek.<br> GeeksforGeeks is a computer science portal which helps students to learn various programming language and master data structures and algorithms. There are various courses available to learn new skills. </div> <br> <form> <input type="text" class="geeks1"> <button type="button" class="geeks2"> Set Width </button> </form> <p id="p1"></p> <p id="p2"></p> </center> <script> $(document).ready(function(){ $(".geeks2").click(function(){ var demo ="Previous-width(border+Padding) : "+ $("#div1").outerWidth(); + "px"; $("#p1").text(demo); var newWidth = $(".geeks1").val(); $(".box").outerWidth(newWidth); demo = "New-width(border+Padding) : "+ $("#div1").outerWidth(); + "px"; $("#p2").text(demo); }); }); </script> </body> </html> Output: jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples. jQuery-Misc CSS HTML JavaScript JQuery Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of CSS (Cascading Style Sheet) Create a Responsive Navbar using ReactJS Design a web page using HTML and CSS How to Upload Image into Database and Display it using PHP ? CSS | :not(:last-child):after Selector How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 25539, "s": 25511, "text": "\n03 Aug, 2021" }, { "code": null, "e": 25584, "s": 25539, "text": "Set the height of a div element using jQuery" }, { "code": null, "e": 26034, "s": 25584, "text": "The content height of a div can dynamically set or change using height(), innerHeight(), and outerHeight() methods depending upon the user requirement. If the user wants to change the content height of a div dynamically, it includes changing the actual height, actual height with padding, and actual height with padding and border, then the user can use any of the following methods that will dynamically set the height of the content of an element." }, { "code": null, "e": 26056, "s": 26034, "text": "Using height() method" }, { "code": null, "e": 26083, "s": 26056, "text": "Using innerHeight() method" }, { "code": null, "e": 26110, "s": 26083, "text": "Using outerHeight() method" }, { "code": null, "e": 26275, "s": 26110, "text": "Example 1: Content Height of div using height() method will change the height of the content of an element excluding the padding, border, and margin of the element." }, { "code": null, "e": 26280, "s": 26275, "text": "HTML" }, { "code": "<!DOCTYPE html> <html> <head> <title> How to dynamically set the height of a div element using jQuery? </title> <script src=\"https://code.jquery.com/jquery-1.12.4.min.js\"> </script> <style> #div1 { height: 50px; width: 300px; border: 2px solid black; } h1 { color: green; } .box{ background: green; border: 1px solid #ccc; color: white; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Dynamically set the height of a div element using jQuery</h3> <div id=\"div1\" class=\"box\"> Dynamically set content height of a div on GeeksforGeek.<br> GeeksforGeeks is a computer science portal which helps students to learn various programming language and master data structures and algorithms. There are various courses available to learn new skills. </div> <br> <form> <input type=\"text\" class=\"geeks1\"> <button type=\"button\" class=\"geeks2\"> Set Height </button> </form> <p id=\"p1\"></p> <p id=\"p2\"></p> </center> <script> $(document).ready(function(){ $(\".geeks2\").click(function(){ var demo =\"Previous-height: \"+ $(\"#div1\").height(); + \"px\"; $(\"#p1\").text(demo); var newHeight = $(\".geeks1\").val(); $(\".box\").height(newHeight); demo = \"New-height: \"+ $(\"#div1\").height(); + \"px\"; $(\"#p2\").text(demo); }); }); </script> </body> </html>", "e": 28248, "s": 26280, "text": null }, { "code": null, "e": 28256, "s": 28248, "text": "Output:" }, { "code": null, "e": 28406, "s": 28256, "text": "Example 2: Content Height of div using innerHeight() method will change the height of the content of an element including the padding of the element." }, { "code": null, "e": 28411, "s": 28406, "text": "HTML" }, { "code": "<!DOCTYPE html> <html> <head> <title> How to dynamically set the height of a div element using jQuery? </title> <script src=\"https://code.jquery.com/jquery-1.12.4.min.js\"> </script> <style> #div1 { height: 50px; width: 300px; border: 2px solid black; padding : 10px; } h1 { color: green; } .box{ background: green; border: 1px solid #ccc; color: white; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Dynamically set the height of a div element using jQuery</h3> <div id=\"div1\" class=\"box\"> Dynamically set content height of a div on GeeksforGeek.<br> GeeksforGeeks is a computer science portal which helps students to learn various programming language and master data structures and algorithms. There are various courses available to learn new skills. </div> <br> <form> <input type=\"text\" class=\"geeks1\"> <button type=\"button\" class=\"geeks2\"> Set Height </button> </form> <p id=\"p1\"></p> <p id=\"p2\"></p> </center> <script> $(document).ready(function(){ $(\".geeks2\").click(function(){ var demo =\"Previous-height(+Padding) : \" + $(\"#div1\").innerHeight(); + \"px\"; $(\"#p1\").text(demo); var newHeight = $(\".geeks1\").val(); $(\".box\").innerHeight(newHeight); demo = \"New-height(+Padding) : \"+ $(\"#div1\").innerHeight(); + \"px\"; $(\"#p2\").text(demo); }); }); </script> </body> </html>", "e": 30443, "s": 28411, "text": null }, { "code": null, "e": 30451, "s": 30443, "text": "Output:" }, { "code": null, "e": 30612, "s": 30451, "text": "Example 3: Content Height of div using outerHeight() method will change the height of the content of an element including the padding and border of the element." }, { "code": null, "e": 30617, "s": 30612, "text": "HTML" }, { "code": "<!DOCTYPE html> <html> <head> <title> How to dynamically set the height of a div element using jQuery? </title> <script src=\"https://code.jquery.com/jquery-1.12.4.min.js\"> </script> <style> #div1 { height: 50px; width: 300px; border: 2px solid black; padding : 10px; } h1 { color: green; } .box{ background: green; border: 1px solid #ccc; color: white; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Dynamically set the height of a div element using jQuery</h3> <div id=\"div1\" class=\"box\"> Dynamically set content height of a div on GeeksforGeek.<br> GeeksforGeeks is a computer science portal which helps students to learn various programming language and master data structures and algorithms. There are various courses available to learn new skills. </div> <br> <form> <input type=\"text\" class=\"geeks1\"> <button type=\"button\" class=\"geeks2\"> Set Height </button> </form> <p id=\"p1\"></p> <p id=\"p2\"></p> </center> <script> $(document).ready(function(){ $(\".geeks2\").click(function(){ var demo =\"Previous-height(border+Padding) : \" + $(\"#div1\").outerHeight(); + \"px\"; $(\"#p1\").text(demo); var newHeight = $(\".geeks1\").val(); $(\".box\").outerHeight(newHeight); demo = \"New-height(border+Padding) : \" + $(\"#div1\").outerHeight(); + \"px\"; $(\"#p2\").text(demo); }); }); </script> </body> </html>", "e": 32664, "s": 30617, "text": null }, { "code": null, "e": 32672, "s": 32664, "text": "Output:" }, { "code": null, "e": 32716, "s": 32672, "text": "Set the width of a div element using jQuery" }, { "code": null, "e": 33157, "s": 32716, "text": "The content width of a div can dynamically set or change using width(), innerWidth(), and outerWidth() methods depending upon the user requirement. If the user wants to change the content width of a div dynamically, it includes changing the actual width, actual width with padding, and actual width with padding and border, then the user can use any of the following methods that will dynamically set the width of the content of an element." }, { "code": null, "e": 33178, "s": 33157, "text": "Using width() method" }, { "code": null, "e": 33204, "s": 33178, "text": "Using innerWidth() method" }, { "code": null, "e": 33230, "s": 33204, "text": "Using outerWidth() method" }, { "code": null, "e": 33392, "s": 33230, "text": "Example 1: Content Width of div using width() method will change the width of the content of an element excluding the padding, border, and margin of the element." }, { "code": null, "e": 33397, "s": 33392, "text": "HTML" }, { "code": "<!DOCTYPE html> <html> <head> <title> How to dynamically set the width of a div element using jQuery? </title> <script src=\"https://code.jquery.com/jquery-1.12.4.min.js\"> </script> <style> #div1 { height: 100px; width: 200px; border: 2px solid black; padding : 10px; } h1 { color: green; } .box{ background: green; border: 1px solid #ccc; color: white; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Dynamically set the width of a div element using jQuery</h3> <div id=\"div1\" class=\"box\"> Dynamically set content width of a div on GeeksforGeek.<br> GeeksforGeeks is a computer science portal which helps students to learn various programming language and master data structures and algorithms. There are various courses available to learn new skills. </div> <br> <form> <input type=\"text\" class=\"geeks1\"> <button type=\"button\" class=\"geeks2\"> Set Width </button> </form> <p id=\"p1\"></p> <p id=\"p2\"></p> </center> <script> $(document).ready(function(){ $(\".geeks2\").click(function(){ var demo =\"Previous-width : \"+ $(\"#div1\").width(); + \"px\"; $(\"#p1\").text(demo); var newWidth = $(\".geeks1\").val(); $(\".box\").width(newWidth); demo = \"New-width : \"+ $(\"#div1\").width(); + \"px\"; $(\"#p2\").text(demo); }); }); </script> </body> </html>", "e": 35386, "s": 33397, "text": null }, { "code": null, "e": 35394, "s": 35386, "text": "Output:" }, { "code": null, "e": 35541, "s": 35394, "text": "Example 2: Content Width of div using innerWidth() method will change the width of the content of an element including the padding of the element." }, { "code": null, "e": 35546, "s": 35541, "text": "HTML" }, { "code": "<!DOCTYPE html> <html> <head> <title> How to dynamically set the width of a div element using jQuery? </title> <script src=\"https://code.jquery.com/jquery-1.12.4.min.js\"> </script> <style> #div1 { height: 100px; width: 200px; border: 2px solid black; padding : 10px; } h1 { color: green; } .box{ background: green; border: 1px solid #ccc; color: white; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Dynamically set the width of a div element using jQuery</h3> <div id=\"div1\" class=\"box\"> Dynamically set content width of a div on GeeksforGeek.<br> GeeksforGeeks is a computer science portal which helps students to learn various programming language and master data structures and algorithms. There are various courses available to learn new skills. </div> <br> <form> <input type=\"text\" class=\"geeks1\"> <button type=\"button\" class=\"geeks2\"> Set Width </button> </form> <p id=\"p1\"></p> <p id=\"p2\"></p> </center> <script> $(document).ready(function(){ $(\".geeks2\").click(function(){ var demo =\"Previous-width(+Padding) : \"+ $(\"#div1\").innerWidth(); + \"px\"; $(\"#p1\").text(demo); var newWidth = $(\".geeks1\").val(); $(\".box\").innerWidth(newWidth); demo = \"New-width(+Padding) : \"+ $(\"#div1\").innerWidth(); + \"px\"; $(\"#p2\").text(demo); }); }); </script> </body> </html>", "e": 37570, "s": 35546, "text": null }, { "code": null, "e": 37578, "s": 37570, "text": "Output:" }, { "code": null, "e": 37736, "s": 37578, "text": "Example 3: Content Width of div using outerWidth() method will change the width of the content of an element including the padding and border of the element." }, { "code": null, "e": 37741, "s": 37736, "text": "HTML" }, { "code": "<!DOCTYPE html> <html> <head> <title> How to dynamically set the width of a div element using jQuery? </title> <script src=\"https://code.jquery.com/jquery-1.12.4.min.js\"> </script> <style> #div1 { height: 100px; width: 200px; border: 2px solid black; padding : 10px; } h1 { color: green; } .box{ background: green; border: 1px solid #ccc; color: white; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Dynamically set the width of a div element using jQuery</h3> <div id=\"div1\" class=\"box\"> Dynamically set content width of a div on GeeksforGeek.<br> GeeksforGeeks is a computer science portal which helps students to learn various programming language and master data structures and algorithms. There are various courses available to learn new skills. </div> <br> <form> <input type=\"text\" class=\"geeks1\"> <button type=\"button\" class=\"geeks2\"> Set Width </button> </form> <p id=\"p1\"></p> <p id=\"p2\"></p> </center> <script> $(document).ready(function(){ $(\".geeks2\").click(function(){ var demo =\"Previous-width(border+Padding) : \"+ $(\"#div1\").outerWidth(); + \"px\"; $(\"#p1\").text(demo); var newWidth = $(\".geeks1\").val(); $(\".box\").outerWidth(newWidth); demo = \"New-width(border+Padding) : \"+ $(\"#div1\").outerWidth(); + \"px\"; $(\"#p2\").text(demo); }); }); </script> </body> </html>", "e": 39777, "s": 37741, "text": null }, { "code": null, "e": 39785, "s": 39777, "text": "Output:" }, { "code": null, "e": 40053, "s": 39785, "text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples." }, { "code": null, "e": 40065, "s": 40053, "text": "jQuery-Misc" }, { "code": null, "e": 40069, "s": 40065, "text": "CSS" }, { "code": null, "e": 40074, "s": 40069, "text": "HTML" }, { "code": null, "e": 40085, "s": 40074, "text": "JavaScript" }, { "code": null, "e": 40092, "s": 40085, "text": "JQuery" }, { "code": null, "e": 40109, "s": 40092, "text": "Web Technologies" }, { "code": null, "e": 40136, "s": 40109, "text": "Web technologies Questions" }, { "code": null, "e": 40141, "s": 40136, "text": "HTML" }, { "code": null, "e": 40239, "s": 40141, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40276, "s": 40239, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 40317, "s": 40276, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 40354, "s": 40317, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 40415, "s": 40354, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 40454, "s": 40415, "text": "CSS | :not(:last-child):after Selector" }, { "code": null, "e": 40514, "s": 40454, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 40575, "s": 40514, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 40628, "s": 40575, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 40678, "s": 40628, "text": "How to Insert Form Data into Database using PHP ?" } ]
SQL Tryit Editor v1.6
SELECT * FROM Customers ORDER BY CustomerName; ​ Edit the SQL Statement, and click "Run SQL" to see the result. This SQL-Statement is not supported in the WebSQL Database. The example still works, because it uses a modified version of SQL. Your browser does not support WebSQL. Your are now using a light-version of the Try-SQL Editor, with a read-only Database. If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time. Our Try-SQL Editor uses WebSQL to demonstrate SQL. A Database-object is created in your browser, for testing purposes. You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button. WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, Opera, and Edge(79). If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
[ { "code": null, "e": 24, "s": 0, "text": "SELECT * FROM Customers" }, { "code": null, "e": 47, "s": 24, "text": "ORDER BY CustomerName;" }, { "code": null, "e": 49, "s": 47, "text": "​" }, { "code": null, "e": 112, "s": 49, "text": "Edit the SQL Statement, and click \"Run SQL\" to see the result." }, { "code": null, "e": 172, "s": 112, "text": "This SQL-Statement is not supported in the WebSQL Database." }, { "code": null, "e": 240, "s": 172, "text": "The example still works, because it uses a modified version of SQL." }, { "code": null, "e": 278, "s": 240, "text": "Your browser does not support WebSQL." }, { "code": null, "e": 363, "s": 278, "text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database." }, { "code": null, "e": 537, "s": 363, "text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time." }, { "code": null, "e": 588, "s": 537, "text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL." }, { "code": null, "e": 656, "s": 588, "text": "A Database-object is created in your browser, for testing purposes." }, { "code": null, "e": 827, "s": 656, "text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button." }, { "code": null, "e": 927, "s": 827, "text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object." }, { "code": null, "e": 987, "s": 927, "text": "WebSQL is supported in Chrome, Safari, Opera, and Edge(79)." } ]
Rust - Quick Guide
Rust is a systems level programming language, developed by Graydon Hoare. Mozilla Labs later acquired the programme. Application programming languages like Java/C# are used to build software, which provide services to the user directly. They help us build business applications like spreadsheets, word processors, web applications or mobile applications. Systems programming languages like C/C++ are used to build software and software platforms. They can be used to build operating systems, game engines, compilers, etc. These programming languages require a great degree of hardware interaction. Systems and application programming languages face two major problems − It is difficult to write secure code. It is difficult to write multi-threaded code. Rust focuses on three goals − Safety Speed Concurrency The language was designed for developing highly reliable and fast software in a simple way. Rust can be used to write high-level programs down to hardware-specific programs. Rust programming language does not have a Garbage Collector (GC) by design. This improves the performance at runtime. Software built using Rust is safe from memory issues like dangling pointers, buffer overruns and memory leaks. Rust’s ownership and memory safety rules provide concurrency without data races. Web Assembly helps to execute high computation intensive algorithms in the browser, on embedded devices, or anywhere else. It runs at the speed of native code. Rust can be compiled to Web Assembly for fast, reliable execution. Installation of Rust is made easy through rustup, a console-based tool for managing Rust versions and associated tools. Let us learn how to install RUST on Windows. Installation of Visual Studio 2013 or higher with C++ tools is mandatory to run the Rust program on windows. First, download Visual Studio from here VS 2013 Express Installation of Visual Studio 2013 or higher with C++ tools is mandatory to run the Rust program on windows. First, download Visual Studio from here VS 2013 Express Download and install rustup tool for windows. rustup-init.exe is available for download here − Rust Lang Download and install rustup tool for windows. rustup-init.exe is available for download here − Rust Lang Double-click rustup-init.exe file. Upon clicking, the following screen will appear. Double-click rustup-init.exe file. Upon clicking, the following screen will appear. Press enter for default installation. Once installation is completed, the following screen appears. Press enter for default installation. Once installation is completed, the following screen appears. From the installation screen, it is clear that Rust related files are stored in the folder − C:\Users\{PC}\.cargo\bin From the installation screen, it is clear that Rust related files are stored in the folder − C:\Users\{PC}\.cargo\bin The contents of the folder are − cargo-fmt.exe cargo.exe rls.exe rust-gdb.exe rust-lldb.exe rustc.exe // this is the compiler for rust rustdoc.exe rustfmt.exe rustup.exe Cargo is the package manager for Rust. To verify if cargo is installed, execute the following command − Cargo is the package manager for Rust. To verify if cargo is installed, execute the following command − C:\Users\Admin>cargo -V cargo 1.29.0 (524a578d7 2018-08-05) The compiler for Rust is rustc. To verify the compiler version, execute the following command − The compiler for Rust is rustc. To verify the compiler version, execute the following command − C:\Users\Admin>cargo -V cargo 1.29.0 (524a578d7 2018-08-05) To install rustup on Linux or macOS, open a terminal and enter the following command. $ curl https://sh.rustup.rs -sSf | sh The command downloads a script and starts the installation of the rustup tool, which installs the latest stable version of Rust. You might be prompted for your password. If the installation is successful, the following line will appear − Rust is installed now. Great! The installation script automatically adds Rust to your system PATH after your next login. To start using Rust right away instead of restarting your terminal, run the following command in your shell to add Rust to your system PATH manually − $ source $HOME/.cargo/env Alternatively, you can add the following line to your ~/.bash_profile − $ export PATH="$HOME/.cargo/bin:$PATH" NOTE − When you try to compile a Rust program and get errors indicating that a linker could not execute, that means a linker is not installed on your system and you will need to install one manually. A Read-Evaluate-Print Loop (REPL) is an easy to use interactive shell to compile and execute computer programs. If you want to compile and execute Rust programs online within the browser, use Tutorialspoint Coding Ground. This chapter explains the basic syntax of Rust language through a HelloWorld example. Create a HelloWorld-App folder and navigate to that folder on terminal Create a HelloWorld-App folder and navigate to that folder on terminal C:\Users\Admin>mkdir HelloWorld-App C:\Users\Admin>cd HelloWorld-App C:\Users\Admin\HelloWorld-App> To create a Rust file, execute the following command − To create a Rust file, execute the following command − C:\Users\Admin\HelloWorld-App>notepad Hello.rs Rust program files have an extension .rs. The above command creates an empty file Hello.rs and opens it in NOTEpad. Add the code given below to this file − fn main(){ println!("Rust says Hello to TutorialsPoint !!"); } The above program defines a function main fn main(). The fn keyword is used to define a function. The main() is a predefined function that acts as an entry point to the program. println! is a predefined macro in Rust. It is used to print a string (here Hello) to the console. Macro calls are always marked with an exclamation mark – !. Compile the Hello.rs file using rustc. Compile the Hello.rs file using rustc. C:\Users\Admin\HelloWorld-App>rustc Hello.rs Upon successful compilation of the program, an executable file (file_name.exe) is generated. To verify if the .exe file is generated, execute the following command. C:\Users\Admin\HelloWorld-App>dir //lists the files in folder Hello.exe Hello.pdb Hello.rs Execute the Hello.exe file and verify the output. Rust provides a powerful macro system that allows meta-programming. As you have seen in the previous example, macros look like functions, except that their name ends with a bang(!), but instead of generating a function call, macros are expanded into source code that gets compiled with the rest of the program. Therefore, they provide more runtime features to a program unlike functions. Macros are an extended version of functions. println!(); // prints just a newline println!("hello ");//prints hello println!("format {} arguments", "some"); //prints format some arguments Comments are a way to improve the readability of a program. Comments can be used to include additional information about a program like author of the code, hints about a function/ construct, etc. The compiler ignores comments. Rust supports the following types of comments − Single-line comments ( // ) − Any text between a // and the end of a line is treated as a comment Single-line comments ( // ) − Any text between a // and the end of a line is treated as a comment Multi-line comments (/* */) − These comments may span multiple lines. Multi-line comments (/* */) − These comments may span multiple lines. //this is single line comment /* This is a Multi-line comment */ Rust programs can be executed online through Tutorialspoint Coding Ground. Write the HelloWorld program in the Editor tab and click Execute to view result. The Type System represents the different types of values supported by the language. The Type System checks validity of the supplied values, before they are stored or manipulated by the program. This ensures that the code behaves as expected. The Type System further allows for richer code hinting and automated documentation too. Rust is a statically typed language. Every value in Rust is of a certain data type. The compiler can automatically infer data type of the variable based on the value assigned to it. Use the let keyword to declare a variable. fn main() { let company_string = "TutorialsPoint"; // string type let rating_float = 4.5; // float type let is_growing_boolean = true; // boolean type let icon_char = '♥'; //unicode character type println!("company name is:{}",company_string); println!("company rating on 5 is:{}",rating_float); println!("company is growing :{}",is_growing_boolean); println!("company icon is:{}",icon_char); } In the above example, data type of the variables will be inferred from the values assigned to them. For example, Rust will assign string data type to the variable company_string, float data type to rating_float, etc. The println! macro takes two arguments − A special syntax { }, which is the placeholder The variable name or a constant The placeholder will be replaced by the variable’s value The output of the above code snippet will be − company name is: TutorialsPoint company rating on 5 is:4.5 company is growing: true company icon is: ♥ A scalar type represents a single value. For example, 10,3.14,'c'. Rust has four primary scalar types. Integer Floating-point Booleans Characters We will learn about each type in our subsequent sections. An integer is a number without a fractional component. Simply put, the integer data type is used to represent whole numbers. Integers can be further classified as Signed and Unsigned. Signed integers can store both negative and positive values. Unsigned integers can only store positive values. A detailed description if integer types is given below − The size of an integer can be arch. This means the size of the data type will be derived from the architecture of the machine. An integer the size of which is arch will be 32 bits on an x86 machine and 64 bits on an x64 machine. An arch integer is primarily used when indexing some sort of collection. fn main() { let result = 10; // i32 by default let age:u32 = 20; let sum:i32 = 5-15; let mark:isize = 10; let count:usize = 30; println!("result value is {}",result); println!("sum is {} and age is {}",sum,age); println!("mark is {} and count is {}",mark,count); } The output will be as given below − result value is 10 sum is -10 and age is 20 mark is 10 and count is 30 The above code will return a compilation error if you replace the value of age with a floating-point value. Each signed variant can store numbers from -(2^(n-1) to 2^(n-1) -1, where n is the number of bits that variant uses. For example, i8 can store numbers from -(2^7) to 2^7 -1 − here we replaced n with 8. Each unsigned variant can store numbers from 0 to (2^n)-1. For example, u8 can store numbers from 0 to (2^8)-1, which is equal to 0 to 255. An integer overflow occurs when the value assigned to an integer variable exceeds the Rust defined range for the data type. Let us understand this with an example − fn main() { let age:u8 = 255; // 0 to 255 only allowed for u8 let weight:u8 = 256; //overflow value is 0 let height:u8 = 257; //overflow value is 1 let score:u8 = 258; //overflow value is 2 println!("age is {} ",age); println!("weight is {}",weight); println!("height is {}",height); println!("score is {}",score); } The valid range of unsigned u8 variable is 0 to 255. In the above example, the variables are assigned values greater than 255 (upper limit for an integer variable in Rust). On execution, the above code will return a warning − warning − literal out of range for u8 for weight, height and score variables. The overflow values after 255 will start from 0, 1, 2, etc. The final output without warning is as shown below − age is 255 weight is 0 height is 1 score is 2 Float data type in Rust can be classified as f32 and f64. The f32 type is a single-precision float, and f64 has double precision. The default type is f64. Consider the following example to understand more about the float data type. fn main() { let result = 10.00; //f64 by default let interest:f32 = 8.35; let cost:f64 = 15000.600; //double precision println!("result value is {}",result); println!("interest is {}",interest); println!("cost is {}",cost); } The output will be as shown below − interest is 8.35 cost is 15000.6 Automatic type casting is not allowed in Rust. Consider the following code snippet. An integer value is assigned to the float variable interest. fn main() { let interest:f32 = 8; // integer assigned to float variable println!("interest is {}",interest); } The compiler throws a mismatched types error as given below. error[E0308]: mismatched types --> main.rs:2:22 | 2 | let interest:f32=8; | ^ expected f32, found integral variable | = note: expected type `f32` found type `{integer}` error: aborting due to previous error(s) For easy readability of large numbers, we can use a visual separator _ underscore to separate digits. That is 50,000 can be written as 50_000 . This is shown in the below example. fn main() { let float_with_separator = 11_000.555_001; println!("float value {}",float_with_separator); let int_with_separator = 50_000; println!("int value {}",int_with_separator); } The output is given below − float value 11000.555001 int value 50000 Boolean types have two possible values – true or false. Use the bool keyword to declare a boolean variable. fn main() { let isfun:bool = true; println!("Is Rust Programming Fun ? {}",isfun); } The output of the above code will be − Is Rust Programming Fun ? true The character data type in Rust supports numbers, alphabets, Unicode and special characters. Use the char keyword to declare a variable of character data type. Rust’s char type represents a Unicode Scalar Value, which means it can represent a lot more than just ASCII. Unicode Scalar Values range from U+0000 to U+D7FF and U+E000 to U+10FFFF inclusive. Let us consider an example to understand more about the Character data type. fn main() { let special_character = '@'; //default let alphabet:char = 'A'; let emoji:char = '😁'; println!("special character is {}",special_character); println!("alphabet is {}",alphabet); println!("emoji is {}",emoji); } The output of the above code will be − special character is @ alphabet is A emoji is 😁 A variable is a named storage that programs can manipulate. Simply put, a variable helps programs to store values. Variables in Rust are associated with a specific data type. The data type determines the size and layout of the variable's memory, the range of values that can be stored within that memory and the set of operations that can be performed on the variable. In this section, we will learn about the different rules for naming a variable. The name of a variable can be composed of letters, digits, and the underscore character. The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Rust is case-sensitive. Upper and lowercase letters are distinct because Rust is case-sensitive. The data type is optional while declaring a variable in Rust. The data type is inferred from the value assigned to the variable. The syntax for declaring a variable is given below. let variable_name = value; // no type specified let variable_name:dataType = value; //type specified fn main() { let fees = 25_000; let salary:f64 = 35_000.00; println!("fees is {} and salary is {}",fees,salary); } The output of the above code will be fees is 25000 and salary is 35000. By default, variables are immutable − read only in Rust. In other words, the variable's value cannot be changed once a value is bound to a variable name. Let us understand this with an example. fn main() { let fees = 25_000; println!("fees is {} ",fees); fees = 35_000; println!("fees changed is {}",fees); } The output will be as shown below − error[E0384]: re-assignment of immutable variable `fees` --> main.rs:6:3 | 3 | let fees = 25_000; | ---- first assignment to `fees` ... 6 | fees=35_000; | ^^^^^^^^^^^ re-assignment of immutable variable error: aborting due to previous error(s) The error message indicates the cause of the error – you cannot assign values twice to immutable variable fees. This is one of the many ways Rust allows programmers to write code and takes advantage of the safety and easy concurrency. Variables are immutable by default. Prefix the variable name with mut keyword to make it mutable. The value of a mutable variable can be changed. The syntax for declaring a mutable variable is as shown below − let mut variable_name = value; let mut variable_name:dataType = value; Let us understand this with an example fn main() { let mut fees:i32 = 25_000; println!("fees is {} ",fees); fees = 35_000; println!("fees changed is {}",fees); } The output of the snippet is given below − fees is 25000 fees changed is 35000 Constants represent values that cannot be changed. If you declare a constant then there is no way its value changes. The keyword for using constants is const. Constants must be explicitly typed. Following is the syntax to declare a constant. const VARIABLE_NAME:dataType = value; The naming convention for Constants are similar to that of variables. All characters in a constant name are usually in uppercase. Unlike declaring variables, the let keyword is not used to declare a constant. We have used constants in Rust in the example below − fn main() { const USER_LIMIT:i32 = 100; // Declare a integer constant const PI:f32 = 3.14; //Declare a float constant println!("user limit is {}",USER_LIMIT); //Display value of the constant println!("pi value is {}",PI); //Display value of the constant } In this section, we will learn about the differentiating factors between constants and variables. Constants are declared using the const keyword while variables are declared using the let keyword. Constants are declared using the const keyword while variables are declared using the let keyword. A variable declaration can optionally have a data type whereas a constant declaration must specify the data type. This means const USER_LIMIT=100 will result in an error. A variable declaration can optionally have a data type whereas a constant declaration must specify the data type. This means const USER_LIMIT=100 will result in an error. A variable declared using the let keyword is by default immutable. However, you have an option to mutate it using the mut keyword. Constants are immutable. A variable declared using the let keyword is by default immutable. However, you have an option to mutate it using the mut keyword. Constants are immutable. Constants can be set only to a constant expression and not to the result of a function call or any other value that will be computed at runtime. Constants can be set only to a constant expression and not to the result of a function call or any other value that will be computed at runtime. Constants can be declared in any scope, including the global scope, which makes them useful for values that many parts of the code need to know about. Constants can be declared in any scope, including the global scope, which makes them useful for values that many parts of the code need to know about. Rust allows programmers to declare variables with the same name. In such a case, the new variable overrides the previous variable. Let us understand this with an example. fn main() { let salary = 100.00; let salary = 1.50 ; // reads first salary println!("The value of salary is :{}",salary); } The above code declares two variables by the name salary. The first declaration is assigned a 100.00 while the second declaration is assigned value 1.50. The second variable shadows or hides the first variable while displaying output. The value of salary is :1.50 Rust supports variables with different data types while shadowing. Consider the following example. The code declares two variables by the name uname. The first declaration is assigned a string value, whereas the second declaration is assigned an integer. The len function returns the total number of characters in a string value. fn main() { let uname = "Mohtashim"; let uname = uname.len(); println!("name changed to integer : {}",uname); } name changed to integer: 9 Unlike variables, constants cannot be shadowed. If variables in the above program are replaced with constants, the compiler will throw an error. fn main() { const NAME:&str = "Mohtashim"; const NAME:usize = NAME.len(); //Error : `NAME` already defined println!("name changed to integer : {}",NAME); } The String data type in Rust can be classified into the following − String Literal(&str) String Literal(&str) String Object(String) String Object(String) String literals (&str) are used when the value of a string is known at compile time. String literals are a set of characters, which are hardcoded into a variable. For example, let company="Tutorials Point". String literals are found in module std::str. String literals are also known as string slices. The following example declares two string literals − company and location. fn main() { let company:&str="TutorialsPoint"; let location:&str = "Hyderabad"; println!("company is : {} location :{}",company,location); } String literals are static by default. This means that string literals are guaranteed to be valid for the duration of the entire program. We can also explicitly specify the variable as static as shown below − fn main() { let company:&'static str = "TutorialsPoint"; let location:&'static str = "Hyderabad"; println!("company is : {} location :{}",company,location); } The above program will generate the following output − company is : TutorialsPoint location :Hyderabad The String object type is provided in Standard Library. Unlike string literal, the string object type is not a part of the core language. It is defined as public structure in standard library pub struct String. String is a growable collection. It is mutable and UTF-8 encoded type. The String object type can be used to represent string values that are provided at runtime. String object is allocated in the heap. To create a String object, we can use any of the following syntax − String::new() The above syntax creates an empty string String::from() This creates a string with some default value passed as parameter to the from() method. The following example illustrates the use of a String object. fn main(){ let empty_string = String::new(); println!("length is {}",empty_string.len()); let content_string = String::from("TutorialsPoint"); println!("length is {}",content_string.len()); } The above example creates two strings − an empty string object using the new method and a string object from string literal using the from method. The output is as shown below − length is 0 length is 14 An empty string object is created using the new() method and its value is set to hello. fn main(){ let mut z = String::new(); z.push_str("hello"); println!("{}",z); } The above program generates the following output − hello To access all methods of String object, convert a string literal to object type using the to_string() function. fn main(){ let name1 = "Hello TutorialsPoint , Hello!".to_string(); println!("{}",name1); } The above program generates the following output − Hello TutorialsPoint , Hello! The replace() function takes two parameters − the first parameter is a string pattern to search for and the second parameter is the new value to be replaced. In the above example, Hello appears two times in the name1 string. The replace function replaces all occurrences of the string Hello with Howdy. fn main(){ let name1 = "Hello TutorialsPoint , Hello!".to_string(); //String object let name2 = name1.replace("Hello","Howdy"); //find and replace println!("{}",name2); } The above program generates the following output − Howdy TutorialsPoint , Howdy! The as_str() function extracts a string slice containing the entire string. fn main() { let example_string = String::from("example_string"); print_literal(example_string.as_str()); } fn print_literal(data:&str ){ println!("displaying string literal {}",data); } The above program generates the following output − displaying string literal example_string The push() function appends the given char to the end of this String. fn main(){ let mut company = "Tutorial".to_string(); company.push('s'); println!("{}",company); } The above program generates the following output − Tutorials The push_str() function appends a given string slice onto the end of a String. fn main(){ let mut company = "Tutorials".to_string(); company.push_str(" Point"); println!("{}",company); } The above program generates the following output − Tutorials Point The len() function returns the total number of characters in a string (including spaces). fn main() { let fullname = " Tutorials Point"; println!("length is {}",fullname.len()); } The above program generates the following output − length is 20 The trim() function removes leading and trailing spaces in a string. NOTE that this function will not remove the inline spaces. fn main() { let fullname = " Tutorials Point \r\n"; println!("Before trim "); println!("length is {}",fullname.len()); println!(); println!("After trim "); println!("length is {}",fullname.trim().len()); } The above program generates the following output − Before trim length is 24 After trim length is 15 The split_whitespace() splits the input string into different strings. It returns an iterator so we are iterating through the tokens as shown below − fn main(){ let msg = "Tutorials Point has good t utorials".to_string(); let mut i = 1; for token in msg.split_whitespace(){ println!("token {} {}",i,token); i+=1; } } token 1 Tutorials token 2 Point token 3 has token 4 good token 5 tutorials The split() string method returns an iterator over substrings of a string slice, separated by characters matched by a pattern. The limitation of the split() method is that the result cannot be stored for later use. The collect method can be used to store the result returned by split() as a vector. fn main() { let fullname = "Kannan,Sudhakaran,Tutorialspoint"; for token in fullname.split(","){ println!("token is {}",token); } //store in a Vector println!("\n"); let tokens:Vec<&str>= fullname.split(",").collect(); println!("firstName is {}",tokens[0]); println!("lastname is {}",tokens[1]); println!("company is {}",tokens[2]); } The above example splits the string fullname, whenever it encounters a comma (,). token is Kannan token is Sudhakaran token is Tutorialspoint firstName is Kannan lastname is Sudhakaran company is Tutorialspoint Individual characters in a string can be accessed using the chars method. Let us consider an example to understand this. fn main(){ let n1 = "Tutorials".to_string(); for n in n1.chars(){ println!("{}",n); } } T u t o r i a l s A string value can be appended to another string. This is called concatenation or interpolation. The result of string concatenation is a new string object. The + operator internally uses an add method. The syntax of the add function takes two parameters. The first parameter is self – the string object itself and the second parameter is a reference of the second string object. This is shown below − //add function add(self,&str)->String { // returns a String object } fn main(){ let n1 = "Tutorials".to_string(); let n2 = "Point".to_string(); let n3 = n1 + &n2; // n2 reference is passed println!("{}",n3); } The Output will be as given below TutorialsPoint The following example illustrates converting a number to a string object − fn main(){ let number = 2020; let number_as_string = number.to_string(); // convert number to string println!("{}",number_as_string); println!("{}",number_as_string=="2020"); } The Output will be as given below 2020 true Another way to add to String objects together is using a macro function called format. The use of Format! is as shown below. fn main(){ let n1 = "Tutorials".to_string(); let n2 = "Point".to_string(); let n3 = format!("{} {}",n1,n2); println!("{}",n3); } The Output will be as given below Tutorials Point An operator defines some function that will be performed on the data. The data on which operators work are called operands. Consider the following expression − 7 + 5 = 12 Here, the values 7, 5, and 12 are operands, while + and = are operators. The major operators in Rust can be classified as − Arithmetic Bitwise Comparison Logical Bitwise Conditional Assume the values in variables a and b are 10 and 5 respectively. Show Examples NOTE − The ++ and -- operators are not supported in Rust. Relational Operators test or define the kind of relationship between two entities. Relational operators are used to compare two or more values. Relational operators return a Boolean value − true or false. Assume the value of A is 10 and B is 20. Show Examples Logical Operators are used to combine two or more conditions. Logical operators too, return a Boolean value. Assume the value of variable A is 10 and B is 20. Show Examples Assume variable A = 2 and B = 3. Show Examples Decision-making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Shown below is the general form of a typical decision-making structure found in most of the programming languages − if statement An if statement consists of a Boolean expression followed by one or more statements. if...else statement An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. else...if and nested ifstatement You can use one if or else if statement inside another if or else if statement(s). match statement A match statement allows a variable to be tested against a list of values. The if...else construct evaluates a condition before a block of code is executed. if boolean_expression { // statement(s) will execute if the boolean expression is true } If the Boolean expression evaluates to true, then the block of code inside the if statement will be executed. If the Boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing curly brace) will be executed. fn main(){ let num:i32 = 5; if num > 0 { println!("number is positive") ; } } The above example will print number is positive as the condition specified by the if block is true. An if can be followed by an optional else block. The else block will execute if the Boolean expression tested by the if statement evaluates to false. if boolean_expression { // statement(s) will execute if the boolean expression is true } else { // statement(s) will execute if the boolean expression is false } The if block guards the conditional expression. The block associated with the if statement is executed if the Boolean expression evaluates to true. The if block may be followed by an optional else statement. The instruction block associated with the else block is executed if the expression evaluates to false. fn main() { let num = 12; if num % 2==0 { println!("Even"); } else { println!("Odd"); } } The above example prints whether the value in a variable is even or odd. The if block checks the divisibility of the value by 2 to determine the same. Here is the output of the above code − Even The else...if ladder is useful to test multiple conditions. The syntax is as shown below − if boolean_expression1 { //statements if the expression1 evaluates to true } else if boolean_expression2 { //statements if the expression2 evaluates to true } else { //statements if both expression1 and expression2 result to false } When using if...else...if and else statements, there are a few points to keep in mind. An if can have zero or one else's and it must come after any else..if. An if can have zero to many else..if and they must come before the else. Once an else..if succeeds, none of the remaining else..if or else will be tested. fn main() { let num = 2 ; if num > 0 { println!("{} is positive",num); } else if num < 0 { println!("{} is negative",num); } else { println!("{} is neither positive nor negative",num) ; } } The snippet displays whether the value is positive, negative or zero. 2 is positive The match statement checks if a current value is matching from a list of values, this is very much similar to the switch statement in C language. In the first place, notice that the expression following the match keyword does not have to be enclosed in parentheses. The syntax is as shown below. let expressionResult = match variable_expression { constant_expr1 => { //statements; }, constant_expr2 => { //statements; }, _ => { //default } }; In the example given below, state_code is matched with a list of values MH, KL, KA, GA − if any match is found, a string value is returned to variable state. If no match is found, the default case _ matches and value Unkown is returned. fn main(){ let state_code = "MH"; let state = match state_code { "MH" => {println!("Found match for MH"); "Maharashtra"}, "KL" => "Kerala", "KA" => "Karnadaka", "GA" => "Goa", _ => "Unknown" }; println!("State name is {}",state); } Found match for MH State name is Maharashtra There may be instances, where a block of code needs to be executed repeatedly. In general, programming instructions are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times. Given below is the general form of a loop statement in most of the programming languages. Rust provides different types of loops to handle looping requirements − while loop for A loop the number of iterations of which is definite/fixed is termed as a definite loop. The for loop is an implementation of a definite loop. The for loop executes the code block for a specified number of times. It can be used to iterate over a fixed set of values, such as an array. The syntax of the for loop is as given below for temp_variable in lower_bound..upper_bound { //statements } An example of a for loop is as shown below fn main(){ for x in 1..11{ // 11 is not inclusive if x==5 { continue; } println!("x is {}",x); } } NOTE: that the variable x is only accessible within the for block. x is 1 x is 2 x is 3 x is 4 x is 6 x is 7 x is 8 x is 9 x is 10 An indefinite loop is used when the number of iterations in a loop is indeterminate or unknown. Indefinite loops can be implemented using − While The while loop executes the instructions each time the condition specified evaluates to true Loop The loop is a while(true) indefinite loop fn main(){ let mut x = 0; while x < 10{ x+=1; println!("inside loop x value is {}",x); } println!("outside loop x value is {}",x); } The output is as shown below − inside loop x value is 1 inside loop x value is 2 inside loop x value is 3 inside loop x value is 4 inside loop x value is 5 inside loop x value is 6 inside loop x value is 7 inside loop x value is 8 inside loop x value is 9 inside loop x value is 10 outside loop x value is 10 fn main(){ //while true let mut x = 0; loop { x+=1; println!("x={}",x); if x==15 { break; } } } The break statement is used to take the control out of a construct. Using break in a loop causes the program to exit the loop. x=1 x=2 x=3 x=4 x=5 x=6 x=7 x=8 x=9 x=10 x=11 x=12 x=13 x=14 x=15 The continue statement skips the subsequent statements in the current iteration and takes the control back to the beginning of the loop. Unlike the break statement, the continue does not exit the loop. It terminates the current iteration and starts the subsequent iteration. An example of the continue statement is given below. fn main() { let mut count = 0; for num in 0..21 { if num % 2==0 { continue; } count+=1; } println! (" The count of odd values between 0 and 20 is: {} ",count); //outputs 10 } The above example displays the number of even values between 0 and 20. The loop exits the current iteration if the number is even. This is achieved using the continue statement. The count of odd values between 0 and 20 is 10 Functions are the building blocks of readable, maintainable, and reusable code. A function is a set of statements to perform a specific task. Functions organize the program into logical blocks of code. Once defined, functions may be called to access code. This makes the code reusable. Moreover, functions make it easy to read and maintain the program’s code. A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function. Defining a function A function definition specifies what and how a specific task would be done. Calling or invoking a Function A function must be called so as to execute it. Returning Functions Functions may also return value along with control, back to the caller. Parameterized Function Parameters are a mechanism to pass values to functions. A function definition specifies what and how a specific task would be done. Before using a function, it must be defined. The function body contains code that should be executed by the function. The rules for naming a function are similar to that of a variable. Functions are defined using the fn keyword. The syntax for defining a standard function is given below fn function_name(param1,param2..paramN) { // function body } A function declaration can optionally contain parameters/arguments. Parameters are used to pass values to functions. //Defining a function fn fn_hello(){ println!("hello from function fn_hello "); } A function must be called so as to execute it. This process is termed as function invocation. Values for parameters should be passed when a function is invoked. The function that invokes another function is called the caller function. function_name(val1,val2,valN) fn main(){ //calling a function fn_hello(); } Here, the main() is the caller function. The following example defines a function fn_hello(). The function prints a message to the console. The main() function invokes the fn_hello() function. fn main(){ //calling a function fn_hello(); } //Defining a function fn fn_hello(){ println!("hello from function fn_hello "); } hello from function fn_hello Functions may also return a value along with control, back to the caller. Such functions are called returning functions. Either of the following syntax can be used to define a function with return type. // Syntax1 function function_name() -> return_type { //statements return value; } //Syntax2 function function_name() -> return_type { value //no semicolon means this value is returned } fn main(){ println!("pi value is {}",get_pi()); } fn get_pi()->f64 { 22.0/7.0 } pi value is 3.142857142857143 Parameters are a mechanism to pass values to functions. Parameters form a part of the function’s signature. The parameter values are passed to the function during its invocation. Unless explicitly specified, the number of values passed to a function must match the number of parameters defined. Parameters can be passed to a function using one of the following techniques − When a method is invoked, a new storage location is created for each value parameter. The values of the actual parameters are copied into them. Hence, the changes made to the parameter inside the invoked method have no effect on the argument. The following example declares a variable no, which is initially 5. The variable is passed as parameter (by value) to the mutate_no_to_zero()functionnction, which changes the value to zero. After the function call when control returns back to main method the value will be the same. fn main(){ let no:i32 = 5; mutate_no_to_zero(no); println!("The value of no is:{}",no); } fn mutate_no_to_zero(mut param_no: i32) { param_no = param_no*0; println!("param_no value is :{}",param_no); } Output param_no value is :0 The value of no is:5 When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters. The reference parameters represent the same memory location as the actual parameters that are supplied to the method. Parameter values can be passed by reference by prefixing the variable name with an & . In the example given below, we have a variable no, which is initially 5. A reference to the variable no is passed to the mutate_no_to_zero() function. The function operates on the original variable. After the function call, when control returns back to main method, the value of the original variable will be the zero. fn main() { let mut no:i32 = 5; mutate_no_to_zero(&mut no); println!("The value of no is:{}",no); } fn mutate_no_to_zero(param_no:&mut i32){ *param_no = 0; //de reference } The * operator is used to access value stored in the memory location that the variable param_no points to. This is also known as dereferencing. The output will be − The value of no is 0. The main() function passes a string object to the display() function. fn main(){ let name:String = String::from("TutorialsPoint"); display(name); //cannot access name after display } fn display(param_name:String){ println!("param_name value is :{}",param_name); } param_name value is :TutorialsPoint Tuple is a compound data type. A scalar type can store only one type of data. For example, an i32 variable can store only a single integer value. In compound types, we can store more than one value at a time and it can be of different types. Tuples have a fixed length - once declared they cannot grow or shrink in size. The tuple index starts from 0. //Syntax1 let tuple_name:(data_type1,data_type2,data_type3) = (value1,value2,value3); //Syntax2 let tuple_name = (value1,value2,value3); The following example displays the values in a tuple. fn main() { let tuple:(i32,f64,u8) = (-325,4.9,22); println!("{:?}",tuple); } The println!("{ }",tuple) syntax cannot be used to display values in a tuple. This is because a tuple is a compound type. Use the println!("{:?}", tuple_name) syntax to print values in a tuple. (-325, 4.9, 22) The following example prints individual values in a tuple. fn main() { let tuple:(i32,f64,u8) = (-325,4.9,22); println!("integer is :{:?}",tuple.0); println!("float is :{:?}",tuple.1); println!("unsigned integer is :{:?}",tuple.2); } integer is :-325 float is :4.9 unsigned integer is :2 The following example passes a tuple as parameter to a function. Tuples are passed by value to functions. fn main(){ let b:(i32,bool,f64) = (110,true,10.9); print(b); } //pass the tuple as a parameter fn print(x:(i32,bool,f64)){ println!("Inside print method"); println!("{:?}",x); } Inside print method (110, true, 10.9) Destructing assignment is a feature of rust wherein we unpack the values of a tuple. This is achieved by assigning a tuple to distinct variables. Consider the following example − fn main(){ let b:(i32,bool,f64) = (30,true,7.9); print(b); } fn print(x:(i32,bool,f64)){ println!("Inside print method"); let (age,is_male,cgpa) = x; //assigns a tuple to distinct variables println!("Age is {} , isMale? {},cgpa is {}",age,is_male,cgpa); } Variable x is a tuple which is assigned to the let statement. Each variable - age, is_male and cgpa will contain the corresponding values in a tuple. Inside print method Age is 30 , isMale? true,cgpa is 7.9 In this chapter, we will learn about an array and the various features associated with it. Before we learn about arrays, let us see how an array is different from a variable. Variables have the following limitations − Variables are scalar in nature. In other words, a variable declaration can only contain a single value at a time. This means that to store n values in a program n variable declaration will be needed. Hence, the use of variables is not feasible when one needs to store a larger collection of values. Variables are scalar in nature. In other words, a variable declaration can only contain a single value at a time. This means that to store n values in a program n variable declaration will be needed. Hence, the use of variables is not feasible when one needs to store a larger collection of values. Variables in a program are allocated memory in random order, thereby making it difficult to retrieve/read the values in the order of their declaration. Variables in a program are allocated memory in random order, thereby making it difficult to retrieve/read the values in the order of their declaration. An array is a homogeneous collection of values. Simply put, an array is a collection of values of the same data type. The features of an array are as listed below − An array declaration allocates sequential memory blocks. An array declaration allocates sequential memory blocks. Arrays are static. This means that an array once initialized cannot be resized. Arrays are static. This means that an array once initialized cannot be resized. Each memory block represents an array element. Each memory block represents an array element. Array elements are identified by a unique integer called the subscript/ index of the element. Array elements are identified by a unique integer called the subscript/ index of the element. Populating the array elements is known as array initialization. Populating the array elements is known as array initialization. Array element values can be updated or modified but cannot be deleted. Array element values can be updated or modified but cannot be deleted. Use the syntax given below to declare and initialize an array in Rust. //Syntax1 let variable_name = [value1,value2,value3]; //Syntax2 let variable_name:[dataType;size] = [value1,value2,value3]; //Syntax3 let variable_name:[dataType;size] = [default_value_for_elements,size]; In the first syntax, type of the array is inferred from the data type of the array’s first element during initialization. The following example explicitly specifies the size and the data type of the array. The {:?} syntax of the println!() function is used to print all values in the array. The len() function is used to compute the size of the array. fn main(){ let arr:[i32;4] = [10,20,30,40]; println!("array is {:?}",arr); println!("array size is :{}",arr.len()); } array is [10, 20, 30, 40] array size is :4 The following program declares an array of 4 elements. The datatype is not explicitly specified during the variable declaration. In this case, the array will be of type integer. The len() function is used to compute the size of the array. fn main(){ let arr = [10,20,30,40]; println!("array is {:?}",arr); println!("array size is :{}",arr.len()); } array is [10, 20, 30, 40] array size is :4 The following example creates an array and initializes all its elements with a default value of -1. fn main() { let arr:[i32;4] = [-1;4]; println!("array is {:?}",arr); println!("array size is :{}",arr.len()); } array is [-1, -1, -1, -1] array size is :4 The following example iterates through an array and prints the indexes and their corresponding values. The loop retrieves values from index 0 to 4 (index of the last array element). fn main(){ let arr:[i32;4] = [10,20,30,40]; println!("array is {:?}",arr); println!("array size is :{}",arr.len()); for index in 0..4 { println!("index is: {} & value is : {}",index,arr[index]); } } array is [10, 20, 30, 40] array size is :4 index is: 0 & value is : 10 index is: 1 & value is : 20 index is: 2 & value is : 30 index is: 3 & value is : 40 The iter() function fetches values of all elements in an array. fn main(){ let arr:[i32;4] = [10,20,30,40]; println!("array is {:?}",arr); println!("array size is :{}",arr.len()); for val in arr.iter(){ println!("value is :{}",val); } } array is [10, 20, 30, 40] array size is :4 value is :10 value is :20 value is :30 value is :40 The mut keyword can be used to declare a mutable array. The following example declares a mutable array and modifies value of the second array element. fn main(){ let mut arr:[i32;4] = [10,20,30,40]; arr[1] = 0; println!("{:?}",arr); } [10, 0, 30, 40] An array can be passed by value or by reference to functions. fn main() { let arr = [10,20,30]; update(arr); print!("Inside main {:?}",arr); } fn update(mut arr:[i32;3]){ for i in 0..3 { arr[i] = 0; } println!("Inside update {:?}",arr); } Inside update [0, 0, 0] Inside main [10, 20, 30] fn main() { let mut arr = [10,20,30]; update(&mut arr); print!("Inside main {:?}",arr); } fn update(arr:&mut [i32;3]){ for i in 0..3 { arr[i] = 0; } println!("Inside update {:?}",arr); } Inside update [0, 0, 0] Inside main [0, 0, 0] Let us consider an example given below to understand array declaration and constants. fn main() { let N: usize = 20; let arr = [0; N]; //Error: non-constant used with constant print!("{}",arr[10]) } The compiler will result in an exception. This is because an array's length must be known at compile time. Here, the value of the variable "N" will be determined at runtime. In other words, variables cannot be used to define the size of an array. However, the following program is valid − fn main() { const N: usize = 20; // pointer sized let arr = [0; N]; print!("{}",arr[10]) } The value of an identifier prefixed with the const keyword is defined at compile time and cannot be changed at runtime. usize is pointer-sized, thus its actual size depends on the architecture you are compiling your program for. The memory for a program can be allocated in the following − Stack Heap A stack follows a last in first out order. Stack stores data values for which the size is known at compile time. For example, a variable of fixed size i32 is a candidate for stack allocation. Its size is known at compile time. All scalar types can be stored in stack as the size is fixed. Consider an example of a string, which is assigned a value at runtime. The exact size of such a string cannot be determined at compile time. So it is not a candidate for stack allocation but for heap allocation. The heap memory stores data values the size of which is unknown at compile time. It is used to store dynamic data. Simply put, a heap memory is allocated to data values that may change throughout the life cycle of the program. The heap is an area in the memory which is less organized when compared to stack. Each value in Rust has a variable that is called owner of the value. Every data stored in Rust will have an owner associated with it. For example, in the syntax − let age = 30, age is the owner of the value 30. Each data can have only one owner at a time. Each data can have only one owner at a time. Two variables cannot point to the same memory location. The variables will always be pointing to different memory locations. Two variables cannot point to the same memory location. The variables will always be pointing to different memory locations. The ownership of value can be transferred by − Assigning value of one variable to another variable. Assigning value of one variable to another variable. Passing value to a function. Passing value to a function. Returning value from a function. Returning value from a function. The key selling point of Rust as a language is its memory safety. Memory safety is achieved by tight control on who can use what and when restrictions. Consider the following snippet − fn main(){ let v = vec![1,2,3]; // vector v owns the object in heap //only a single variable owns the heap memory at any given time let v2 = v; // here two variables owns heap value, //two pointers to the same content is not allowed in rust //Rust is very smart in terms of memory access ,so it detects a race condition //as two variables point to same heap println!("{:?}",v); } The above example declares a vector v. The idea of ownership is that only one variable binds to a resource, either v binds to resource or v2 binds to the resource. The above example throws an error − use of moved value: `v`. This is because the ownership of the resource is transferred to v2. It means the ownership is moved from v to v2 (v2=v) and v is invalidated after the move. The ownership of a value also changes when we pass an object in the heap to a closure or function. fn main(){ let v = vec![1,2,3]; // vector v owns the object in heap let v2 = v; // moves ownership to v2 display(v2); // v2 is moved to display and v2 is invalidated println!("In main {:?}",v2); //v2 is No longer usable here } fn display(v:Vec<i32>){ println!("inside display {:?}",v); } Ownership passed to the function will be invalidated as function execution completes. One work around for this is let the function return the owned object back to the caller. fn main(){ let v = vec![1,2,3]; // vector v owns the object in heap let v2 = v; // moves ownership to v2 let v2_return = display(v2); println!("In main {:?}",v2_return); } fn display(v:Vec<i32>)->Vec<i32> { // returning same vector println!("inside display {:?}",v); } In case of primitive types, contents from one variable is copied to another. So, there is no ownership move happening. This is because a primitive variable needs less resources than an object. Consider the following example − fn main(){ let u1 = 10; let u2 = u1; // u1 value copied(not moved) to u2 println!("u1 = {}",u1); } The output will be – 10. It is very inconvenient to pass the ownership of a variable to another function and then return the ownership. Rust supports a concept, borrowing, where the ownership of a value is transferred temporarily to an entity and then returned to the original owner entity. Consider the following − fn main(){ // a list of nos let v = vec![10,20,30]; print_vector(v); println!("{}",v[0]); // this line gives error } fn print_vector(x:Vec<i32>){ println!("Inside print_vector function {:?}",x); } The main function invokes a function print_vector(). A vector is passed as parameter to this function. The ownership of the vector is also passed to the print_vector() function from the main(). The above code will result in an error as shown below when the main() function tries to access the vector v. | print_vector(v); | - value moved here | println!("{}",v[0]); | ^ value used here after move This is because a variable or value can no longer be used by the function that originally owned it once the ownership is transferred to another function. When a function transfers its control over a variable/value to another function temporarily, for a while, it is called borrowing. This is achieved by passing a reference to the variable (& var_name) rather than passing the variable/value itself to the function. The ownership of the variable/ value is transferred to the original owner of the variable after the function to which the control was passed completes execution. fn main(){ // a list of nos let v = vec![10,20,30]; print_vector(&v); // passing reference println!("Printing the value from main() v[0]={}",v[0]); } fn print_vector(x:&Vec<i32>){ println!("Inside print_vector function {:?}",x); } Inside print_vector function [10, 20, 30] Printing the value from main() v[0] = 10 A function can modify a borrowed resource by using a mutable reference to such resource. A mutable reference is prefixed with &mut. Mutable references can operate only on mutable variables. fn add_one(e: &mut i32) { *e+= 1; } fn main() { let mut i = 3; add_one(&mut i); println!("{}", i); } The main() function declares a mutable integer variable i and passes a mutable reference of i to the add_one(). The add_one() increments the value of the variable i by one. fn main() { let mut name:String = String::from("TutorialsPoint"); display(&mut name); //pass a mutable reference of name println!("The value of name after modification is:{}",name); } fn display(param_name:&mut String){ println!("param_name value is :{}",param_name); param_name.push_str(" Rocks"); //Modify the actual string,name } The main() function passes a mutable reference of the variable name to the display() function. The display function appends an additional string to the original name variable. param_name value is :TutorialsPoint The value of name after modification is:TutorialsPoint Rocks A slice is a pointer to a block of memory. Slices can be used to access portions of data stored in contiguous memory blocks. It can be used with data structures like arrays, vectors and strings. Slices use index numbers to access portions of data. The size of a slice is determined at runtime. Slices are pointers to the actual data. They are passed by reference to functions, which is also known as borrowing. For example, slices can be used to fetch a portion of a string value. A sliced string is a pointer to the actual string object. Therefore, we need to specify the starting and ending index of a String. Index starts from 0 just like arrays. let sliced_value = &data_structure[start_index..end_index] The minimum index value is 0 and the maximum index value is the size of the data structure. NOTE that the end_index will not be included in final string. The diagram below shows a sample string Tutorials, that has 9 characters. The index of the first character is 0 and that of the last character is 8. The following code fetches 5 characters from the string (starting from index 4). fn main() { let n1 = "Tutorials".to_string(); println!("length of string is {}",n1.len()); let c1 = &n1[4..9]; // fetches characters at 4,5,6,7, and 8 indexes println!("{}",c1); } length of string is 9 rials The main() function declares an array with 5 elements. It invokes the use_slice() function and passes to it a slice of three elements (points to the data array). The slices are passed by reference. The use_slice() function prints the value of the slice and its length. fn main(){ let data = [10,20,30,40,50]; use_slice(&data[1..4]); //this is effectively borrowing elements for a while } fn use_slice(slice:&[i32]) { // is taking a slice or borrowing a part of an array of i32s println!("length of slice is {:?}",slice.len()); println!("{:?}",slice); } length of slice is 3 [20, 30, 40] The &mut keyword can be used to mark a slice as mutable. fn main(){ let mut data = [10,20,30,40,50]; use_slice(&mut data[1..4]); // passes references of 20, 30 and 40 println!("{:?}",data); } fn use_slice(slice:&mut [i32]) { println!("length of slice is {:?}",slice.len()); println!("{:?}",slice); slice[0] = 1010; // replaces 20 with 1010 } length of slice is 3 [20, 30, 40] [10, 1010, 30, 40, 50] The above code passes a mutable slice to the use_slice() function. The function modifies the second element of the original array. Arrays are used to represent a homogeneous collection of values. Similarly, a structure is another user defined data type available in Rust that allows us to combine data items of different types, including another structure. A structure defines data as a key-value pair. The struct keyword is used to declare a structure. Since structures are statically typed, every field in the structure must be associated with a data type. The naming rules and conventions for a structure is like that of a variable. The structure block must end with a semicolon. struct Name_of_structure { field1:data_type, field2:data_type, field3:data_type } After declaring a struct, each field should be assigned a value. This is known as initialization. let instance_name = Name_of_structure { field1:value1, field2:value2, field3:value3 }; //NOTE the semicolon Syntax: Accessing values in a structure Use the dot notation to access value of a specific field. instance_name.field1 Illustration struct Employee { name:String, company:String, age:u32 } fn main() { let emp1 = Employee { company:String::from("TutorialsPoint"), name:String::from("Mohtashim"), age:50 }; println!("Name is :{} company is {} age is {}",emp1.name,emp1.company,emp1.age); } The above example declares a struct Employee with three fields – name, company and age of types. The main() initializes the structure. It uses the println! macro to print values of the fields defined in the structure. Name is :Mohtashim company is TutorialsPoint age is 50 To modify an instance, the instance variable should be marked mutable. The below example declares and initializes a structure named Employee and later modifies value of the age field to 40 from 50. let mut emp1 = Employee { company:String::from("TutorialsPoint"), name:String::from("Mohtashim"), age:50 }; emp1.age = 40; println!("Name is :{} company is {} age is {}",emp1.name,emp1.company,emp1.age); Name is :Mohtashim company is TutorialsPoint age is 40 The following example shows how to pass instance of struct as a parameter. The display method takes an Employee instance as parameter and prints the details. fn display( emp:Employee) { println!("Name is :{} company is {} age is {}",emp.name,emp.company,emp.age); } Here is the complete program − //declare a structure struct Employee { name:String, company:String, age:u32 } fn main() { //initialize a structure let emp1 = Employee { company:String::from("TutorialsPoint"), name:String::from("Mohtashim"), age:50 }; let emp2 = Employee{ company:String::from("TutorialsPoint"), name:String::from("Kannan"), age:32 }; //pass emp1 and emp2 to display() display(emp1); display(emp2); } // fetch values of specific structure fields using the // operator and print it to the console fn display( emp:Employee){ println!("Name is :{} company is {} age is {}",emp.name,emp.company,emp.age); } Name is :Mohtashim company is TutorialsPoint age is 50 Name is :Kannan company is TutorialsPoint age is 32 Let us consider a function who_is_elder(), which compares two employees age and returns the elder one. fn who_is_elder (emp1:Employee,emp2:Employee)->Employee { if emp1.age>emp2.age { return emp1; } else { return emp2; } } Here is the complete program − fn main() { //initialize structure let emp1 = Employee{ company:String::from("TutorialsPoint"), name:String::from("Mohtashim"), age:50 }; let emp2 = Employee { company:String::from("TutorialsPoint"), name:String::from("Kannan"), age:32 }; let elder = who_is_elder(emp1,emp2); println!("elder is:"); //prints details of the elder employee display(elder); } //accepts instances of employee structure and compares their age fn who_is_elder (emp1:Employee,emp2:Employee)->Employee { if emp1.age>emp2.age { return emp1; } else { return emp2; } } //display name, comapny and age of the employee fn display( emp:Employee) { println!("Name is :{} company is {} age is {}",emp.name,emp.company,emp.age); } //declare a structure struct Employee { name:String, company:String, age:u32 } elder is: Name is :Mohtashim company is TutorialsPoint age is 50 Methods are like functions. They are a logical group of programming instructions. Methods are declared with the fn keyword. The scope of a method is within the structure block. Methods are declared outside the structure block. The impl keyword is used to define a method within the context of a structure. The first parameter of a method will be always self, which represents the calling instance of the structure. Methods operate on the data members of a structure. To invoke a method, we need to first instantiate the structure. The method can be called using the structure's instance. struct My_struct {} impl My_struct { //set the method's context fn method_name() { //define a method } } The following example defines a structure Rectangle with fields − width and height. A method area is defined within the structure's context. The area method accesses the structure's fields via the self keyword and calculates the area of a rectangle. //define dimensions of a rectangle struct Rectangle { width:u32, height:u32 } //logic to calculate area of a rectangle impl Rectangle { fn area(&self)->u32 { //use the . operator to fetch the value of a field via the self keyword self.width * self.height } } fn main() { // instanatiate the structure let small = Rectangle { width:10, height:20 }; //print the rectangle's area println!("width is {} height is {} area of Rectangle is {}",small.width,small.height,small.area()); } width is 10 height is 20 area of Rectangle is 200 Static methods can be used as utility methods. These methods exist even before the structure is instantiated. Static methods are invoked using the structure's name and can be accessed without an instance. Unlike normal methods, a static method will not take the &self parameter. A static method like functions and other methods can optionally contain parameters. impl Structure_Name { //static method that creates objects of the Point structure fn method_name(param1: datatype, param2: datatype) -> return_type { // logic goes here } } The structure_name :: syntax is used to access a static method. structure_name::method_name(v1,v2) The following example uses the getInstance method as a factory class that creates and returns instances of the structure Point. //declare a structure struct Point { x: i32, y: i32, } impl Point { //static method that creates objects of the Point structure fn getInstance(x: i32, y: i32) -> Point { Point { x: x, y: y } } //display values of the structure's field fn display(&self){ println!("x ={} y={}",self.x,self.y ); } } fn main(){ // Invoke the static method let p1 = Point::getInstance(10,20); p1.display(); } x =10 y=20 In Rust programming, when we have to select a value from a list of possible variants we use enumeration data types. An enumerated type is declared using the enum keyword. Following is the syntax of enum − enum enum_name { variant1, variant2, variant3 } The example declares an enum − GenderCategory, which has variants as Male and Female. The print! macro displays value of the enum. The compiler will throw an error the trait std::fmt::Debug is not implemented for GenderCategory. The attribute #[derive(Debug)] is used to suppress this error. // The `derive` attribute automatically creates the implementation // required to make this `enum` printable with `fmt::Debug`. #[derive(Debug)] enum GenderCategory { Male,Female } fn main() { let male = GenderCategory::Male; let female = GenderCategory::Female; println!("{:?}",male); println!("{:?}",female); } Male Female The following example defines a structure Person. The field gender is of the type GenderCategory (which is an enum) and can be assigned either Male or Female as value. // The `derive` attribute automatically creates the implementation // required to make this `enum` printable with `fmt::Debug`. #[derive(Debug)] enum GenderCategory { Male,Female } // The `derive` attribute automatically creates the implementation // required to make this `struct` printable with `fmt::Debug`. #[derive(Debug)] struct Person { name:String, gender:GenderCategory } fn main() { let p1 = Person { name:String::from("Mohtashim"), gender:GenderCategory::Male }; let p2 = Person { name:String::from("Amy"), gender:GenderCategory::Female }; println!("{:?}",p1); println!("{:?}",p2); } The example creates objects p1 and p2 of type Person and initializes the attributes, name and gender for each of these objects. Person { name: "Mohtashim", gender: Male } Person { name: "Amy", gender: Female } Option is a predefined enum in the Rust standard library. This enum has two values − Some(data) and None. enum Option<T> { Some(T), //used to return a value None // used to return null, as Rust doesn't support the null keyword } Here, the type T represents value of any type. Rust does not support the null keyword. The value None, in the enumOption, can be used by a function to return a null value. If there is data to return, the function can return Some(data). Let us understand this with an example − The program defines a function is_even(), with a return type Option. The function verifies if the value passed is an even number. If the input is even, then a value true is returned, else the function returns None. fn main() { let result = is_even(3); println!("{:?}",result); println!("{:?}",is_even(30)); } fn is_even(no:i32)->Option<bool> { if no%2 == 0 { Some(true) } else { None } } None Some(true) The match statement can be used to compare values stored in an enum. The following example defines a function, print_size, which takes CarType enum as parameter. The function compares the parameter values with a pre-defined set of constants and displays the appropriate message. enum CarType { Hatch, Sedan, SUV } fn print_size(car:CarType) { match car { CarType::Hatch => { println!("Small sized car"); }, CarType::Sedan => { println!("medium sized car"); }, CarType::SUV =>{ println!("Large sized Sports Utility car"); } } } fn main(){ print_size(CarType::SUV); print_size(CarType::Hatch); print_size(CarType::Sedan); } Large sized Sports Utility car Small sized car medium sized car The example of is_even function, which returns Option type, can also be implemented with match statement as shown below − fn main() { match is_even(5) { Some(data) => { if data==true { println!("Even no"); } }, None => { println!("not even"); } } } fn is_even(no:i32)->Option<bool> { if no%2 == 0 { Some(true) } else { None } } not even It is possible to add data type to each variant of an enum. In the following example, Name and Usr_ID variants of the enum are of String and integer types respectively. The following example shows the use of match statement with an enum having a data type. // The `derive` attribute automatically creates the implementation // required to make this `enum` printable with `fmt::Debug`. #[derive(Debug)] enum GenderCategory { Name(String),Usr_ID(i32) } fn main() { let p1 = GenderCategory::Name(String::from("Mohtashim")); let p2 = GenderCategory::Usr_ID(100); println!("{:?}",p1); println!("{:?}",p2); match p1 { GenderCategory::Name(val)=> { println!("{}",val); } GenderCategory::Usr_ID(val)=> { println!("{}",val); } } } Name("Mohtashim") Usr_ID(100) Mohtashim A logical group of code is called a Module. Multiple modules are compiled into a unit called crate. Rust programs may contain a binary crate or a library crate. A binary crate is an executable project that has a main() method. A library crate is a group of components that can be reused in other projects. Unlike a binary crate, a library crate does not have an entry point (main() method). The Cargo tool is used to manage crates in Rust. For example, the network module contains networking related functions and the graphics module contains drawing-related functions. Modules are similar to namespaces in other programming languages. Third-party crates can be downloaded using cargo from crates.io. crate Is a compilation unit in Rust; Crate is compiled to binary or library. cargo The official Rust package management tool for crates. module Logically groups code within a crate. crates.io The official Rust package registry. //public module pub mod a_public_module { pub fn a_public_function() { //public function } fn a_private_function() { //private function } } //private module mod a_private_module { fn a_private_function() { } } Modules can be public or private. Components in a private module cannot be accessed by other modules. Modules in Rust are private by default. On the contrary, functions in a public module can be accessed by other modules. Modules should be prefixed with pub keyword to make it public. Functions within a public module must also be made public. The example defines a public module − movies. The module contains a function play() that accepts a parameter and prints its value. pub mod movies { pub fn play(name:String) { println!("Playing movie {}",name); } } fn main(){ movies::play("Herold and Kumar".to_string()); } Playing movie Herold and Kumar The use keyword helps to import a public module. use public_module_name::function_name; pub mod movies { pub fn play(name:String) { println!("Playing movie {}",name); } } use movies::play; fn main(){ play("Herold and Kumar ".to_string()); } Playing movie Herold and Kumar Modules can also be nested. The comedy module is nested within the english module, which is further nested in the movies module. The example given below defines a function play inside the movies/english/comedy module. pub mod movies { pub mod english { pub mod comedy { pub fn play(name:String) { println!("Playing comedy movie {}",name); } } } } use movies::english::comedy::play; // importing a public module fn main() { // short path syntax play("Herold and Kumar".to_string()); play("The Hangover".to_string()); //full path syntax movies::english::comedy::play("Airplane!".to_string()); } Playing comedy movie Herold and Kumar Playing comedy movie The Hangover Playing comedy movie Airplane! Let us create a library crate named movie_lib, which contains a module movies. To build the movie_lib library crate, we will use the tool cargo. Create a folder movie-app followed by a sub-folder movie-lib. After the folder and sub-folder are created, create an src folder and a Cargo.toml file in this directory. The source code should go in the src folder. Create the files lib.rs and movies.rs in the src folder. The Cargo.toml file will contain the metadata of the project like version number, author name, etc. The project directory structure will be as shown below − movie-app movie-lib/ -->Cargo.toml -->src/ lib.rs movies.rs [package] name = "movies_lib" version = "0.1.0" authors = ["Mohtashim"] Add the following module definition to this file. pub mod movies; The above line creates a public module − movies. This file will define all functions for the movies module. pub fn play(name:String){ println!("Playing movie {} :movies-app",name); } The above code defines a function play() that accepts a parameter and prints it to the console. Build app using the cargo build command to verify if the library crate is structured properly. Make sure you are at root of project − the movie-app folder. The following message will be displayed in the terminal if the build succeeds. D:\Rust\movie-lib> cargo build Compiling movies_lib v0.1.0 (file:///D:/Rust/movie-lib) Finished dev [unoptimized + debuginfo] target(s) in 0.67s Create another folder movie-lib-test in the movie-app folder followed by a Cargo.toml file and the src folder. This project should have main method as this is a binary crate, which will consume the library crate created previously. Create a main.rs file in the src folder. The folder structure will be as shown. movie-app movie-lib // already completed movie-lib-test/ -->Cargo.toml -->src/ main.rs [package] name = "test_for_movie_lib" version = "0.1.0" authors = ["Mohtashim"] [dependencies] movies_lib = { path = "../movie-lib" } NOTE − The path to the library folder is set as dependencies. The following diagram shows the contents of both the projects. extern crate movies_lib; use movies_lib::movies::play; fn main() { println!("inside main of test "); play("Tutorialspoint".to_string()) } The above code imports an external package called movies_lib. Check the Cargo.toml of current project to verify the crate name. We will use the cargo build and cargo run to build the binary project and execute it as shown below − Rust's standard collection library provides efficient implementations of the most common general-purpose programming data structures. This chapter discusses the implementation of the commonly used collections − Vector, HashMap and HashSet. A Vector is a resizable array. It stores values in contiguous memory blocks. The predefined structure Vec can be used to create vectors. Some important features of a Vector are − A Vector can grow or shrink at runtime. A Vector can grow or shrink at runtime. A Vector is a homogeneous collection. A Vector is a homogeneous collection. A Vector stores data as sequence of elements in a particular order. Every element in a Vector is assigned a unique index number. The index starts from 0 and goes up to n-1 where, n is the size of the collection. For example, in a collection of 5 elements, the first element will be at index 0 and the last element will be at index 4. A Vector stores data as sequence of elements in a particular order. Every element in a Vector is assigned a unique index number. The index starts from 0 and goes up to n-1 where, n is the size of the collection. For example, in a collection of 5 elements, the first element will be at index 0 and the last element will be at index 4. A Vector will only append values to (or near) the end. In other words, a Vector can be used to implement a stack. A Vector will only append values to (or near) the end. In other words, a Vector can be used to implement a stack. Memory for a Vector is allocated in the heap. Memory for a Vector is allocated in the heap. let mut instance_name = Vec::new(); The static method new() of the Vecstructure is used to create a vector instance. Alternatively, a vector can also be created using the vec! macro. The syntax is as given below − let vector_name = vec![val1,val2,val3] The following table lists some commonly used functions of the Vec structure. pub fn new()->Vect Constructs a new, empty Vec. The vector will not allocate until elements are pushed onto it. pub fn push(&mut self, value: T) Appends an element to the back of a collection. pub fn remove(&mut self, index: usize) -> T Removes and returns the element at position index within the vector, shifting all elements after it to the left. pub fn contains(&self, x: &T) -> bool Returns true if the slice contains an element with the given value. pub fn len(&self) -> usize Returns the number of elements in the vector, also referred to as its 'length'. To create a vector, we use the static method new− fn main() { let mut v = Vec::new(); v.push(20); v.push(30); v.push(40); println!("size of vector is :{}",v.len()); println!("{:?}",v); } The above example creates a Vector using the static method new() that is defined in structure Vec. The push(val) function appends the value passed as parameter to the collection. The len() function returns the length of the vector. size of vector is :3 [20, 30, 40] The following code creates a vector using the vec! macro. The data type of the vector is inferred the first value that is assigned to it. fn main() { let v = vec![1,2,3]; println!("{:?}",v); } [1, 2, 3] As mentioned earlier, a vector can only contain values of the same data type. The following snippet will throw a error[E0308]: mismatched types error. fn main() { let v = vec![1,2,3,"hello"]; println!("{:?}",v); } Appends an element to the end of a collection. fn main() { let mut v = Vec::new(); v.push(20); v.push(30); v.push(40); println!("{:?}",v); } [20, 30, 40] Removes and returns the element at position index within the vector, shifting all elements after it to the left. fn main() { let mut v = vec![10,20,30]; v.remove(1); println!("{:?}",v); } [10, 30] Returns true if the slice contains an element with the given value − fn main() { let v = vec![10,20,30]; if v.contains(&10) { println!("found 10"); } println!("{:?}",v); } found 10 [10, 20, 30] Returns the number of elements in the vector, also referred to as its 'length'. fn main() { let v = vec![1,2,3]; println!("size of vector is :{}",v.len()); } size of vector is :3 Individual elements in a vector can be accessed using their corresponding index numbers. The following example creates a vector ad prints the value of the first element. fn main() { let mut v = Vec::new(); v.push(20); v.push(30); println!("{:?}",v[0]); } Output: `20` Values in a vector can also be fetched using reference to the collection. fn main() { let mut v = Vec::new(); v.push(20); v.push(30); v.push(40); v.push(500); for i in &v { println!("{}",i); } println!("{:?}",v); } 20 30 40 500 [20, 30, 40, 500] A map is a collection of key-value pairs (called entries). No two entries in a map can have the same key. In short, a map is a lookup table. A HashMap stores the keys and values in a hash table. The entries are stored in an arbitrary order. The key is used to search for values in the HashMap. The HashMap structure is defined in the std::collections module. This module should be explicitly imported to access the HashMap structure. let mut instance_name = HashMap::new(); The static method new() of the HashMap structure is used to create a HashMap object. This method creates an empty HashMap. The commonly used functions of HashMap are discussed below − pub fn insert(&mut self, k: K, v: V) -> Option Inserts a key/value pair, if no key then None is returned. After update, old value is returned. pub fn len(&self) -> usize Returns the number of elements in the map. pub fn get<Q: ?Sized>(&lself, k: &Q) -> Option<&V> where K:Borrow Q:Hash+ Eq Returns a reference to the value corresponding to the key. pub fn iter(&self) -> Iter<K, V> An iterator visiting all key-value pairs in arbitrary order. The iterator element type is (&'a K, &'a V). pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool Returns true if the map contains a value for the specified key. pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)> Removes a key from the map, returning the stored key and value if the key was previously in the map. Inserts a key/value pair into the HashMap. use std::collections::HashMap; fn main(){ let mut stateCodes = HashMap::new(); stateCodes.insert("KL","Kerala"); stateCodes.insert("MH","Maharashtra"); println!("{:?}",stateCodes); } The above program creates a HashMap and initializes it with 2 key-value pairs. {"KL": "Kerala", "MH": "Maharashtra"} Returns the number of elements in the map use std::collections::HashMap; fn main() { let mut stateCodes = HashMap::new(); stateCodes.insert("KL","Kerala"); stateCodes.insert("MH","Maharashtra"); println!("size of map is {}",stateCodes.len()); } The above example creates a HashMap and prints the total number of elements in it. size of map is 2 Returns a reference to the value corresponding to the key. The following example retrieves the value for key KL in the HashMap. use std::collections::HashMap; fn main() { let mut stateCodes = HashMap::new(); stateCodes.insert("KL","Kerala"); stateCodes.insert("MH","Maharashtra"); println!("size of map is {}",stateCodes.len()); println!("{:?}",stateCodes); match stateCodes.get(&"KL") { Some(value)=> { println!("Value for key KL is {}",value); } None => { println!("nothing found"); } } } size of map is 2 {"KL": "Kerala", "MH": "Maharashtra"} Value for key KL is Kerala Returns an iterator containing reference to all key-value pairs in an arbitrary order. use std::collections::HashMap; fn main() { let mut stateCodes = HashMap::new(); stateCodes.insert("KL","Kerala"); stateCodes.insert("MH","Maharashtra"); for (key, val) in stateCodes.iter() { println!("key: {} val: {}", key, val); } } key: MH val: Maharashtra key: KL val: Kerala Returns true if the map contains a value for the specified key. use std::collections::HashMap; fn main() { let mut stateCodes = HashMap::new(); stateCodes.insert("KL","Kerala"); stateCodes.insert("MH","Maharashtra"); stateCodes.insert("GJ","Gujarat"); if stateCodes.contains_key(&"GJ") { println!("found key"); } } found key Removes a key from the map. use std::collections::HashMap; fn main() { let mut stateCodes = HashMap::new(); stateCodes.insert("KL","Kerala"); stateCodes.insert("MH","Maharashtra"); stateCodes.insert("GJ","Gujarat"); println!("length of the hashmap {}",stateCodes.len()); stateCodes.remove(&"GJ"); println!("length of the hashmap after remove() {}",stateCodes.len()); } length of the hashmap 3 length of the hashmap after remove() 2 HashSet is a set of unique values of type T. Adding and removing values is fast, and it is fast to ask whether a given value is in the set or not. The HashSet structure is defined in the std::collections module. This module should be explicitly imported to access the HashSet structure. let mut hash_set_name = HashSet::new(); The static method, new, of HashSet structure is used to create a HashSet. This method creates an empty HashSet. The following table lists some of the commonly used methods of the HashSet structure. pub fn insert(&mut self, value: T) -> bool Adds a value to the set. If the set did not have this value present, true is returned else false. pub fn len(&self) -> usize Returns the number of elements in the set. pub fn get<Q:?Sized>(&self, value: &Q) -> Option<&T> where T: Borrow,Q: Hash + Eq, Returns a reference to the value in the set, if any that is equal to the given value. pub fn iter(&self) -> Iter Returns an iterator visiting all elements in arbitrary order. The iterator element type is &'a T. pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool Returns true if the set contains a value. pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool Removes a value from the set. Returns true if the value was present in the set. Adds a value to the set. A HashSet does not add duplicate values to the collection. use std::collections::HashSet; fn main() { let mut names = HashSet::new(); names.insert("Mohtashim"); names.insert("Kannan"); names.insert("TutorialsPoint"); names.insert("Mohtashim");//duplicates not added println!("{:?}",names); } {"TutorialsPoint", "Kannan", "Mohtashim"} Returns the number of elements in the set. use std::collections::HashSet; fn main() { let mut names = HashSet::new(); names.insert("Mohtashim"); names.insert("Kannan"); names.insert("TutorialsPoint"); println!("size of the set is {}",names.len()); } size of the set is 3 Retruns an iterator visiting all elements in arbitrary order. use std::collections::HashSet; fn main() { let mut names = HashSet::new(); names.insert("Mohtashim"); names.insert("Kannan"); names.insert("TutorialsPoint"); names.insert("Mohtashim"); for name in names.iter() { println!("{}",name); } } TutorialsPoint Mohtashim Kannan Returns a reference to the value in the set, if any, which is equal to the given value. use std::collections::HashSet; fn main() { let mut names = HashSet::new(); names.insert("Mohtashim"); names.insert("Kannan"); names.insert("TutorialsPoint"); names.insert("Mohtashim"); match names.get(&"Mohtashim"){ Some(value)=>{ println!("found {}",value); } None =>{ println!("not found"); } } println!("{:?}",names); } found Mohtashim {"Kannan", "Mohtashim", "TutorialsPoint"} Returns true if the set contains a value. use std::collections::HashSet; fn main() { let mut names = HashSet::new(); names.insert("Mohtashim"); names.insert("Kannan"); names.insert("TutorialsPoint"); if names.contains(&"Kannan") { println!("found name"); } } found name Removes a value from the set. use std::collections::HashSet; fn main() { let mut names = HashSet::new(); names.insert("Mohtashim"); names.insert("Kannan"); names.insert("TutorialsPoint"); println!("length of the Hashset: {}",names.len()); names.remove(&"Kannan"); println!("length of the Hashset after remove() : {}",names.len()); } length of the Hashset: 3 length of the Hashset after remove() : 2 In Rust, errors can be classified into two major categories as shown in the table below. Recoverable Errors which can be handled UnRecoverable Errors which cannot be handled A recoverable error is an error that can be corrected. A program can retry the failed operation or specify an alternate course of action when it encounters a recoverable error. Recoverable errors do not cause a program to fail abruptly. An example of a recoverable error is File Not Found error. Unrecoverable errors cause a program to fail abruptly. A program cannot revert to its normal state if an unrecoverable error occurs. It cannot retry the failed operation or undo the error. An example of an unrecoverable error is trying to access a location beyond the end of an array. Unlike other programming languages, Rust does not have exceptions. It returns an enum Result<T, E> for recoverable errors, while it calls the panic macro if the program encounters an unrecoverable error. The panic macro causes the program to exit abruptly. panic! macro allows a program to terminate immediately and provide feedback to the caller of the program. It should be used when a program reaches an unrecoverable state. fn main() { panic!("Hello"); println!("End of main"); //unreachable statement } In the above example, the program will terminate immediately when it encounters the panic! macro. thread 'main' panicked at 'Hello', main.rs:3 fn main() { let a = [10,20,30]; a[10]; //invokes a panic since index 10 cannot be reached } Output is as shown below − warning: this expression will panic at run-time --> main.rs:4:4 | 4 | a[10]; | ^^^^^ index out of bounds: the len is 3 but the index is 10 $main thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 10', main.rs:4 note: Run with `RUST_BACKTRACE=1` for a backtrace. A program can invoke the panic! macro if business rules are violated as shown in the example below − fn main() { let no = 13; //try with odd and even if no%2 == 0 { println!("Thank you , number is even"); } else { panic!("NOT_AN_EVEN"); } println!("End of main"); } The above example returns an error if the value assigned to the variable is odd. thread 'main' panicked at 'NOT_AN_EVEN', main.rs:9 note: Run with `RUST_BACKTRACE=1` for a backtrace. Enum Result – <T,E> can be used to handle recoverable errors. It has two variants − OK and Err. T and E are generic type parameters. T represents the type of the value that will be returned in a success case within the OK variant, and E represents the type of the error that will be returned in a failure case within the Err variant. enum Result<T,E> { OK(T), Err(E) } Let us understand this with the help of an example − use std::fs::File; fn main() { let f = File::open("main.jpg"); //this file does not exist println!("{:?}",f); } The program returns OK(File) if the file already exists and Err(Error) if the file is not found. Err(Error { repr: Os { code: 2, message: "No such file or directory" } }) Let us now see how to handle the Err variant. The following example handles an error returned while opening file using the match statement use std::fs::File; fn main() { let f = File::open("main.jpg"); // main.jpg doesn't exist match f { Ok(f)=> { println!("file found {:?}",f); }, Err(e)=> { println!("file not found \n{:?}",e); //handled error } } println!("end of main"); } NOTE − The program prints end of the main event though file was not found. This means the program has handled error gracefully. file not found Os { code: 2, kind: NotFound, message: "The system cannot find the file specified." } end of main The is_even function returns an error if the number is not an even number. The main() function handles this error. fn main(){ let result = is_even(13); match result { Ok(d)=>{ println!("no is even {}",d); }, Err(msg)=>{ println!("Error msg is {}",msg); } } println!("end of main"); } fn is_even(no:i32)->Result<bool,String> { if no%2==0 { return Ok(true); } else { return Err("NOT_AN_EVEN".to_string()); } } NOTE − Since the main function handles error gracefully, the end of main statement is printed. Error msg is NOT_AN_EVEN end of main The standard library contains a couple of helper methods that both enums − Result<T,E> and Option<T> implement. You can use them to simplify error cases where you really do not expect things to fail. In case of success from a method, the "unwrap" function is used to extract the actual result. unwrap(self): T Expects self to be Ok/Some and returns the value contained within. If it is Err or None instead, it raises a panic with the contents of the error displayed. expect(self, msg: &str): T Behaves like unwrap, except that it outputs a custom message before panicking in addition to the contents of the error. The unwrap() function returns the actual result an operation succeeds. It returns a panic with a default error message if an operation fails. This function is a shorthand for match statement. This is shown in the example below − fn main(){ let result = is_even(10).unwrap(); println!("result is {}",result); println!("end of main"); } fn is_even(no:i32)->Result<bool,String> { if no%2==0 { return Ok(true); } else { return Err("NOT_AN_EVEN".to_string()); } } result is true end of main Modify the above code to pass an odd number to the is_even() function. The unwrap() function will panic and return a default error message as shown below thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: "NOT_AN_EVEN"', libcore\result.rs:945:5 note: Run with `RUST_BACKTRACE=1` for a backtrace The program can return a custom error message in case of a panic. This is shown in the following example − use std::fs::File; fn main(){ let f = File::open("pqr.txt").expect("File not able to open"); //file does not exist println!("end of main"); } The function expect() is similar to unwrap(). The only difference is that a custom error message can be displayed using expect. thread 'main' panicked at 'File not able to open: Error { repr: Os { code: 2, message: "No such file or directory" } }', src/libcore/result.rs:860 note: Run with `RUST_BACKTRACE=1` for a backtrace. Generics are a facility to write code for multiple contexts with different types. In Rust, generics refer to the parameterization of data types and traits. Generics allows to write more concise and clean code by reducing code duplication and providing type-safety. The concept of Generics can be applied to methods, functions, structures, enumerations, collections and traits. The <T> syntax known as the type parameter, is used to declare a generic construct. T represents any data-type. The following example declares a vector that can store only integers. fn main(){ let mut vector_integer: Vec<i32> = vec![20,30]; vector_integer.push(40); println!("{:?}",vector_integer); } [20, 30, 40] Consider the following snippet − fn main() { let mut vector_integer: Vec<i32> = vec![20,30]; vector_integer.push(40); vector_integer.push("hello"); //error[E0308]: mismatched types println!("{:?}",vector_integer); } The above example shows that a vector of integer type can only store integer values. So, if we try to push a string value into the collection, the compiler will return an error. Generics make collections more type safe. The type parameter represents a type, which the compiler will fill in later. struct Data<T> { value:T, } fn main() { //generic type of i32 let t:Data<i32> = Data{value:350}; println!("value is :{} ",t.value); //generic type of String let t2:Data<String> = Data{value:"Tom".to_string()}; println!("value is :{} ",t2.value); } The above example declares a generic structure named Data. The <T> type indicates some data type. The main() function creates two instances − an integer instance and a string instance, of the structure. value is :350 value is :Tom Traits can be used to implement a standard set of behaviors (methods) across multiple structures. Traits are like interfaces in Object-oriented Programming. The syntax of trait is as shown below − trait some_trait { //abstract or method which is empty fn method1(&self); // this is already implemented , this is free fn method2(&self){ //some contents of method2 } } Traits can contain concrete methods (methods with body) or abstract methods (methods without a body). Use a concrete method if the method definition will be shared by all structures implementing the Trait. However, a structure can choose to override a function defined by the trait. Use abstract methods if the method definition varies for the implementing structures. impl some_trait for structure_name { // implement method1() there.. fn method1(&self ){ } } The following examples defines a trait Printable with a method print(), which is implemented by the structure book. fn main(){ //create an instance of the structure let b1 = Book { id:1001, name:"Rust in Action" }; b1.print(); } //declare a structure struct Book { name:&'static str, id:u32 } //declare a trait trait Printable { fn print(&self); } //implement the trait impl Printable for Book { fn print(&self){ println!("Printing book with id:{} and name {}",self.id,self.name) } } Printing book with id:1001 and name Rust in Action The example defines a generic function that displays a parameter passed to it. The parameter can be of any type. The parameter’s type should implement the Display trait so that its value can be printed by the println! macro. use std::fmt::Display; fn main(){ print_pro(10 as u8); print_pro(20 as u16); print_pro("Hello TutorialsPoint"); } fn print_pro<T:Display>(t:T){ println!("Inside print_pro generic function:"); println!("{}",t); } Inside print_pro generic function: 10 Inside print_pro generic function: 20 Inside print_pro generic function: Hello TutorialsPoint This chapter discusses how to accept values from the standard input (keyboard) and display values to the standard output (console). In this chapter, we will also discuss passing command line arguments. Rust’s standard library features for input and output are organized around two traits − Read Write Read Types that implement Read have methods for byte-oriented input. They’re called readers Write Types that implement Write support both byte-oriented and UTF-8 text output. They’re called writers. Readers are components that your program can read bytes from. Examples include reading input from the keyboard, files, etc. The read_line() method of this trait can be used to read data, one line at a time, from a file or standard input stream. read_line(&mut line)->Result Reads a line of text and appends it to line, which is a String. The return value is an io::Result, the number of bytes read. Rust programs might have to accept values from the user at runtime. The following example reads values from the standard input (Keyboard) and prints it to the console. fn main(){ let mut line = String::new(); println!("Enter your name :"); let b1 = std::io::stdin().read_line(&mut line).unwrap(); println!("Hello , {}", line); println!("no of bytes read , {}", b1); } The stdin() function returns a handle to the standard input stream of the current process, to which the read_line function can be applied. This function tries to read all the characters present in the input buffer when it encounters an end-of-line character. Enter your name : Mohtashim Hello , Mohtashim no of bytes read , 10 Writers are components that your program can write bytes to. Examples include printing values to the console, writing to files, etc. The write() method of this trait can be used to write data to a file or standard output stream. write(&buf)->Result Writes some of the bytes in the slice buf to the underlying stream. It returns an io::Result, the number of bytes written. The print! or println! macros can be used to display text on the console. However, you can also use the write() standard library function to display some text to the standard output. Let us consider an example to understand this. use std::io::Write; fn main() { let b1 = std::io::stdout().write("Tutorials ".as_bytes()).unwrap(); let b2 = std::io::stdout().write(String::from("Point").as_bytes()).unwrap(); std::io::stdout().write(format!("\nbytes written {}",(b1+b2)).as_bytes()).unwrap(); } Tutorials Point bytes written 15 The stdout() standard library function returns a handle to the standard output stream of the current process, to which the write function can be applied. The write() method returns an enum, Result. The unwrap() is a helper method to extract the actual result from the enumeration. The unwrap method will send panic if an error occurs. NOTE − File IO is discussed in the next chapter. CommandLine arguments are passed to a program before executing it. They are like parameters passed to functions. CommandLine parameters can be used to pass values to the main() function. The std::env::args() returns the commandline arguments. The following example passes values as commandLine arguments to the main() function. The program is created in a file name main.rs. //main.rs fn main(){ let cmd_line = std::env::args(); println!("No of elements in arguments is :{}",cmd_line.len()); //print total number of values passed for arg in cmd_line { println!("[{}]",arg); //print all values passed as commandline arguments } } The program will generate a file main.exe once compiled. Multiple command line parameters should be separated by space. Execute main.exe from the terminal as main.exe hello tutorialspoint. NOTE − hello and tutorialspoint are commandline arguments. No of elements in arguments is :3 [main.exe] [hello] [tutorialspoint] The output shows 3 arguments as the main.exe is the first argument. The following program calculates the sum of values passed as commandline arguments. A list integer values separated by space is passed to program. fn main(){ let cmd_line = std::env::args(); println!("No of elements in arguments is :{}",cmd_line.len()); // total number of elements passed let mut sum = 0; let mut has_read_first_arg = false; //iterate through all the arguments and calculate their sum for arg in cmd_line { if has_read_first_arg { //skip the first argument since it is the exe file name sum += arg.parse::<i32>().unwrap(); } has_read_first_arg = true; // set the flag to true to calculate sum for the subsequent arguments. } println!("sum is {}",sum); } On executing the program as main.exe 1 2 3 4, the output will be − No of elements in arguments is :5 sum is 10 In addition to reading and writing to console, Rust allows reading and writing to files. The File struct represents a file. It allows a program to perform read-write operations on a file. All methods in the File struct return a variant of the io::Result enumeration. The commonly used methods of the File struct are listed in the table below − Let us see an example to understand how to write a file. The following program creates a file 'data.txt'. The create() method is used to create a file. The method returns a file handle if the file is created successfully. The last line write_all function will write bytes in newly created file. If any of the operations fail, the expect() function returns an error message. use std::io::Write; fn main() { let mut file = std::fs::File::create("data.txt").expect("create failed"); file.write_all("Hello World".as_bytes()).expect("write failed"); file.write_all("\nTutorialsPoint".as_bytes()).expect("write failed"); println!("data written to file" ); } data written to file The following program reads the contents in a file data.txt and prints it to the console. The "open" function is used to open an existing file. An absolute or relative path to the file is passed to the open() function as a parameter. The open() function throws an exception if the file does not exist, or if it is not accessible for whatever reason. If it succeeds, a file handle to such file is assigned to the "file" variable. The "read_to_string" function of the "file" handle is used to read contents of that file into a string variable. use std::io::Read; fn main(){ let mut file = std::fs::File::open("data.txt").unwrap(); let mut contents = String::new(); file.read_to_string(&mut contents).unwrap(); print!("{}", contents); } Hello World TutorialsPoint The following example uses the remove_file() function to delete a file. The expect() function returns a custom message in case an error occurs. use std::fs; fn main() { fs::remove_file("data.txt").expect("could not remove file"); println!("file is removed"); } file is removed The append() function writes data to the end of the file. This is shown in the example given below − use std::fs::OpenOptions; use std::io::Write; fn main() { let mut file = OpenOptions::new().append(true).open("data.txt").expect( "cannot open file"); file.write_all("Hello World".as_bytes()).expect("write failed"); file.write_all("\nTutorialsPoint".as_bytes()).expect("write failed"); println!("file append success"); } file append success The following example copies the contents in a file to a new file. use std::io::Read; use std::io::Write; fn main() { let mut command_line: std::env::Args = std::env::args(); command_line.next().unwrap(); // skip the executable file name // accept the source file let source = command_line.next().unwrap(); // accept the destination file let destination = command_line.next().unwrap(); let mut file_in = std::fs::File::open(source).unwrap(); let mut file_out = std::fs::File::create(destination).unwrap(); let mut buffer = [0u8; 4096]; loop { let nbytes = file_in.read(&mut buffer).unwrap(); file_out.write(&buffer[..nbytes]).unwrap(); if nbytes < buffer.len() { break; } } } Execute the above program as main.exe data.txt datacopy.txt. Two command line arguments are passed while executing the file − the path to the source file the destination file Cargo is the package manager for RUST. This acts like a tool and manages Rust projects. Some commonly used cargo commands are listed in the table below − cargo build Compiles the current project. cargo check Analyzes the current project and report errors, but don't build object files. cargo run Builds and executes src/main.rs. cargo clean Removes the target directory. cargo update Updates dependencies listed in Cargo.lock. cargo new Creates a new cargo project. Cargo helps to download third party libraries. Therefore, it acts like a package manager. You can also build your own libraries. Cargo is installed by default when you install Rust. To create a new cargo project, we can use the commands given below. cargo new project_name --bin cargo new project_name --lib To check the current version of cargo, execute the following command − cargo --version The game generates a random number and prompts the user to guess the number. Open the terminal and type the following command cargo new guess-game-app --bin. This will create the following folder structure. guess-game-app/ -->Cargo.toml -->src/ main.rs The cargo new command is used to create a crate. The --bin flag indicates that the crate being created is a binary crate. Public crates are stored in a central repository called crates.io https://crates.io/. This example needs to generate a random number. Since the internal standard library does not provide random number generation logic, we need to look at external libraries or crates. Let us use rand crate which is available at crates.io website crates.io The https://crates.io/crates/rand is a rust library for random number generation. Rand provides utilities to generate random numbers, to convert them to useful types and distributions, and some randomness-related algorithms. The following diagram shows crate.io website and search result for rand crate. Copy the version of rand crate to the Cargo.toml file rand = "0.5.5". [package] name = "guess-game-app" version = "0.1.0" authors = ["Mohtashim"] [dependencies] rand = "0.5.5" Navigate to the project folder. Execute the command cargo build on the terminal window − Updating registry `https://github.com/rust-lang/crates.io-index` Downloading rand v0.5.5 Downloading rand_core v0.2.2 Downloading winapi v0.3.6 Downloading rand_core v0.3.0 Compiling winapi v0.3.6 Compiling rand_core v0.3.0 Compiling rand_core v0.2.2 Compiling rand v0.5.5 Compiling guess-game-app v0.1.0 (file:///E:/RustWorks/RustRepo/Code_Snippets/cargo-projects/guess-game-app) Finished dev [unoptimized + debuginfo] target(s) in 1m 07s The rand crate and all transitive dependencies (inner dependencies of rand) will be automatically downloaded. Let us now see how the business logic works for the number guessing game − Game initially generates a random number. Game initially generates a random number. A user is asked to enter input and guess the number. A user is asked to enter input and guess the number. If number is less than the generated number, a message “Too low” is printed. If number is less than the generated number, a message “Too low” is printed. If number is greater than the generated number, a message “Too high” is printed. If number is greater than the generated number, a message “Too high” is printed. If the user enters the number generated by the program, the game exits. If the user enters the number generated by the program, the game exits. Add the business logic to main.rs file. use std::io; extern crate rand; //importing external crate use rand::random; fn get_guess() -> u8 { loop { println!("Input guess") ; let mut guess = String::new(); io::stdin().read_line(&mut guess) .expect("could not read from stdin"); match guess.trim().parse::<u8>(){ //remember to trim input to avoid enter spaces Ok(v) => return v, Err(e) => println!("could not understand input {}",e) } } } fn handle_guess(guess:u8,correct:u8)-> bool { if guess < correct { println!("Too low"); false } else if guess> correct { println!("Too high"); false } else { println!("You go it .."); true } } fn main() { println!("Welcome to no guessing game"); let correct:u8 = random(); println!("correct value is {}",correct); loop { let guess = get_guess(); if handle_guess(guess,correct){ break; } } } Execute the command cargo run on the terminal. Make sure that the terminal points to the Project directory. Welcome to no guessing game correct value is 97 Input guess 20 Too low Input guess 100 Too high Input guess 97 You got it .. In this chapter, we will learn how iterators and closures work in RUST. An iterator helps to iterate over a collection of values such as arrays, vectors, maps, etc. Iterators implement the Iterator trait that is defined in the Rust standard library. The iter() method returns an iterator object of the collection. Values in an iterator object are called items. The next() method of the iterator can be used to traverse through the items. The next() method returns a value None when it reaches the end of the collection. The following example uses an iterator to read values from an array. fn main() { //declare an array let a = [10,20,30]; let mut iter = a.iter(); // fetch an iterator object for the array println!("{:?}",iter); //fetch individual values from the iterator object println!("{:?}",iter.next()); println!("{:?}",iter.next()); println!("{:?}",iter.next()); println!("{:?}",iter.next()); } Iter([10, 20, 30]) Some(10) Some(20) Some(30) None If a collection like array or Vector implements Iterator trait then it can be traversed using the for...in syntax as shown below- fn main() { let a = [10,20,30]; let iter = a.iter(); for data in iter{ print!("{}\t",data); } } 10 20 30 The following 3 methods return an iterator object from a collection, where T represents the elements in a collection. iter() gives an iterator over &T(reference to T) into_iter() gives an iterator over T iter_mut() gives an iterator over &mut T The iter() function uses the concept of borrowing. It returns a reference to each element of the collection, leaving the collection untouched and available for reuse after the loop. fn main() { let names = vec!["Kannan", "Mohtashim", "Kiran"]; for name in names.iter() { match name { &"Mohtashim" => println!("There is a rustacean among us!"), _ => println!("Hello {}", name), } } println!("{:?}",names); // reusing the collection after iteration } Hello Kannan There is a rustacean among us! Hello Kiran ["Kannan", "Mohtashim", "Kiran"] This function uses the concept of ownership. It moves values in the collection into an iter object, i.e., the collection is consumed and it is no longer available for reuse. fn main(){ let names = vec!["Kannan", "Mohtashim", "Kiran"]; for name in names.into_iter() { match name { "Mohtashim" => println!("There is a rustacean among us!"), _ => println!("Hello {}", name), } } // cannot reuse the collection after iteration //println!("{:?}",names); //Error:Cannot access after ownership move } Hello Kannan There is a rustacean among us! Hello Kiran This function is like the iter() function. However, this function can modify elements within the collection. fn main() { let mut names = vec!["Kannan", "Mohtashim", "Kiran"]; for name in names.iter_mut() { match name { &mut "Mohtashim" => println!("There is a rustacean among us!"), _ => println!("Hello {}", name), } } println!("{:?}",names); //// reusing the collection after iteration } Hello Kannan There is a rustacean among us! Hello Kiran ["Kannan", "Mohtashim", "Kiran"] Closure refers to a function within another function. These are anonymous functions – functions without a name. Closure can be used to assign a function to a variable. This allows a program to pass a function as a parameter to other functions. Closure is also known as an inline function. Variables in the outer function can be accessed by inline functions. A closure definition may optionally have parameters. Parameters are enclosed within two vertical bars. let closure_function = |parameter| { //logic } The syntax invoking a Closure implements Fn traits. So, it can be invoked with () syntax. closure_function(parameter); //invoking The following example defines a closure is_even within the function main(). The closure returns true if a number is even and returns false if the number is odd. fn main(){ let is_even = |x| { x%2==0 }; let no = 13; println!("{} is even ? {}",no,is_even(no)); } 13 is even ? false fn main(){ let val = 10; // declared outside let closure2 = |x| { x + val //inner function accessing outer fn variable }; println!("{}",closure2(2)); } The main() function declares a variable val and a closure. The closure accesses the variable declared in the outer function main(). 12 Rust allocates everything on the stack by default. You can store things on the heap by wrapping them in smart pointers like Box. Types like Vec and String implicitly help heap allocation. Smart pointers implement traits listed in the table below. These traits of the smart pointers differentiate them from an ordinary struct − std::ops::Deref Used for immutable dereferencing operations, like *v. std::ops::Drop Used to run some code when a value goes out of scope. This is sometimes called a destructor In this chapter, we will learn about the Box smart pointer. We will also learn how to create a custom smart pointer like Box. The Box smart pointer also called a box allows you to store data on the heap rather than the stack. The stack contains the pointer to the heap data. A Box does not have performance overhead, other than storing their data on the heap. Let us see how to use a box to store an i32 value on the heap. fn main() { let var_i32 = 5; //stack let b = Box::new(var_i32); //heap println!("b = {}", b); } b = 5 In order to access a value pointed by a variable, use dereferencing. The * is used as a dereference operator. Let us see how to use dereference with Box. fn main() { let x = 5; //value type variable let y = Box::new(x); //y points to a new value 5 in the heap println!("{}",5==x); println!("{}",5==*y); //dereferencing y } The variable x is a value-type with the value 5. So, the expression 5==x will return true. Variable y points to the heap. To access the value in heap, we need to dereference using *y. *y returns value 5. So, the expression 5==*y returns true. true true The Deref trait, provided by the standard library, requires us to implement one method named deref, that borrows self and returns a reference to the inner data. The following example creates a structure MyBox, which is a generic type. It implements the trait Deref. This trait helps us access heap values wrapped by y using *y. use std::ops::Deref; struct MyBox<T>(T); impl<T> MyBox<T> { // Generic structure with static method new fn new(x:T)-> MyBox<T> { MyBox(x) } } impl<T> Deref for MyBox<T> { type Target = T; fn deref(&self) -> &T { &self.0 //returns data } } fn main() { let x = 5; let y = MyBox::new(x); // calling static method println!("5==x is {}",5==x); println!("5==*y is {}",5==*y); // dereferencing y println!("x==*y is {}",x==*y); //dereferencing y } 5==x is true 5==*y is true x==*y is true The Drop trait contains the drop() method. This method is called when a structure that implemented this trait goes out of scope. In some languages, the programmer must call code to free memory or resources every time they finish using an instance of a smart pointer. In Rust, you can achieve automatic memory deallocation using Drop trait. use std::ops::Deref; struct MyBox<T>(T); impl<T> MyBox<T> { fn new(x:T)->MyBox<T>{ MyBox(x) } } impl<T> Deref for MyBox<T> { type Target = T; fn deref(&self) -< &T { &self.0 } } impl<T> Drop for MyBox<T>{ fn drop(&mut self){ println!("dropping MyBox object from memory "); } } fn main() { let x = 50; MyBox::new(x); MyBox::new("Hello"); } In the above example, the drop method will be called twice as we are creating two objects in the heap. dropping MyBox object from memory dropping MyBox object from memory In Concurrent programming, different parts of a program execute independently. On the other hand, in parallel programming, different parts of a program execute at the same time. Both the models are equally important as more computers take advantage of their multiple processors. We can use threads to run codes simultaneously. In current operating systems, an executed program’s code is run in a process, and the operating system manages multiple processes at once. Within your program, you can also have independent parts that run simultaneously. The features that run these independent parts are called threads. The thread::spawn function is used to create a new thread. The spawn function takes a closure as parameter. The closure defines code that should be executed by the thread. The following example prints some text from a main thread and other text from a new thread. //import the necessary modules use std::thread; use std::time::Duration; fn main() { //create a new thread thread::spawn(|| { for i in 1..10 { println!("hi number {} from the spawned thread!", i); thread::sleep(Duration::from_millis(1)); } }); //code executed by the main thread for i in 1..5 { println!("hi number {} from the main thread!", i); thread::sleep(Duration::from_millis(1)); } } hi number 1 from the main thread! hi number 1 from the spawned thread! hi number 2 from the main thread! hi number 2 from the spawned thread! hi number 3 from the main thread! hi number 3 from the spawned thread! hi number 4 from the spawned thread! hi number 4 from the main thread! The main thread prints values from 1 to 4. NOTE − The new thread will be stopped when the main thread ends. The output from this program might be a little different every time. The thread::sleep function forces a thread to stop its execution for a short duration, allowing a different thread to run. The threads will probably take turns, but that is not guaranteed – it depends on how the operating system schedules the threads. In this run, the main thread is printed first, even though the print statement from the spawned thread appears first in the code. Moreover, even if the spawned thread is programmed to print values till 9, it only got to 5 before the main thread shut down. A spawned thread may not get a chance to run or run completely. This is because the main thread completes quickly. The function spawn<F, T>(f: F) -> JoinHandlelt;T> returns a JoinHandle. The join() method on JoinHandle waits for the associated thread to finish. use std::thread; use std::time::Duration; fn main() { let handle = thread::spawn(|| { for i in 1..10 { println!("hi number {} from the spawned thread!", i); thread::sleep(Duration::from_millis(1)); } }); for i in 1..5 { println!("hi number {} from the main thread!", i); thread::sleep(Duration::from_millis(1)); } handle.join().unwrap(); } hi number 1 from the main thread! hi number 1 from the spawned thread! hi number 2 from the spawned thread! hi number 2 from the main thread! hi number 3 from the spawned thread! hi number 3 from the main thread! hi number 4 from the main thread! hi number 4 from the spawned thread! hi number 5 from the spawned thread! hi number 6 from the spawned thread! hi number 7 from the spawned thread! hi number 8 from the spawned thread! hi number 9 from the spawned thread! The main thread and spawned thread continue switching. NOTE − The main thread waits for spawned thread to complete because of the call to the join() method. 45 Lectures 4.5 hours Stone River ELearning 10 Lectures 33 mins Ken Burke Print Add Notes Bookmark this page
[ { "code": null, "e": 2204, "s": 2087, "text": "Rust is a systems level programming language, developed by Graydon Hoare. Mozilla Labs later acquired the programme." }, { "code": null, "e": 2442, "s": 2204, "text": "Application programming languages like Java/C# are used to build software, which provide services to the user directly. They help us build business applications like spreadsheets, word processors, web applications or mobile applications." }, { "code": null, "e": 2685, "s": 2442, "text": "Systems programming languages like C/C++ are used to build software and software platforms. They can be used to build operating systems, game engines, compilers, etc. These programming languages require a great degree of hardware interaction." }, { "code": null, "e": 2757, "s": 2685, "text": "Systems and application programming languages face two major problems −" }, { "code": null, "e": 2795, "s": 2757, "text": "It is difficult to write secure code." }, { "code": null, "e": 2841, "s": 2795, "text": "It is difficult to write multi-threaded code." }, { "code": null, "e": 2871, "s": 2841, "text": "Rust focuses on three goals −" }, { "code": null, "e": 2878, "s": 2871, "text": "Safety" }, { "code": null, "e": 2884, "s": 2878, "text": "Speed" }, { "code": null, "e": 2896, "s": 2884, "text": "Concurrency" }, { "code": null, "e": 3070, "s": 2896, "text": "The language was designed for developing highly reliable and fast software in a simple way. Rust can be used to write high-level programs down to hardware-specific programs." }, { "code": null, "e": 3188, "s": 3070, "text": "Rust programming language does not have a Garbage Collector (GC) by design. This improves the performance at runtime." }, { "code": null, "e": 3299, "s": 3188, "text": "Software built using Rust is safe from memory issues like dangling pointers, buffer overruns and memory leaks." }, { "code": null, "e": 3380, "s": 3299, "text": "Rust’s ownership and memory safety rules provide concurrency without data races." }, { "code": null, "e": 3607, "s": 3380, "text": "Web Assembly helps to execute high computation intensive algorithms in the browser, on embedded devices, or anywhere else. It runs at the speed of native code. Rust can be compiled to Web Assembly for fast, reliable execution." }, { "code": null, "e": 3727, "s": 3607, "text": "Installation of Rust is made easy through rustup, a console-based tool for managing Rust versions and associated tools." }, { "code": null, "e": 3772, "s": 3727, "text": "Let us learn how to install RUST on Windows." }, { "code": null, "e": 3937, "s": 3772, "text": "Installation of Visual Studio 2013 or higher with C++ tools is mandatory to run the Rust program on windows. First, download Visual Studio from here VS 2013 Express" }, { "code": null, "e": 4102, "s": 3937, "text": "Installation of Visual Studio 2013 or higher with C++ tools is mandatory to run the Rust program on windows. First, download Visual Studio from here VS 2013 Express" }, { "code": null, "e": 4207, "s": 4102, "text": "Download and install rustup tool for windows. rustup-init.exe is available for download here − Rust Lang" }, { "code": null, "e": 4312, "s": 4207, "text": "Download and install rustup tool for windows. rustup-init.exe is available for download here − Rust Lang" }, { "code": null, "e": 4396, "s": 4312, "text": "Double-click rustup-init.exe file. Upon clicking, the following screen will appear." }, { "code": null, "e": 4480, "s": 4396, "text": "Double-click rustup-init.exe file. Upon clicking, the following screen will appear." }, { "code": null, "e": 4580, "s": 4480, "text": "Press enter for default installation. Once installation is completed, the following screen appears." }, { "code": null, "e": 4680, "s": 4580, "text": "Press enter for default installation. Once installation is completed, the following screen appears." }, { "code": null, "e": 4799, "s": 4680, "text": "From the installation screen, it is clear that Rust related files are stored in the folder −\nC:\\Users\\{PC}\\.cargo\\bin\n" }, { "code": null, "e": 4892, "s": 4799, "text": "From the installation screen, it is clear that Rust related files are stored in the folder −" }, { "code": null, "e": 4917, "s": 4892, "text": "C:\\Users\\{PC}\\.cargo\\bin" }, { "code": null, "e": 4950, "s": 4917, "text": "The contents of the folder are −" }, { "code": null, "e": 5088, "s": 4950, "text": "cargo-fmt.exe\ncargo.exe\nrls.exe\nrust-gdb.exe\nrust-lldb.exe\nrustc.exe // this is the compiler for rust\nrustdoc.exe\nrustfmt.exe\nrustup.exe\n" }, { "code": null, "e": 5192, "s": 5088, "text": "Cargo is the package manager for Rust. To verify if cargo is installed, execute the following command −" }, { "code": null, "e": 5296, "s": 5192, "text": "Cargo is the package manager for Rust. To verify if cargo is installed, execute the following command −" }, { "code": null, "e": 5357, "s": 5296, "text": "C:\\Users\\Admin>cargo -V\ncargo 1.29.0 (524a578d7 2018-08-05)\n" }, { "code": null, "e": 5453, "s": 5357, "text": "The compiler for Rust is rustc. To verify the compiler version, execute the following command −" }, { "code": null, "e": 5549, "s": 5453, "text": "The compiler for Rust is rustc. To verify the compiler version, execute the following command −" }, { "code": null, "e": 5610, "s": 5549, "text": "C:\\Users\\Admin>cargo -V\ncargo 1.29.0 (524a578d7 2018-08-05)\n" }, { "code": null, "e": 5696, "s": 5610, "text": "To install rustup on Linux or macOS, open a terminal and enter the following command." }, { "code": null, "e": 5735, "s": 5696, "text": "$ curl https://sh.rustup.rs -sSf | sh\n" }, { "code": null, "e": 5973, "s": 5735, "text": "The command downloads a script and starts the installation of the rustup tool, which installs the latest stable version of Rust. You might be prompted for your password. If the installation is successful, the following line will appear −" }, { "code": null, "e": 6004, "s": 5973, "text": "Rust is installed now. Great!\n" }, { "code": null, "e": 6246, "s": 6004, "text": "The installation script automatically adds Rust to your system PATH after your next login. To start using Rust right away instead of restarting your terminal, run the following command in your shell to add Rust to your system PATH manually −" }, { "code": null, "e": 6273, "s": 6246, "text": "$ source $HOME/.cargo/env\n" }, { "code": null, "e": 6345, "s": 6273, "text": "Alternatively, you can add the following line to your ~/.bash_profile −" }, { "code": null, "e": 6385, "s": 6345, "text": "$ export PATH=\"$HOME/.cargo/bin:$PATH\"\n" }, { "code": null, "e": 6585, "s": 6385, "text": "NOTE − When you try to compile a Rust program and get errors indicating that a linker could not execute, that means a linker is not installed on your system and you will need to install one manually." }, { "code": null, "e": 6807, "s": 6585, "text": "A Read-Evaluate-Print Loop (REPL) is an easy to use interactive shell to compile and execute computer programs. If you want to compile and execute Rust programs online within the browser, use Tutorialspoint Coding Ground." }, { "code": null, "e": 6893, "s": 6807, "text": "This chapter explains the basic syntax of Rust language through a HelloWorld example." }, { "code": null, "e": 6964, "s": 6893, "text": "Create a HelloWorld-App folder and navigate to that folder on terminal" }, { "code": null, "e": 7035, "s": 6964, "text": "Create a HelloWorld-App folder and navigate to that folder on terminal" }, { "code": null, "e": 7136, "s": 7035, "text": "C:\\Users\\Admin>mkdir HelloWorld-App\nC:\\Users\\Admin>cd HelloWorld-App\nC:\\Users\\Admin\\HelloWorld-App>\n" }, { "code": null, "e": 7191, "s": 7136, "text": "To create a Rust file, execute the following command −" }, { "code": null, "e": 7246, "s": 7191, "text": "To create a Rust file, execute the following command −" }, { "code": null, "e": 7294, "s": 7246, "text": "C:\\Users\\Admin\\HelloWorld-App>notepad Hello.rs\n" }, { "code": null, "e": 7450, "s": 7294, "text": "Rust program files have an extension .rs. The above command creates an empty file Hello.rs and opens it in NOTEpad. Add the code given below to this file −" }, { "code": null, "e": 7516, "s": 7450, "text": "fn\nmain(){\n println!(\"Rust says Hello to TutorialsPoint !!\");\n}" }, { "code": null, "e": 7852, "s": 7516, "text": "The above program defines a function main fn main(). The fn keyword is used to define a function. The main() is a predefined function that acts as an entry point to the program. println! is a predefined macro in Rust. It is used to print a string (here Hello) to the console. Macro calls are always marked with an exclamation mark – !." }, { "code": null, "e": 7891, "s": 7852, "text": "Compile the Hello.rs file using rustc." }, { "code": null, "e": 7930, "s": 7891, "text": "Compile the Hello.rs file using rustc." }, { "code": null, "e": 7976, "s": 7930, "text": "C:\\Users\\Admin\\HelloWorld-App>rustc Hello.rs\n" }, { "code": null, "e": 8141, "s": 7976, "text": "Upon successful compilation of the program, an executable file (file_name.exe) is generated. To verify if the .exe file is generated, execute the following command." }, { "code": null, "e": 8233, "s": 8141, "text": "C:\\Users\\Admin\\HelloWorld-App>dir\n//lists the files in folder\nHello.exe\nHello.pdb\nHello.rs\n" }, { "code": null, "e": 8283, "s": 8233, "text": "Execute the Hello.exe file and verify the output." }, { "code": null, "e": 8716, "s": 8283, "text": "Rust provides a powerful macro system that allows meta-programming. As you have seen in the previous example, macros look like functions, except that their name ends with a bang(!), but instead of generating a function call, macros are expanded into source code that gets compiled with the rest of the program. Therefore, they provide more runtime features to a program unlike functions. Macros are an extended version of functions." }, { "code": null, "e": 8860, "s": 8716, "text": "println!(); // prints just a newline\nprintln!(\"hello \");//prints hello\nprintln!(\"format {} arguments\", \"some\"); //prints format some arguments\n" }, { "code": null, "e": 9087, "s": 8860, "text": "Comments are a way to improve the readability of a program. Comments can be used to include additional information about a program like author of the code, hints about a function/ construct, etc. The compiler ignores comments." }, { "code": null, "e": 9135, "s": 9087, "text": "Rust supports the following types of comments −" }, { "code": null, "e": 9233, "s": 9135, "text": "Single-line comments ( // ) − Any text between a // and the end of a line is treated as a comment" }, { "code": null, "e": 9331, "s": 9233, "text": "Single-line comments ( // ) − Any text between a // and the end of a line is treated as a comment" }, { "code": null, "e": 9401, "s": 9331, "text": "Multi-line comments (/* */) − These comments may span multiple lines." }, { "code": null, "e": 9471, "s": 9401, "text": "Multi-line comments (/* */) − These comments may span multiple lines." }, { "code": null, "e": 9541, "s": 9471, "text": "//this is single line comment\n\n/* This is a\n Multi-line comment\n*/\n" }, { "code": null, "e": 9697, "s": 9541, "text": "Rust programs can be executed online through Tutorialspoint Coding Ground. Write the HelloWorld program in the Editor tab and click Execute to view result." }, { "code": null, "e": 10027, "s": 9697, "text": "The Type System represents the different types of values supported by the language. The Type System checks validity of the supplied values, before they are stored or manipulated by the program. This ensures that the code behaves as expected. The Type System further allows for richer code hinting and automated documentation too." }, { "code": null, "e": 10209, "s": 10027, "text": "Rust is a statically typed language. Every value in Rust is of a certain data type. The compiler can automatically infer data type of the variable based on the value assigned to it." }, { "code": null, "e": 10252, "s": 10209, "text": "Use the let keyword to declare a variable." }, { "code": null, "e": 10717, "s": 10252, "text": "fn main() {\n let company_string = \"TutorialsPoint\"; // string type\n let rating_float = 4.5; // float type\n let is_growing_boolean = true; // boolean type\n let icon_char = '♥'; //unicode character type\n\n println!(\"company name is:{}\",company_string);\n println!(\"company rating on 5 is:{}\",rating_float);\n println!(\"company is growing :{}\",is_growing_boolean);\n println!(\"company icon is:{}\",icon_char);\n}" }, { "code": null, "e": 10934, "s": 10717, "text": "In the above example, data type of the variables will be inferred from the values assigned to them. For example, Rust will assign string data type to the variable company_string, float data type to rating_float, etc." }, { "code": null, "e": 10975, "s": 10934, "text": "The println! macro takes two arguments −" }, { "code": null, "e": 11022, "s": 10975, "text": "A special syntax { }, which is the placeholder" }, { "code": null, "e": 11054, "s": 11022, "text": "The variable name or a constant" }, { "code": null, "e": 11111, "s": 11054, "text": "The placeholder will be replaced by the variable’s value" }, { "code": null, "e": 11158, "s": 11111, "text": "The output of the above code snippet will be −" }, { "code": null, "e": 11262, "s": 11158, "text": "company name is: TutorialsPoint\ncompany rating on 5 is:4.5\ncompany is growing: true\ncompany icon is: ♥\n" }, { "code": null, "e": 11365, "s": 11262, "text": "A scalar type represents a single value. For example, 10,3.14,'c'. Rust has four primary scalar types." }, { "code": null, "e": 11373, "s": 11365, "text": "Integer" }, { "code": null, "e": 11388, "s": 11373, "text": "Floating-point" }, { "code": null, "e": 11397, "s": 11388, "text": "Booleans" }, { "code": null, "e": 11408, "s": 11397, "text": "Characters" }, { "code": null, "e": 11466, "s": 11408, "text": "We will learn about each type in our subsequent sections." }, { "code": null, "e": 11591, "s": 11466, "text": "An integer is a number without a fractional component. Simply put, the integer data type is used to represent whole numbers." }, { "code": null, "e": 11818, "s": 11591, "text": "Integers can be further classified as Signed and Unsigned. Signed integers can store both negative and positive values. Unsigned integers can only store positive values. A detailed description if integer types is given below −" }, { "code": null, "e": 12120, "s": 11818, "text": "The size of an integer can be arch. This means the size of the data type will be derived from the architecture of the machine. An integer the size of which is arch will be 32 bits on an x86 machine and 64 bits on an x64 machine. An arch integer is primarily used when indexing some sort of collection." }, { "code": null, "e": 12412, "s": 12120, "text": "fn main() {\n let result = 10; // i32 by default\n let age:u32 = 20;\n let sum:i32 = 5-15;\n let mark:isize = 10;\n let count:usize = 30;\n println!(\"result value is {}\",result);\n println!(\"sum is {} and age is {}\",sum,age);\n println!(\"mark is {} and count is {}\",mark,count);\n}" }, { "code": null, "e": 12448, "s": 12412, "text": "The output will be as given below −" }, { "code": null, "e": 12520, "s": 12448, "text": "result value is 10\nsum is -10 and age is 20\nmark is 10 and count is 30\n" }, { "code": null, "e": 12628, "s": 12520, "text": "The above code will return a compilation error if you replace the value of age with a floating-point value." }, { "code": null, "e": 12830, "s": 12628, "text": "Each signed variant can store numbers from -(2^(n-1) to 2^(n-1) -1, where n is the number of bits that variant uses. For example, i8 can store numbers from -(2^7) to 2^7 -1 − here we replaced n with 8." }, { "code": null, "e": 12970, "s": 12830, "text": "Each unsigned variant can store numbers from 0 to (2^n)-1. For example, u8 can store numbers from 0 to (2^8)-1, which is equal to 0 to 255." }, { "code": null, "e": 13135, "s": 12970, "text": "An integer overflow occurs when the value assigned to an integer variable exceeds the Rust defined range for the data type. Let us understand this with an example −" }, { "code": null, "e": 13488, "s": 13135, "text": "fn main() {\n let age:u8 = 255;\n\n // 0 to 255 only allowed for u8\n let weight:u8 = 256; //overflow value is 0\n let height:u8 = 257; //overflow value is 1\n let score:u8 = 258; //overflow value is 2\n\n println!(\"age is {} \",age);\n println!(\"weight is {}\",weight);\n println!(\"height is {}\",height);\n println!(\"score is {}\",score);\n}" }, { "code": null, "e": 13905, "s": 13488, "text": "The valid range of unsigned u8 variable is 0 to 255. In the above example, the variables are assigned values greater than 255 (upper limit for an integer variable in Rust). On execution, the above code will return a warning − warning − literal out of range for u8 for weight, height and score variables. The overflow values after 255 will start from 0, 1, 2, etc. The final output without warning is as shown below −" }, { "code": null, "e": 13952, "s": 13905, "text": "age is 255\nweight is 0\nheight is 1\nscore is 2\n" }, { "code": null, "e": 14184, "s": 13952, "text": "Float data type in Rust can be classified as f32 and f64. The f32 type is a single-precision float, and f64 has double precision. The default type is f64. Consider the following example to understand more about the float data type." }, { "code": null, "e": 14440, "s": 14184, "text": "fn main() {\n let result = 10.00; //f64 by default\n let interest:f32 = 8.35;\n let cost:f64 = 15000.600; //double precision\n \n println!(\"result value is {}\",result);\n println!(\"interest is {}\",interest);\n println!(\"cost is {}\",cost);\n}" }, { "code": null, "e": 14476, "s": 14440, "text": "The output will be as shown below −" }, { "code": null, "e": 14510, "s": 14476, "text": "interest is 8.35\ncost is 15000.6\n" }, { "code": null, "e": 14655, "s": 14510, "text": "Automatic type casting is not allowed in Rust. Consider the following code snippet. An integer value is assigned to the float variable interest." }, { "code": null, "e": 14774, "s": 14655, "text": "fn main() {\n let interest:f32 = 8; // integer assigned to float variable\n println!(\"interest is {}\",interest);\n}" }, { "code": null, "e": 14835, "s": 14774, "text": "The compiler throws a mismatched types error as given below." }, { "code": null, "e": 15071, "s": 14835, "text": "error[E0308]: mismatched types\n --> main.rs:2:22\n |\n 2 | let interest:f32=8;\n | ^ expected f32, found integral variable\n |\n = note: expected type `f32`\n found type `{integer}`\nerror: aborting due to previous error(s)\n" }, { "code": null, "e": 15251, "s": 15071, "text": "For easy readability of large numbers, we can use a visual separator _ underscore to separate digits. That is 50,000 can be written as 50_000 . This is shown in the below example." }, { "code": null, "e": 15451, "s": 15251, "text": "fn main() {\n let float_with_separator = 11_000.555_001;\n println!(\"float value {}\",float_with_separator);\n \n let int_with_separator = 50_000;\n println!(\"int value {}\",int_with_separator);\n}" }, { "code": null, "e": 15479, "s": 15451, "text": "The output is given below −" }, { "code": null, "e": 15521, "s": 15479, "text": "float value 11000.555001\nint value 50000\n" }, { "code": null, "e": 15629, "s": 15521, "text": "Boolean types have two possible values – true or false. Use the bool keyword to declare a boolean variable." }, { "code": null, "e": 15720, "s": 15629, "text": "fn main() {\n let isfun:bool = true;\n println!(\"Is Rust Programming Fun ? {}\",isfun);\n}" }, { "code": null, "e": 15759, "s": 15720, "text": "The output of the above code will be −" }, { "code": null, "e": 15791, "s": 15759, "text": "Is Rust Programming Fun ? true\n" }, { "code": null, "e": 16144, "s": 15791, "text": "The character data type in Rust supports numbers, alphabets, Unicode and special characters. Use the char keyword to declare a variable of character data type. Rust’s char type represents a Unicode Scalar Value, which means it can represent a lot more than just ASCII. Unicode Scalar Values range from U+0000 to U+D7FF and U+E000 to U+10FFFF inclusive." }, { "code": null, "e": 16221, "s": 16144, "text": "Let us consider an example to understand more about the Character data type." }, { "code": null, "e": 16466, "s": 16221, "text": "fn main() {\n let special_character = '@'; //default\n let alphabet:char = 'A';\n let emoji:char = '😁';\n \n println!(\"special character is {}\",special_character);\n println!(\"alphabet is {}\",alphabet);\n println!(\"emoji is {}\",emoji);\n}" }, { "code": null, "e": 16505, "s": 16466, "text": "The output of the above code will be −" }, { "code": null, "e": 16554, "s": 16505, "text": "special character is @\nalphabet is A\nemoji is 😁\n" }, { "code": null, "e": 16923, "s": 16554, "text": "A variable is a named storage that programs can manipulate. Simply put, a variable helps programs to store values. Variables in Rust are associated with a specific data type. The data type determines the size and layout of the variable's memory, the range of values that can be stored within that memory and the set of operations that can be performed on the variable." }, { "code": null, "e": 17003, "s": 16923, "text": "In this section, we will learn about the different rules for naming a variable." }, { "code": null, "e": 17092, "s": 17003, "text": "The name of a variable can be composed of letters, digits, and the underscore character." }, { "code": null, "e": 17181, "s": 17092, "text": "The name of a variable can be composed of letters, digits, and the underscore character." }, { "code": null, "e": 17234, "s": 17181, "text": "It must begin with either a letter or an underscore." }, { "code": null, "e": 17287, "s": 17234, "text": "It must begin with either a letter or an underscore." }, { "code": null, "e": 17360, "s": 17287, "text": "Upper and lowercase letters are distinct because Rust is case-sensitive." }, { "code": null, "e": 17433, "s": 17360, "text": "Upper and lowercase letters are distinct because Rust is case-sensitive." }, { "code": null, "e": 17562, "s": 17433, "text": "The data type is optional while declaring a variable in Rust. The data type is inferred from the value assigned to the variable." }, { "code": null, "e": 17614, "s": 17562, "text": "The syntax for declaring a variable is given below." }, { "code": null, "e": 17729, "s": 17614, "text": "let variable_name = value; // no type specified\nlet variable_name:dataType = value; //type specified\n" }, { "code": null, "e": 17852, "s": 17729, "text": "fn main() {\n let fees = 25_000;\n let salary:f64 = 35_000.00;\n println!(\"fees is {} and salary is {}\",fees,salary);\n}" }, { "code": null, "e": 17924, "s": 17852, "text": "The output of the above code will be fees is 25000 and salary is 35000." }, { "code": null, "e": 18078, "s": 17924, "text": "By default, variables are immutable − read only in Rust. In other words, the variable's value cannot be changed once a value is bound to a variable name." }, { "code": null, "e": 18118, "s": 18078, "text": "Let us understand this with an example." }, { "code": null, "e": 18245, "s": 18118, "text": "fn main() {\n let fees = 25_000;\n println!(\"fees is {} \",fees);\n fees = 35_000;\n println!(\"fees changed is {}\",fees);\n}" }, { "code": null, "e": 18281, "s": 18245, "text": "The output will be as shown below −" }, { "code": null, "e": 18539, "s": 18281, "text": "error[E0384]: re-assignment of immutable variable `fees`\n --> main.rs:6:3\n |\n 3 | let fees = 25_000;\n | ---- first assignment to `fees`\n...\n 6 | fees=35_000;\n | ^^^^^^^^^^^ re-assignment of immutable variable\n\nerror: aborting due to previous error(s)\n" }, { "code": null, "e": 18774, "s": 18539, "text": "The error message indicates the cause of the error – you cannot assign values twice to immutable variable fees. This is one of the many ways Rust allows programmers to write code and takes advantage of the safety and easy concurrency." }, { "code": null, "e": 18920, "s": 18774, "text": "Variables are immutable by default. Prefix the variable name with mut keyword to make it mutable. The value of a mutable variable can be changed." }, { "code": null, "e": 18984, "s": 18920, "text": "The syntax for declaring a mutable variable is as shown below −" }, { "code": null, "e": 19230, "s": 18984, "text": "let mut variable_name = value;\nlet mut variable_name:dataType = value;\nLet us understand this with an example\n\nfn main() {\n let mut fees:i32 = 25_000;\n println!(\"fees is {} \",fees);\n fees = 35_000;\n println!(\"fees changed is {}\",fees);\n}" }, { "code": null, "e": 19273, "s": 19230, "text": "The output of the snippet is given below −" }, { "code": null, "e": 19310, "s": 19273, "text": "fees is 25000\nfees changed is 35000\n" }, { "code": null, "e": 19552, "s": 19310, "text": "Constants represent values that cannot be changed. If you declare a constant then there is no way its value changes. The keyword for using constants is const. Constants must be explicitly typed. Following is the syntax to declare a constant." }, { "code": null, "e": 19591, "s": 19552, "text": "const VARIABLE_NAME:dataType = value;\n" }, { "code": null, "e": 19800, "s": 19591, "text": "The naming convention for Constants are similar to that of variables. All characters in a constant name are usually in uppercase. Unlike declaring variables, the let keyword is not used to declare a constant." }, { "code": null, "e": 19854, "s": 19800, "text": "We have used constants in Rust in the example below −" }, { "code": null, "e": 20148, "s": 19854, "text": "fn main() {\n const USER_LIMIT:i32 = 100; // Declare a integer constant\n const PI:f32 = 3.14; //Declare a float constant\n\n println!(\"user limit is {}\",USER_LIMIT); //Display value of the constant\n println!(\"pi value is {}\",PI); //Display value of the constant\n}" }, { "code": null, "e": 20246, "s": 20148, "text": "In this section, we will learn about the differentiating factors between constants and variables." }, { "code": null, "e": 20345, "s": 20246, "text": "Constants are declared using the const keyword while variables are declared using the let keyword." }, { "code": null, "e": 20444, "s": 20345, "text": "Constants are declared using the const keyword while variables are declared using the let keyword." }, { "code": null, "e": 20615, "s": 20444, "text": "A variable declaration can optionally have a data type whereas a constant declaration must specify the data type. This means const USER_LIMIT=100 will result in an error." }, { "code": null, "e": 20786, "s": 20615, "text": "A variable declaration can optionally have a data type whereas a constant declaration must specify the data type. This means const USER_LIMIT=100 will result in an error." }, { "code": null, "e": 20942, "s": 20786, "text": "A variable declared using the let keyword is by default immutable. However, you have an option to mutate it using the mut keyword. Constants are immutable." }, { "code": null, "e": 21098, "s": 20942, "text": "A variable declared using the let keyword is by default immutable. However, you have an option to mutate it using the mut keyword. Constants are immutable." }, { "code": null, "e": 21243, "s": 21098, "text": "Constants can be set only to a constant expression and not to the result of a function call or any other value that will be computed at runtime." }, { "code": null, "e": 21388, "s": 21243, "text": "Constants can be set only to a constant expression and not to the result of a function call or any other value that will be computed at runtime." }, { "code": null, "e": 21539, "s": 21388, "text": "Constants can be declared in any scope, including the global scope, which makes them useful for values that many parts of the code need to know about." }, { "code": null, "e": 21690, "s": 21539, "text": "Constants can be declared in any scope, including the global scope, which makes them useful for values that many parts of the code need to know about." }, { "code": null, "e": 21821, "s": 21690, "text": "Rust allows programmers to declare variables with the same name. In such a case, the new variable overrides the previous variable." }, { "code": null, "e": 21861, "s": 21821, "text": "Let us understand this with an example." }, { "code": null, "e": 21998, "s": 21861, "text": "fn main() {\n let salary = 100.00;\n let salary = 1.50 ; \n // reads first salary\n println!(\"The value of salary is :{}\",salary);\n}" }, { "code": null, "e": 22233, "s": 21998, "text": "The above code declares two variables by the name salary. The first declaration is assigned a 100.00 while the second declaration is assigned value 1.50. The second variable shadows or hides the first variable while displaying output." }, { "code": null, "e": 22263, "s": 22233, "text": "The value of salary is :1.50\n" }, { "code": null, "e": 22330, "s": 22263, "text": "Rust supports variables with different data types while shadowing." }, { "code": null, "e": 22362, "s": 22330, "text": "Consider the following example." }, { "code": null, "e": 22593, "s": 22362, "text": "The code declares two variables by the name uname. The first declaration is assigned a string value, whereas the second declaration is assigned an integer. The len function returns the total number of characters in a string value." }, { "code": null, "e": 22714, "s": 22593, "text": "fn main() {\n let uname = \"Mohtashim\";\n let uname = uname.len();\n println!(\"name changed to integer : {}\",uname);\n}" }, { "code": null, "e": 22742, "s": 22714, "text": "name changed to integer: 9\n" }, { "code": null, "e": 22887, "s": 22742, "text": "Unlike variables, constants cannot be shadowed. If variables in the above program are replaced with constants, the compiler will throw an error." }, { "code": null, "e": 23056, "s": 22887, "text": "fn main() {\n const NAME:&str = \"Mohtashim\";\n const NAME:usize = NAME.len(); \n //Error : `NAME` already defined\n println!(\"name changed to integer : {}\",NAME);\n}" }, { "code": null, "e": 23124, "s": 23056, "text": "The String data type in Rust can be classified into the following −" }, { "code": null, "e": 23145, "s": 23124, "text": "String Literal(&str)" }, { "code": null, "e": 23166, "s": 23145, "text": "String Literal(&str)" }, { "code": null, "e": 23188, "s": 23166, "text": "String Object(String)" }, { "code": null, "e": 23210, "s": 23188, "text": "String Object(String)" }, { "code": null, "e": 23512, "s": 23210, "text": "String literals (&str) are used when the value of a string is known at compile time. String literals are a set of characters, which are hardcoded into a variable. For example, let company=\"Tutorials Point\". String literals are found in module std::str. String literals are also known as string slices." }, { "code": null, "e": 23587, "s": 23512, "text": "The following example declares two string literals − company and location." }, { "code": null, "e": 23737, "s": 23587, "text": "fn main() {\n let company:&str=\"TutorialsPoint\";\n let location:&str = \"Hyderabad\";\n println!(\"company is : {} location :{}\",company,location);\n}" }, { "code": null, "e": 23946, "s": 23737, "text": "String literals are static by default. This means that string literals are guaranteed to be valid for the duration of the entire program. We can also explicitly specify the variable as static as shown below −" }, { "code": null, "e": 24114, "s": 23946, "text": "fn main() {\n let company:&'static str = \"TutorialsPoint\";\n let location:&'static str = \"Hyderabad\";\n println!(\"company is : {} location :{}\",company,location);\n}" }, { "code": null, "e": 24169, "s": 24114, "text": "The above program will generate the following output −" }, { "code": null, "e": 24218, "s": 24169, "text": "company is : TutorialsPoint location :Hyderabad\n" }, { "code": null, "e": 24632, "s": 24218, "text": "The String object type is provided in Standard Library. Unlike string literal, the string object type is not a part of the core language. It is defined as public structure in standard library pub struct String. String is a growable collection. It is mutable and UTF-8 encoded type. The String object type can be used to represent string values that are provided at runtime. String object is allocated in the heap." }, { "code": null, "e": 24700, "s": 24632, "text": "To create a String object, we can use any of the following syntax −" }, { "code": null, "e": 24715, "s": 24700, "text": "String::new()\n" }, { "code": null, "e": 24756, "s": 24715, "text": "The above syntax creates an empty string" }, { "code": null, "e": 24772, "s": 24756, "text": "String::from()\n" }, { "code": null, "e": 24860, "s": 24772, "text": "This creates a string with some default value passed as parameter to the from() method." }, { "code": null, "e": 24922, "s": 24860, "text": "The following example illustrates the use of a String object." }, { "code": null, "e": 25127, "s": 24922, "text": "fn main(){\n let empty_string = String::new();\n println!(\"length is {}\",empty_string.len());\n\n let content_string = String::from(\"TutorialsPoint\");\n println!(\"length is {}\",content_string.len());\n}" }, { "code": null, "e": 25274, "s": 25127, "text": "The above example creates two strings − an empty string object using the new method and a string object from string literal using the from method." }, { "code": null, "e": 25305, "s": 25274, "text": "The output is as shown below −" }, { "code": null, "e": 25331, "s": 25305, "text": "length is 0\nlength is 14\n" }, { "code": null, "e": 25419, "s": 25331, "text": "An empty string object is created using the new() method and its value is set to hello." }, { "code": null, "e": 25507, "s": 25419, "text": "fn main(){\n let mut z = String::new();\n z.push_str(\"hello\");\n println!(\"{}\",z);\n}" }, { "code": null, "e": 25558, "s": 25507, "text": "The above program generates the following output −" }, { "code": null, "e": 25565, "s": 25558, "text": "hello\n" }, { "code": null, "e": 25677, "s": 25565, "text": "To access all methods of String object, convert a string literal to object type using the to_string() function." }, { "code": null, "e": 25779, "s": 25677, "text": "fn main(){\n let name1 = \"Hello TutorialsPoint , \n Hello!\".to_string();\n println!(\"{}\",name1);\n}" }, { "code": null, "e": 25830, "s": 25779, "text": "The above program generates the following output −" }, { "code": null, "e": 25861, "s": 25830, "text": "Hello TutorialsPoint , Hello!\n" }, { "code": null, "e": 26086, "s": 25861, "text": "The replace() function takes two parameters − the first parameter is a string pattern to search for and the second parameter is the new value to be replaced. In the above example, Hello appears two times in the name1 string." }, { "code": null, "e": 26164, "s": 26086, "text": "The replace function replaces all occurrences of the string Hello with Howdy." }, { "code": null, "e": 26359, "s": 26164, "text": "fn main(){\n let name1 = \"Hello TutorialsPoint , \n Hello!\".to_string(); //String object\n let name2 = name1.replace(\"Hello\",\"Howdy\"); //find and replace\n println!(\"{}\",name2);\n}" }, { "code": null, "e": 26410, "s": 26359, "text": "The above program generates the following output −" }, { "code": null, "e": 26441, "s": 26410, "text": "Howdy TutorialsPoint , Howdy!\n" }, { "code": null, "e": 26517, "s": 26441, "text": "The as_str() function extracts a string slice containing the entire string." }, { "code": null, "e": 26712, "s": 26517, "text": "fn main() {\n let example_string = String::from(\"example_string\");\n print_literal(example_string.as_str());\n}\nfn print_literal(data:&str ){\n println!(\"displaying string literal {}\",data);\n}" }, { "code": null, "e": 26763, "s": 26712, "text": "The above program generates the following output −" }, { "code": null, "e": 26805, "s": 26763, "text": "displaying string literal example_string\n" }, { "code": null, "e": 26875, "s": 26805, "text": "The push() function appends the given char to the end of this String." }, { "code": null, "e": 26982, "s": 26875, "text": "fn main(){\n let mut company = \"Tutorial\".to_string();\n company.push('s');\n println!(\"{}\",company);\n}" }, { "code": null, "e": 27033, "s": 26982, "text": "The above program generates the following output −" }, { "code": null, "e": 27044, "s": 27033, "text": "Tutorials\n" }, { "code": null, "e": 27123, "s": 27044, "text": "The push_str() function appends a given string slice onto the end of a String." }, { "code": null, "e": 27240, "s": 27123, "text": "fn main(){\n let mut company = \"Tutorials\".to_string();\n company.push_str(\" Point\");\n println!(\"{}\",company);\n}" }, { "code": null, "e": 27291, "s": 27240, "text": "The above program generates the following output −" }, { "code": null, "e": 27308, "s": 27291, "text": "Tutorials Point\n" }, { "code": null, "e": 27398, "s": 27308, "text": "The len() function returns the total number of characters in a string (including spaces)." }, { "code": null, "e": 27494, "s": 27398, "text": "fn main() {\n let fullname = \" Tutorials Point\";\n println!(\"length is {}\",fullname.len());\n}" }, { "code": null, "e": 27545, "s": 27494, "text": "The above program generates the following output −" }, { "code": null, "e": 27559, "s": 27545, "text": "length is 20\n" }, { "code": null, "e": 27687, "s": 27559, "text": "The trim() function removes leading and trailing spaces in a string. NOTE that this function will not remove the inline spaces." }, { "code": null, "e": 27911, "s": 27687, "text": "fn main() {\n let fullname = \" Tutorials Point \\r\\n\";\n println!(\"Before trim \");\n println!(\"length is {}\",fullname.len());\n println!();\n println!(\"After trim \");\n println!(\"length is {}\",fullname.trim().len());\n}" }, { "code": null, "e": 27962, "s": 27911, "text": "The above program generates the following output −" }, { "code": null, "e": 28013, "s": 27962, "text": "Before trim\nlength is 24\n\nAfter trim\nlength is 15\n" }, { "code": null, "e": 28163, "s": 28013, "text": "The split_whitespace() splits the input string into different strings. It returns an iterator so we are iterating through the tokens as shown below −" }, { "code": null, "e": 28361, "s": 28163, "text": "fn main(){\n let msg = \"Tutorials Point has good t\n utorials\".to_string();\n let mut i = 1;\n \n for token in msg.split_whitespace(){\n println!(\"token {} {}\",i,token);\n i+=1;\n }\n}" }, { "code": null, "e": 28437, "s": 28361, "text": "token 1 Tutorials\ntoken 2 Point\ntoken 3 has\ntoken 4 good\ntoken 5 tutorials\n" }, { "code": null, "e": 28736, "s": 28437, "text": "The split() string method returns an iterator over substrings of a string slice, separated by characters matched by a pattern. The limitation of the split() method is that the result cannot be stored for later use. The collect method can be used to store the result returned by split() as a vector." }, { "code": null, "e": 29106, "s": 28736, "text": "fn main() {\n let fullname = \"Kannan,Sudhakaran,Tutorialspoint\";\n\n for token in fullname.split(\",\"){\n println!(\"token is {}\",token);\n }\n\n //store in a Vector\n println!(\"\\n\");\n let tokens:Vec<&str>= fullname.split(\",\").collect();\n println!(\"firstName is {}\",tokens[0]);\n println!(\"lastname is {}\",tokens[1]);\n println!(\"company is {}\",tokens[2]);\n}" }, { "code": null, "e": 29188, "s": 29106, "text": "The above example splits the string fullname, whenever it encounters a comma (,)." }, { "code": null, "e": 29319, "s": 29188, "text": "token is Kannan\ntoken is Sudhakaran\ntoken is Tutorialspoint\n\nfirstName is Kannan\nlastname is Sudhakaran\ncompany is Tutorialspoint\n" }, { "code": null, "e": 29440, "s": 29319, "text": "Individual characters in a string can be accessed using the chars method. Let us consider an example to understand this." }, { "code": null, "e": 29544, "s": 29440, "text": "fn main(){\n let n1 = \"Tutorials\".to_string();\n\n for n in n1.chars(){\n println!(\"{}\",n);\n }\n}" }, { "code": null, "e": 29563, "s": 29544, "text": "T\nu\nt\no\nr\ni\na\nl\ns\n" }, { "code": null, "e": 29964, "s": 29563, "text": "A string value can be appended to another string. This is called concatenation or interpolation. The result of string concatenation is a new string object. The + operator internally uses an add method. The syntax of the add function takes two parameters. The first parameter is self – the string object itself and the second parameter is a reference of the second string object. This is shown below −" }, { "code": null, "e": 30038, "s": 29964, "text": "//add function\nadd(self,&str)->String { \n // returns a String object\n}\n" }, { "code": null, "e": 30192, "s": 30038, "text": "fn main(){\n let n1 = \"Tutorials\".to_string();\n let n2 = \"Point\".to_string();\n\n let n3 = n1 + &n2; // n2 reference is passed\n println!(\"{}\",n3);\n}" }, { "code": null, "e": 30226, "s": 30192, "text": "The Output will be as given below" }, { "code": null, "e": 30242, "s": 30226, "text": "TutorialsPoint\n" }, { "code": null, "e": 30317, "s": 30242, "text": "The following example illustrates converting a number to a string object −" }, { "code": null, "e": 30514, "s": 30317, "text": "fn main(){\n let number = 2020;\n let number_as_string = number.to_string(); \n \n // convert number to string\n println!(\"{}\",number_as_string);\n println!(\"{}\",number_as_string==\"2020\");\n}" }, { "code": null, "e": 30548, "s": 30514, "text": "The Output will be as given below" }, { "code": null, "e": 30559, "s": 30548, "text": "2020\ntrue\n" }, { "code": null, "e": 30684, "s": 30559, "text": "Another way to add to String objects together is using a macro function called format. The use of Format! is as shown below." }, { "code": null, "e": 30825, "s": 30684, "text": "fn main(){\n let n1 = \"Tutorials\".to_string();\n let n2 = \"Point\".to_string();\n let n3 = format!(\"{} {}\",n1,n2);\n println!(\"{}\",n3);\n}" }, { "code": null, "e": 30859, "s": 30825, "text": "The Output will be as given below" }, { "code": null, "e": 30876, "s": 30859, "text": "Tutorials Point\n" }, { "code": null, "e": 31036, "s": 30876, "text": "An operator defines some function that will be performed on the data. The data on which operators work are called operands. Consider the following expression −" }, { "code": null, "e": 31047, "s": 31036, "text": "7 + 5 = 12" }, { "code": null, "e": 31120, "s": 31047, "text": "Here, the values 7, 5, and 12 are operands, while + and = are operators." }, { "code": null, "e": 31171, "s": 31120, "text": "The major operators in Rust can be classified as −" }, { "code": null, "e": 31182, "s": 31171, "text": "Arithmetic" }, { "code": null, "e": 31190, "s": 31182, "text": "Bitwise" }, { "code": null, "e": 31201, "s": 31190, "text": "Comparison" }, { "code": null, "e": 31209, "s": 31201, "text": "Logical" }, { "code": null, "e": 31217, "s": 31209, "text": "Bitwise" }, { "code": null, "e": 31229, "s": 31217, "text": "Conditional" }, { "code": null, "e": 31295, "s": 31229, "text": "Assume the values in variables a and b are 10 and 5 respectively." }, { "code": null, "e": 31309, "s": 31295, "text": "Show Examples" }, { "code": null, "e": 31367, "s": 31309, "text": "NOTE − The ++ and -- operators are not supported in Rust." }, { "code": null, "e": 31572, "s": 31367, "text": "Relational Operators test or define the kind of relationship between two entities. Relational operators are used to compare two or more values. Relational operators return a Boolean value − true or false." }, { "code": null, "e": 31613, "s": 31572, "text": "Assume the value of A is 10 and B is 20." }, { "code": null, "e": 31627, "s": 31613, "text": "Show Examples" }, { "code": null, "e": 31786, "s": 31627, "text": "Logical Operators are used to combine two or more conditions. Logical operators too, return a Boolean value. Assume the value of variable A is 10 and B is 20." }, { "code": null, "e": 31800, "s": 31786, "text": "Show Examples" }, { "code": null, "e": 31833, "s": 31800, "text": "Assume variable A = 2 and B = 3." }, { "code": null, "e": 31847, "s": 31833, "text": "Show Examples" }, { "code": null, "e": 32162, "s": 31847, "text": "Decision-making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false." }, { "code": null, "e": 32278, "s": 32162, "text": "Shown below is the general form of a typical decision-making structure found in most of the programming languages −" }, { "code": null, "e": 32291, "s": 32278, "text": "if statement" }, { "code": null, "e": 32376, "s": 32291, "text": "An if statement consists of a Boolean expression followed by one or more statements." }, { "code": null, "e": 32396, "s": 32376, "text": "if...else statement" }, { "code": null, "e": 32512, "s": 32396, "text": "An if statement can be followed by an optional else statement, which executes when the Boolean expression is false." }, { "code": null, "e": 32545, "s": 32512, "text": "else...if and nested ifstatement" }, { "code": null, "e": 32628, "s": 32545, "text": "You can use one if or else if statement inside another if or else if statement(s)." }, { "code": null, "e": 32644, "s": 32628, "text": "match statement" }, { "code": null, "e": 32719, "s": 32644, "text": "A match statement allows a variable to be tested against a list of values." }, { "code": null, "e": 32801, "s": 32719, "text": "The if...else construct evaluates a condition before a block of code is executed." }, { "code": null, "e": 32894, "s": 32801, "text": "if boolean_expression {\n // statement(s) will execute if the boolean expression is true\n}\n" }, { "code": null, "e": 33161, "s": 32894, "text": "If the Boolean expression evaluates to true, then the block of code inside the if statement will be executed. If the Boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing curly brace) will be executed." }, { "code": null, "e": 33254, "s": 33161, "text": "fn main(){\n let num:i32 = 5;\n if num > 0 {\n println!(\"number is positive\") ;\n }\n}" }, { "code": null, "e": 33354, "s": 33254, "text": "The above example will print number is positive as the condition specified by the if block is true." }, { "code": null, "e": 33504, "s": 33354, "text": "An if can be followed by an optional else block. The else block will execute if the Boolean expression tested by the if statement evaluates to false." }, { "code": null, "e": 33673, "s": 33504, "text": "if boolean_expression {\n // statement(s) will execute if the boolean expression is true\n} else {\n // statement(s) will execute if the boolean expression is false\n}\n" }, { "code": null, "e": 33821, "s": 33673, "text": "The if block guards the conditional expression. The block associated with the if statement is executed if the Boolean expression evaluates to true." }, { "code": null, "e": 33984, "s": 33821, "text": "The if block may be followed by an optional else statement. The instruction block associated with the else block is executed if the expression evaluates to false." }, { "code": null, "e": 34098, "s": 33984, "text": "fn main() {\n let num = 12;\n if num % 2==0 {\n println!(\"Even\");\n } else {\n println!(\"Odd\");\n }\n}" }, { "code": null, "e": 34288, "s": 34098, "text": "The above example prints whether the value in a variable is even or odd. The if block checks the divisibility of the value by 2 to determine the same. Here is the output of the above code −" }, { "code": null, "e": 34294, "s": 34288, "text": "Even\n" }, { "code": null, "e": 34385, "s": 34294, "text": "The else...if ladder is useful to test multiple conditions. The syntax is as shown below −" }, { "code": null, "e": 34628, "s": 34385, "text": "if boolean_expression1 {\n //statements if the expression1 evaluates to true\n} else if boolean_expression2 {\n //statements if the expression2 evaluates to true\n} else {\n //statements if both expression1 and expression2 result to false\n}\n" }, { "code": null, "e": 34715, "s": 34628, "text": "When using if...else...if and else statements, there are a few points to keep in mind." }, { "code": null, "e": 34786, "s": 34715, "text": "An if can have zero or one else's and it must come after any else..if." }, { "code": null, "e": 34859, "s": 34786, "text": "An if can have zero to many else..if and they must come before the else." }, { "code": null, "e": 34941, "s": 34859, "text": "Once an else..if succeeds, none of the remaining else..if or else will be tested." }, { "code": null, "e": 35164, "s": 34941, "text": "fn main() {\n let num = 2 ;\n if num > 0 {\n println!(\"{} is positive\",num);\n } else if num < 0 {\n println!(\"{} is negative\",num);\n } else {\n println!(\"{} is neither positive nor negative\",num) ;\n }\n}" }, { "code": null, "e": 35234, "s": 35164, "text": "The snippet displays whether the value is positive, negative or zero." }, { "code": null, "e": 35249, "s": 35234, "text": "2 is positive\n" }, { "code": null, "e": 35515, "s": 35249, "text": "The match statement checks if a current value is matching from a list of values, this is very much similar to the switch statement in C language. In the first place, notice that the expression following the match keyword does not have to be enclosed in parentheses." }, { "code": null, "e": 35545, "s": 35515, "text": "The syntax is as shown below." }, { "code": null, "e": 35729, "s": 35545, "text": "let expressionResult = match variable_expression {\n constant_expr1 => {\n //statements;\n },\n constant_expr2 => {\n //statements;\n },\n _ => {\n //default\n }\n};\n" }, { "code": null, "e": 35966, "s": 35729, "text": "In the example given below, state_code is matched with a list of values MH, KL, KA, GA − if any match is found, a string value is returned to variable state. If no match is found, the default case _ matches and value Unkown is returned." }, { "code": null, "e": 36240, "s": 35966, "text": "fn main(){\n let state_code = \"MH\";\n let state = match state_code {\n \"MH\" => {println!(\"Found match for MH\"); \"Maharashtra\"},\n \"KL\" => \"Kerala\",\n \"KA\" => \"Karnadaka\",\n \"GA\" => \"Goa\",\n _ => \"Unknown\"\n };\n println!(\"State name is {}\",state);\n}" }, { "code": null, "e": 36286, "s": 36240, "text": "Found match for MH\nState name is Maharashtra\n" }, { "code": null, "e": 36517, "s": 36286, "text": "There may be instances, where a block of code needs to be executed repeatedly. In general, programming instructions are executed sequentially: The first statement in a function is executed first, followed by the second, and so on." }, { "code": null, "e": 36623, "s": 36517, "text": "Programming languages provide various control structures that allow for more complicated execution paths." }, { "code": null, "e": 36802, "s": 36623, "text": "A loop statement allows us to execute a statement or group of statements multiple times. Given below is the general form of a loop statement in most of the programming languages." }, { "code": null, "e": 36874, "s": 36802, "text": "Rust provides different types of loops to handle looping requirements −" }, { "code": null, "e": 36880, "s": 36874, "text": "while" }, { "code": null, "e": 36885, "s": 36880, "text": "loop" }, { "code": null, "e": 36889, "s": 36885, "text": "for" }, { "code": null, "e": 37032, "s": 36889, "text": "A loop the number of iterations of which is definite/fixed is termed as a definite loop. The for loop is an implementation of a definite loop." }, { "code": null, "e": 37219, "s": 37032, "text": "The for loop executes the code block for a specified number of times. It can be used to iterate over a fixed set of values, such as an array. The syntax of the for loop is as given below" }, { "code": null, "e": 37286, "s": 37219, "text": "for temp_variable in lower_bound..upper_bound {\n //statements\n}\n" }, { "code": null, "e": 37329, "s": 37286, "text": "An example of a for loop is as shown below" }, { "code": null, "e": 37461, "s": 37329, "text": "fn main(){\n for x in 1..11{ // 11 is not inclusive\n if x==5 {\n continue;\n }\n println!(\"x is {}\",x);\n }\n}" }, { "code": null, "e": 37528, "s": 37461, "text": "NOTE: that the variable x is only accessible within the for block." }, { "code": null, "e": 37593, "s": 37528, "text": "x is 1\nx is 2\nx is 3\nx is 4\nx is 6\nx is 7\nx is 8\nx is 9\nx is 10\n" }, { "code": null, "e": 37689, "s": 37593, "text": "An indefinite loop is used when the number of iterations in a loop is indeterminate or unknown." }, { "code": null, "e": 37733, "s": 37689, "text": "Indefinite loops can be implemented using −" }, { "code": null, "e": 37739, "s": 37733, "text": "While" }, { "code": null, "e": 37832, "s": 37739, "text": "The while loop executes the instructions each time the condition specified evaluates to true" }, { "code": null, "e": 37837, "s": 37832, "text": "Loop" }, { "code": null, "e": 37879, "s": 37837, "text": "The loop is a while(true) indefinite loop" }, { "code": null, "e": 38036, "s": 37879, "text": "fn main(){\n let mut x = 0;\n while x < 10{\n x+=1;\n println!(\"inside loop x value is {}\",x);\n }\n println!(\"outside loop x value is {}\",x);\n}" }, { "code": null, "e": 38067, "s": 38036, "text": "The output is as shown below −" }, { "code": null, "e": 38346, "s": 38067, "text": "inside loop x value is 1\ninside loop x value is 2\ninside loop x value is 3\ninside loop x value is 4\ninside loop x value is 5\ninside loop x value is 6\ninside loop x value is 7\ninside loop x value is 8\ninside loop x value is 9\ninside loop x value is 10\noutside loop x value is 10\n" }, { "code": null, "e": 38489, "s": 38346, "text": "fn main(){\n //while true\n\n let mut x = 0;\n loop {\n x+=1;\n println!(\"x={}\",x);\n\n if x==15 {\n break;\n }\n }\n}" }, { "code": null, "e": 38616, "s": 38489, "text": "The break statement is used to take the control out of a construct. Using break in a loop causes the program to exit the loop." }, { "code": null, "e": 38683, "s": 38616, "text": "x=1\nx=2\nx=3\nx=4\nx=5\nx=6\nx=7\nx=8\nx=9\nx=10\nx=11\nx=12\nx=13\nx=14\nx=15\n" }, { "code": null, "e": 38958, "s": 38683, "text": "The continue statement skips the subsequent statements in the current iteration and takes the control back to the beginning of the loop. Unlike the break statement, the continue does not exit the loop. It terminates the current iteration and starts the subsequent iteration." }, { "code": null, "e": 39011, "s": 38958, "text": "An example of the continue statement is given below." }, { "code": null, "e": 39230, "s": 39011, "text": "fn main() {\n\n let mut count = 0;\n\n for num in 0..21 {\n if num % 2==0 {\n continue;\n }\n count+=1;\n }\n println! (\" The count of odd values between 0 and 20 is: {} \",count);\n //outputs 10\n}" }, { "code": null, "e": 39408, "s": 39230, "text": "The above example displays the number of even values between 0 and 20. The loop exits the current iteration if the number is even. This is achieved using the continue statement." }, { "code": null, "e": 39455, "s": 39408, "text": "The count of odd values between 0 and 20 is 10" }, { "code": null, "e": 39815, "s": 39455, "text": "Functions are the building blocks of readable, maintainable, and reusable code. A function is a set of statements to perform a specific task. Functions organize the program into logical blocks of code. Once defined, functions may be called to access code. This makes the code reusable. Moreover, functions make it easy to read and maintain the program’s code." }, { "code": null, "e": 39975, "s": 39815, "text": "A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function." }, { "code": null, "e": 39995, "s": 39975, "text": "Defining a function" }, { "code": null, "e": 40071, "s": 39995, "text": "A function definition specifies what and how a specific task would be done." }, { "code": null, "e": 40102, "s": 40071, "text": "Calling or invoking a Function" }, { "code": null, "e": 40149, "s": 40102, "text": "A function must be called so as to execute it." }, { "code": null, "e": 40169, "s": 40149, "text": "Returning Functions" }, { "code": null, "e": 40241, "s": 40169, "text": "Functions may also return value along with control, back to the caller." }, { "code": null, "e": 40264, "s": 40241, "text": "Parameterized Function" }, { "code": null, "e": 40320, "s": 40264, "text": "Parameters are a mechanism to pass values to functions." }, { "code": null, "e": 40684, "s": 40320, "text": "A function definition specifies what and how a specific task would be done. Before using a function, it must be defined. The function body contains code that should be executed by the function. The rules for naming a function are similar to that of a variable. Functions are defined using the fn keyword. The syntax for defining a standard function is given below" }, { "code": null, "e": 40749, "s": 40684, "text": "fn function_name(param1,param2..paramN) {\n // function body\n}\n" }, { "code": null, "e": 40866, "s": 40749, "text": "A function declaration can optionally contain parameters/arguments. Parameters are used to pass values to functions." }, { "code": null, "e": 40951, "s": 40866, "text": "//Defining a function\nfn fn_hello(){\n println!(\"hello from function fn_hello \");\n}" }, { "code": null, "e": 41186, "s": 40951, "text": "A function must be called so as to execute it. This process is termed as function invocation. Values for parameters should be passed when a function is invoked. The function that invokes another function is called the caller function." }, { "code": null, "e": 41217, "s": 41186, "text": "function_name(val1,val2,valN)\n" }, { "code": null, "e": 41269, "s": 41217, "text": "fn main(){\n //calling a function\n fn_hello();\n}" }, { "code": null, "e": 41310, "s": 41269, "text": "Here, the main() is the caller function." }, { "code": null, "e": 41462, "s": 41310, "text": "The following example defines a function fn_hello(). The function prints a message to the console. The main() function invokes the fn_hello() function." }, { "code": null, "e": 41599, "s": 41462, "text": "fn main(){\n //calling a function\n fn_hello();\n}\n//Defining a function\nfn fn_hello(){\n println!(\"hello from function fn_hello \");\n}" }, { "code": null, "e": 41629, "s": 41599, "text": "hello from function fn_hello\n" }, { "code": null, "e": 41750, "s": 41629, "text": "Functions may also return a value along with control, back to the caller. Such functions are called returning functions." }, { "code": null, "e": 41832, "s": 41750, "text": "Either of the following syntax can be used to define a function with return type." }, { "code": null, "e": 41921, "s": 41832, "text": "// Syntax1\nfunction function_name() -> return_type {\n //statements\n return value;\n}\n" }, { "code": null, "e": 42029, "s": 41921, "text": "//Syntax2\nfunction function_name() -> return_type {\n value //no semicolon means this value is returned\n}\n" }, { "code": null, "e": 42115, "s": 42029, "text": "fn main(){\n println!(\"pi value is {}\",get_pi());\n}\nfn get_pi()->f64 {\n 22.0/7.0\n}" }, { "code": null, "e": 42146, "s": 42115, "text": "pi value is 3.142857142857143\n" }, { "code": null, "e": 42441, "s": 42146, "text": "Parameters are a mechanism to pass values to functions. Parameters form a part of the function’s signature. The parameter values are passed to the function during its invocation. Unless explicitly specified, the number of values passed to a function must match the number of parameters defined." }, { "code": null, "e": 42520, "s": 42441, "text": "Parameters can be passed to a function using one of the following techniques −" }, { "code": null, "e": 42763, "s": 42520, "text": "When a method is invoked, a new storage location is created for each value parameter. The values of the actual parameters are copied into them. Hence, the changes made to the parameter inside the invoked method have no effect on the argument." }, { "code": null, "e": 43046, "s": 42763, "text": "The following example declares a variable no, which is initially 5. The variable is passed as parameter (by value) to the mutate_no_to_zero()functionnction, which changes the value to zero. After the function call when control returns back to main method the value will be the same." }, { "code": null, "e": 43263, "s": 43046, "text": "fn main(){\n let no:i32 = 5;\n mutate_no_to_zero(no);\n println!(\"The value of no is:{}\",no);\n}\n\nfn mutate_no_to_zero(mut param_no: i32) {\n param_no = param_no*0;\n println!(\"param_no value is :{}\",param_no);\n}" }, { "code": null, "e": 43270, "s": 43263, "text": "Output" }, { "code": null, "e": 43313, "s": 43270, "text": "param_no value is :0\nThe value of no is:5\n" }, { "code": null, "e": 43643, "s": 43313, "text": "When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters. The reference parameters represent the same memory location as the actual parameters that are supplied to the method. Parameter values can be passed by reference by prefixing the variable name with an & . " }, { "code": null, "e": 43962, "s": 43643, "text": "In the example given below, we have a variable no, which is initially 5. A reference to the variable no is passed to the mutate_no_to_zero() function. The function operates on the original variable. After the function call, when control returns back to main method, the value of the original variable will be the zero." }, { "code": null, "e": 44147, "s": 43962, "text": "fn main() {\n let mut no:i32 = 5;\n mutate_no_to_zero(&mut no);\n println!(\"The value of no is:{}\",no);\n}\nfn mutate_no_to_zero(param_no:&mut i32){\n *param_no = 0; //de reference\n}" }, { "code": null, "e": 44291, "s": 44147, "text": "The * operator is used to access value stored in the memory location that the variable param_no points to. This is also known as dereferencing." }, { "code": null, "e": 44312, "s": 44291, "text": "The output will be −" }, { "code": null, "e": 44335, "s": 44312, "text": "The value of no is 0.\n" }, { "code": null, "e": 44405, "s": 44335, "text": "The main() function passes a string object to the display() function." }, { "code": null, "e": 44612, "s": 44405, "text": "fn main(){\n let name:String = String::from(\"TutorialsPoint\");\n display(name); \n //cannot access name after display\n}\nfn display(param_name:String){\n println!(\"param_name value is :{}\",param_name);\n}" }, { "code": null, "e": 44649, "s": 44612, "text": "param_name value is :TutorialsPoint\n" }, { "code": null, "e": 44891, "s": 44649, "text": "Tuple is a compound data type. A scalar type can store only one type of data. For example, an i32 variable can store only a single integer value. In compound types, we can store more than one value at a time and it can be of different types." }, { "code": null, "e": 45001, "s": 44891, "text": "Tuples have a fixed length - once declared they cannot grow or shrink in size. The tuple index starts from 0." }, { "code": null, "e": 45140, "s": 45001, "text": "//Syntax1\nlet tuple_name:(data_type1,data_type2,data_type3) = (value1,value2,value3);\n\n//Syntax2\nlet tuple_name = (value1,value2,value3);\n" }, { "code": null, "e": 45194, "s": 45140, "text": "The following example displays the values in a tuple." }, { "code": null, "e": 45278, "s": 45194, "text": "fn main() {\n let tuple:(i32,f64,u8) = (-325,4.9,22);\n println!(\"{:?}\",tuple);\n}" }, { "code": null, "e": 45472, "s": 45278, "text": "The println!(\"{ }\",tuple) syntax cannot be used to display values in a tuple. This is because a tuple is a compound type. Use the println!(\"{:?}\", tuple_name) syntax to print values in a tuple." }, { "code": null, "e": 45489, "s": 45472, "text": "(-325, 4.9, 22)\n" }, { "code": null, "e": 45548, "s": 45489, "text": "The following example prints individual values in a tuple." }, { "code": null, "e": 45735, "s": 45548, "text": "fn main() {\n let tuple:(i32,f64,u8) = (-325,4.9,22);\n println!(\"integer is :{:?}\",tuple.0);\n println!(\"float is :{:?}\",tuple.1);\n println!(\"unsigned integer is :{:?}\",tuple.2);\n}" }, { "code": null, "e": 45790, "s": 45735, "text": "integer is :-325\nfloat is :4.9\nunsigned integer is :2\n" }, { "code": null, "e": 45896, "s": 45790, "text": "The following example passes a tuple as parameter to a function. Tuples are passed by value to functions." }, { "code": null, "e": 46087, "s": 45896, "text": "fn main(){\n let b:(i32,bool,f64) = (110,true,10.9);\n print(b);\n}\n//pass the tuple as a parameter\n\nfn print(x:(i32,bool,f64)){\n println!(\"Inside print method\");\n println!(\"{:?}\",x);\n}" }, { "code": null, "e": 46126, "s": 46087, "text": "Inside print method\n(110, true, 10.9)\n" }, { "code": null, "e": 46272, "s": 46126, "text": "Destructing assignment is a feature of rust wherein we unpack the values of a tuple. This is achieved by assigning a tuple to distinct variables." }, { "code": null, "e": 46305, "s": 46272, "text": "Consider the following example −" }, { "code": null, "e": 46584, "s": 46305, "text": "fn main(){\n let b:(i32,bool,f64) = (30,true,7.9);\n print(b);\n}\nfn print(x:(i32,bool,f64)){\n println!(\"Inside print method\");\n let (age,is_male,cgpa) = x; //assigns a tuple to \n distinct variables\n println!(\"Age is {} , isMale? {},cgpa is \n {}\",age,is_male,cgpa);\n}" }, { "code": null, "e": 46734, "s": 46584, "text": "Variable x is a tuple which is assigned to the let statement. Each variable - age, is_male and cgpa will contain the corresponding values in a tuple." }, { "code": null, "e": 46792, "s": 46734, "text": "Inside print method\nAge is 30 , isMale? true,cgpa is 7.9\n" }, { "code": null, "e": 46967, "s": 46792, "text": "In this chapter, we will learn about an array and the various features associated with it. Before we learn about arrays, let us see how an array is different from a variable." }, { "code": null, "e": 47010, "s": 46967, "text": "Variables have the following limitations −" }, { "code": null, "e": 47309, "s": 47010, "text": "Variables are scalar in nature. In other words, a variable declaration can only contain a single value at a time. This means that to store n values in a program n variable declaration will be needed. Hence, the use of variables is not feasible when one needs to store a larger collection of values." }, { "code": null, "e": 47608, "s": 47309, "text": "Variables are scalar in nature. In other words, a variable declaration can only contain a single value at a time. This means that to store n values in a program n variable declaration will be needed. Hence, the use of variables is not feasible when one needs to store a larger collection of values." }, { "code": null, "e": 47760, "s": 47608, "text": "Variables in a program are allocated memory in random order, thereby making it difficult to retrieve/read the values in the order of their declaration." }, { "code": null, "e": 47912, "s": 47760, "text": "Variables in a program are allocated memory in random order, thereby making it difficult to retrieve/read the values in the order of their declaration." }, { "code": null, "e": 48030, "s": 47912, "text": "An array is a homogeneous collection of values. Simply put, an array is a collection of values of the same data type." }, { "code": null, "e": 48077, "s": 48030, "text": "The features of an array are as listed below −" }, { "code": null, "e": 48134, "s": 48077, "text": "An array declaration allocates sequential memory blocks." }, { "code": null, "e": 48191, "s": 48134, "text": "An array declaration allocates sequential memory blocks." }, { "code": null, "e": 48271, "s": 48191, "text": "Arrays are static. This means that an array once initialized cannot be resized." }, { "code": null, "e": 48351, "s": 48271, "text": "Arrays are static. This means that an array once initialized cannot be resized." }, { "code": null, "e": 48398, "s": 48351, "text": "Each memory block represents an array element." }, { "code": null, "e": 48445, "s": 48398, "text": "Each memory block represents an array element." }, { "code": null, "e": 48539, "s": 48445, "text": "Array elements are identified by a unique integer called the subscript/ index of the element." }, { "code": null, "e": 48633, "s": 48539, "text": "Array elements are identified by a unique integer called the subscript/ index of the element." }, { "code": null, "e": 48697, "s": 48633, "text": "Populating the array elements is known as array initialization." }, { "code": null, "e": 48761, "s": 48697, "text": "Populating the array elements is known as array initialization." }, { "code": null, "e": 48832, "s": 48761, "text": "Array element values can be updated or modified but cannot be deleted." }, { "code": null, "e": 48903, "s": 48832, "text": "Array element values can be updated or modified but cannot be deleted." }, { "code": null, "e": 48974, "s": 48903, "text": "Use the syntax given below to declare and initialize an array in Rust." }, { "code": null, "e": 49182, "s": 48974, "text": "//Syntax1\nlet variable_name = [value1,value2,value3];\n\n//Syntax2\nlet variable_name:[dataType;size] = [value1,value2,value3];\n\n//Syntax3\nlet variable_name:[dataType;size] = [default_value_for_elements,size];\n" }, { "code": null, "e": 49304, "s": 49182, "text": "In the first syntax, type of the array is inferred from the data type of the array’s first element during initialization." }, { "code": null, "e": 49534, "s": 49304, "text": "The following example explicitly specifies the size and the data type of the array. The {:?} syntax of the println!() function is used to print all values in the array. The len() function is used to compute the size of the array." }, { "code": null, "e": 49661, "s": 49534, "text": "fn main(){\n let arr:[i32;4] = [10,20,30,40];\n println!(\"array is {:?}\",arr);\n println!(\"array size is :{}\",arr.len());\n}" }, { "code": null, "e": 49705, "s": 49661, "text": "array is [10, 20, 30, 40]\narray size is :4\n" }, { "code": null, "e": 49944, "s": 49705, "text": "The following program declares an array of 4 elements. The datatype is not explicitly specified during the variable declaration. In this case, the array will be of type integer. The len() function is used to compute the size of the array." }, { "code": null, "e": 50063, "s": 49944, "text": "fn main(){\n let arr = [10,20,30,40];\n println!(\"array is {:?}\",arr);\n println!(\"array size is :{}\",arr.len());\n}" }, { "code": null, "e": 50107, "s": 50063, "text": "array is [10, 20, 30, 40]\narray size is :4\n" }, { "code": null, "e": 50207, "s": 50107, "text": "The following example creates an array and initializes all its elements with a default value of -1." }, { "code": null, "e": 50328, "s": 50207, "text": "fn main() {\n let arr:[i32;4] = [-1;4];\n println!(\"array is {:?}\",arr);\n println!(\"array size is :{}\",arr.len());\n}" }, { "code": null, "e": 50372, "s": 50328, "text": "array is [-1, -1, -1, -1]\narray size is :4\n" }, { "code": null, "e": 50554, "s": 50372, "text": "The following example iterates through an array and prints the indexes and their corresponding values. The loop retrieves values from index 0 to 4 (index of the last array element)." }, { "code": null, "e": 50775, "s": 50554, "text": "fn main(){\n let arr:[i32;4] = [10,20,30,40];\n println!(\"array is {:?}\",arr);\n println!(\"array size is :{}\",arr.len());\n\n for index in 0..4 {\n println!(\"index is: {} & value is : {}\",index,arr[index]);\n }\n}" }, { "code": null, "e": 50931, "s": 50775, "text": "array is [10, 20, 30, 40]\narray size is :4\nindex is: 0 & value is : 10\nindex is: 1 & value is : 20\nindex is: 2 & value is : 30\nindex is: 3 & value is : 40\n" }, { "code": null, "e": 50995, "s": 50931, "text": "The iter() function fetches values of all elements in an array." }, { "code": null, "e": 51188, "s": 50995, "text": "fn main(){\n\nlet arr:[i32;4] = [10,20,30,40];\n println!(\"array is {:?}\",arr);\n println!(\"array size is :{}\",arr.len());\n\n for val in arr.iter(){\n println!(\"value is :{}\",val);\n }\n}" }, { "code": null, "e": 51284, "s": 51188, "text": "array is [10, 20, 30, 40]\narray size is :4\nvalue is :10\nvalue is :20\nvalue is :30\nvalue is :40\n" }, { "code": null, "e": 51435, "s": 51284, "text": "The mut keyword can be used to declare a mutable array. The following example declares a mutable array and modifies value of the second array element." }, { "code": null, "e": 51528, "s": 51435, "text": "fn main(){\n let mut arr:[i32;4] = [10,20,30,40];\n arr[1] = 0;\n println!(\"{:?}\",arr);\n}" }, { "code": null, "e": 51545, "s": 51528, "text": "[10, 0, 30, 40]\n" }, { "code": null, "e": 51607, "s": 51545, "text": "An array can be passed by value or by reference to functions." }, { "code": null, "e": 51809, "s": 51607, "text": "fn main() {\n let arr = [10,20,30];\n update(arr);\n\n print!(\"Inside main {:?}\",arr);\n}\nfn update(mut arr:[i32;3]){\n for i in 0..3 {\n arr[i] = 0;\n }\n println!(\"Inside update {:?}\",arr);\n}" }, { "code": null, "e": 51859, "s": 51809, "text": "Inside update [0, 0, 0]\nInside main [10, 20, 30]\n" }, { "code": null, "e": 52070, "s": 51859, "text": "fn main() {\n let mut arr = [10,20,30];\n update(&mut arr);\n print!(\"Inside main {:?}\",arr);\n}\nfn update(arr:&mut [i32;3]){\n for i in 0..3 {\n arr[i] = 0;\n }\n println!(\"Inside update {:?}\",arr);\n}" }, { "code": null, "e": 52117, "s": 52070, "text": "Inside update [0, 0, 0]\nInside main [0, 0, 0]\n" }, { "code": null, "e": 52203, "s": 52117, "text": "Let us consider an example given below to understand array declaration and constants." }, { "code": null, "e": 52325, "s": 52203, "text": "fn main() {\n let N: usize = 20;\n let arr = [0; N]; //Error: non-constant used with constant\n print!(\"{}\",arr[10])\n}" }, { "code": null, "e": 52572, "s": 52325, "text": "The compiler will result in an exception. This is because an array's length must be known at compile time. Here, the value of the variable \"N\" will be determined at runtime. In other words, variables cannot be used to define the size of an array." }, { "code": null, "e": 52614, "s": 52572, "text": "However, the following program is valid −" }, { "code": null, "e": 52719, "s": 52614, "text": "fn main() {\n const N: usize = 20; \n // pointer sized\n let arr = [0; N];\n\n print!(\"{}\",arr[10])\n}" }, { "code": null, "e": 52948, "s": 52719, "text": "The value of an identifier prefixed with the const keyword is defined at compile time and cannot be changed at runtime. usize is pointer-sized, thus its actual size depends on the architecture you are compiling your program for." }, { "code": null, "e": 53009, "s": 52948, "text": "The memory for a program can be allocated in the following −" }, { "code": null, "e": 53015, "s": 53009, "text": "Stack" }, { "code": null, "e": 53020, "s": 53015, "text": "Heap" }, { "code": null, "e": 53309, "s": 53020, "text": "A stack follows a last in first out order. Stack stores data values for which the size is known at compile time. For example, a variable of fixed size i32 is a candidate for stack allocation. Its size is known at compile time. All scalar types can be stored in stack as the size is fixed." }, { "code": null, "e": 53521, "s": 53309, "text": "Consider an example of a string, which is assigned a value at runtime. The exact size of such a string cannot be determined at compile time. So it is not a candidate for stack allocation but for heap allocation." }, { "code": null, "e": 53830, "s": 53521, "text": "The heap memory stores data values the size of which is unknown at compile time. It is used to store dynamic data. Simply put, a heap memory is allocated to data values that may change throughout the life cycle of the program. The heap is an area in the memory which is less organized when compared to stack." }, { "code": null, "e": 54041, "s": 53830, "text": "Each value in Rust has a variable that is called owner of the value. Every data stored in Rust will have an owner associated with it. For example, in the syntax − let age = 30, age is the owner of the value 30." }, { "code": null, "e": 54086, "s": 54041, "text": "Each data can have only one owner at a time." }, { "code": null, "e": 54131, "s": 54086, "text": "Each data can have only one owner at a time." }, { "code": null, "e": 54256, "s": 54131, "text": "Two variables cannot point to the same memory location. The variables will always be pointing to different memory locations." }, { "code": null, "e": 54381, "s": 54256, "text": "Two variables cannot point to the same memory location. The variables will always be pointing to different memory locations." }, { "code": null, "e": 54428, "s": 54381, "text": "The ownership of value can be transferred by −" }, { "code": null, "e": 54481, "s": 54428, "text": "Assigning value of one variable to another variable." }, { "code": null, "e": 54534, "s": 54481, "text": "Assigning value of one variable to another variable." }, { "code": null, "e": 54563, "s": 54534, "text": "Passing value to a function." }, { "code": null, "e": 54592, "s": 54563, "text": "Passing value to a function." }, { "code": null, "e": 54625, "s": 54592, "text": "Returning value from a function." }, { "code": null, "e": 54658, "s": 54625, "text": "Returning value from a function." }, { "code": null, "e": 54810, "s": 54658, "text": "The key selling point of Rust as a language is its memory safety. Memory safety is achieved by tight control on who can use what and when restrictions." }, { "code": null, "e": 54843, "s": 54810, "text": "Consider the following snippet −" }, { "code": null, "e": 55255, "s": 54843, "text": "fn main(){\n let v = vec![1,2,3]; \n // vector v owns the object in heap\n\n //only a single variable owns the heap memory at any given time\n let v2 = v; \n // here two variables owns heap value,\n //two pointers to the same content is not allowed in rust\n\n //Rust is very smart in terms of memory access ,so it detects a race condition\n //as two variables point to same heap\n\n println!(\"{:?}\",v);\n}" }, { "code": null, "e": 55637, "s": 55255, "text": "The above example declares a vector v. The idea of ownership is that only one variable binds to a resource, either v binds to resource or v2 binds to the resource. The above example throws an error − use of moved value: `v`. This is because the ownership of the resource is transferred to v2. It means the ownership is moved from v to v2 (v2=v) and v is invalidated after the move." }, { "code": null, "e": 55736, "s": 55637, "text": "The ownership of a value also changes when we pass an object in the heap to a closure or function." }, { "code": null, "e": 56071, "s": 55736, "text": "fn main(){\n let v = vec![1,2,3]; // vector v owns the object in heap\n let v2 = v; // moves ownership to v2\n display(v2); // v2 is moved to display and v2 is invalidated\n println!(\"In main {:?}\",v2); //v2 is No longer usable here\n}\nfn display(v:Vec<i32>){\n println!(\"inside display {:?}\",v);\n}" }, { "code": null, "e": 56246, "s": 56071, "text": "Ownership passed to the function will be invalidated as function execution completes. One work around for this is let the function return the owned object back to the caller." }, { "code": null, "e": 56559, "s": 56246, "text": "fn main(){\n let v = vec![1,2,3]; // vector v owns the object in heap\n let v2 = v; // moves ownership to v2\n let v2_return = display(v2); \n println!(\"In main {:?}\",v2_return);\n}\nfn display(v:Vec<i32>)->Vec<i32> { \n // returning same vector\n println!(\"inside display {:?}\",v);\n}" }, { "code": null, "e": 56785, "s": 56559, "text": "In case of primitive types, contents from one variable is copied to another. So, there is no ownership move happening. This is because a primitive variable needs less resources than an object. Consider the following example −" }, { "code": null, "e": 56895, "s": 56785, "text": "fn main(){\n let u1 = 10;\n let u2 = u1; // u1 value copied(not moved) to u2\n\n println!(\"u1 = {}\",u1);\n}" }, { "code": null, "e": 56920, "s": 56895, "text": "The output will be – 10." }, { "code": null, "e": 57186, "s": 56920, "text": "It is very inconvenient to pass the ownership of a variable to another function and then return the ownership. Rust supports a concept, borrowing, where the ownership of a value is transferred temporarily to an entity and then returned to the original owner entity." }, { "code": null, "e": 57211, "s": 57186, "text": "Consider the following −" }, { "code": null, "e": 57423, "s": 57211, "text": "fn main(){\n // a list of nos\n let v = vec![10,20,30];\n print_vector(v);\n println!(\"{}\",v[0]); // this line gives error\n}\nfn print_vector(x:Vec<i32>){\n println!(\"Inside print_vector function {:?}\",x);\n}" }, { "code": null, "e": 57726, "s": 57423, "text": "The main function invokes a function print_vector(). A vector is passed as parameter to this function. The ownership of the vector is also passed to the print_vector() function from the main(). The above code will result in an error as shown below when the main() function tries to access the vector v." }, { "code": null, "e": 57831, "s": 57726, "text": "| print_vector(v);\n| - value moved here\n| println!(\"{}\",v[0]);\n| ^ value used here after move\n" }, { "code": null, "e": 57985, "s": 57831, "text": "This is because a variable or value can no longer be used by the function that originally owned it once the ownership is transferred to another function." }, { "code": null, "e": 58409, "s": 57985, "text": "When a function transfers its control over a variable/value to another function temporarily, for a while, it is called borrowing. This is achieved by passing a reference to the variable (& var_name) rather than passing the variable/value itself to the function. The ownership of the variable/ value is transferred to the original owner of the variable after the function to which the control was passed completes execution." }, { "code": null, "e": 58655, "s": 58409, "text": "fn main(){\n // a list of nos\n let v = vec![10,20,30];\n print_vector(&v); // passing reference\n println!(\"Printing the value from main() v[0]={}\",v[0]);\n}\nfn print_vector(x:&Vec<i32>){\n println!(\"Inside print_vector function {:?}\",x);\n}" }, { "code": null, "e": 58739, "s": 58655, "text": "Inside print_vector function [10, 20, 30]\nPrinting the value from main() v[0] = 10\n" }, { "code": null, "e": 58929, "s": 58739, "text": "A function can modify a borrowed resource by using a mutable reference to such resource. A mutable reference is prefixed with &mut. Mutable references can operate only on mutable variables." }, { "code": null, "e": 59042, "s": 58929, "text": "fn add_one(e: &mut i32) {\n *e+= 1;\n}\nfn main() {\n let mut i = 3;\n add_one(&mut i);\n println!(\"{}\", i);\n}" }, { "code": null, "e": 59215, "s": 59042, "text": "The main() function declares a mutable integer variable i and passes a mutable reference of i to the add_one(). The add_one() increments the value of the variable i by one." }, { "code": null, "e": 59571, "s": 59215, "text": "fn main() {\n let mut name:String = String::from(\"TutorialsPoint\");\n display(&mut name); \n //pass a mutable reference of name\n println!(\"The value of name after modification is:{}\",name);\n}\nfn display(param_name:&mut String){\n println!(\"param_name value is :{}\",param_name);\n param_name.push_str(\" Rocks\"); \n //Modify the actual string,name\n}" }, { "code": null, "e": 59747, "s": 59571, "text": "The main() function passes a mutable reference of the variable name to the display() function. The display function appends an additional string to the original name variable." }, { "code": null, "e": 59845, "s": 59747, "text": "param_name value is :TutorialsPoint\nThe value of name after modification is:TutorialsPoint Rocks\n" }, { "code": null, "e": 60139, "s": 59845, "text": "A slice is a pointer to a block of memory. Slices can be used to access portions of data stored in contiguous memory blocks. It can be used with data structures like arrays, vectors and strings. Slices use index numbers to access portions of data. The size of a slice is determined at runtime." }, { "code": null, "e": 60256, "s": 60139, "text": "Slices are pointers to the actual data. They are passed by reference to functions, which is also known as borrowing." }, { "code": null, "e": 60495, "s": 60256, "text": "For example, slices can be used to fetch a portion of a string value. A sliced string is a pointer to the actual string object. Therefore, we need to specify the starting and ending index of a String. Index starts from 0 just like arrays." }, { "code": null, "e": 60555, "s": 60495, "text": "let sliced_value = &data_structure[start_index..end_index]\n" }, { "code": null, "e": 60709, "s": 60555, "text": "The minimum index value is 0 and the maximum index value is the size of the data structure. NOTE that the end_index will not be included in final string." }, { "code": null, "e": 60858, "s": 60709, "text": "The diagram below shows a sample string Tutorials, that has 9 characters. The index of the first character is 0 and that of the last character is 8." }, { "code": null, "e": 60939, "s": 60858, "text": "The following code fetches 5 characters from the string (starting from index 4)." }, { "code": null, "e": 61139, "s": 60939, "text": "fn main() {\n let n1 = \"Tutorials\".to_string();\n println!(\"length of string is {}\",n1.len());\n let c1 = &n1[4..9]; \n \n // fetches characters at 4,5,6,7, and 8 indexes\n println!(\"{}\",c1);\n}" }, { "code": null, "e": 61168, "s": 61139, "text": "length of string is 9\nrials\n" }, { "code": null, "e": 61437, "s": 61168, "text": "The main() function declares an array with 5 elements. It invokes the use_slice() function and passes to it a slice of three elements (points to the data array). The slices are passed by reference. The use_slice() function prints the value of the slice and its length." }, { "code": null, "e": 61740, "s": 61437, "text": "fn main(){\n let data = [10,20,30,40,50];\n use_slice(&data[1..4]);\n //this is effectively borrowing elements for a while\n}\nfn use_slice(slice:&[i32]) { \n // is taking a slice or borrowing a part of an array of i32s\n println!(\"length of slice is {:?}\",slice.len());\n println!(\"{:?}\",slice);\n}" }, { "code": null, "e": 61775, "s": 61740, "text": "length of slice is 3\n[20, 30, 40]\n" }, { "code": null, "e": 61833, "s": 61775, "text": "The &mut keyword can be used to mark a slice as mutable." }, { "code": null, "e": 62143, "s": 61833, "text": "fn main(){\n let mut data = [10,20,30,40,50];\n use_slice(&mut data[1..4]);\n // passes references of \n 20, 30 and 40\n println!(\"{:?}\",data);\n}\nfn use_slice(slice:&mut [i32]) {\n println!(\"length of slice is {:?}\",slice.len());\n println!(\"{:?}\",slice);\n slice[0] = 1010; // replaces 20 with 1010\n}" }, { "code": null, "e": 62201, "s": 62143, "text": "length of slice is 3\n[20, 30, 40]\n[10, 1010, 30, 40, 50]\n" }, { "code": null, "e": 62332, "s": 62201, "text": "The above code passes a mutable slice to the use_slice() function. The function modifies the second element of the original array." }, { "code": null, "e": 62604, "s": 62332, "text": "Arrays are used to represent a homogeneous collection of values. Similarly, a structure is another user defined data type available in Rust that allows us to combine data items of different types, including another structure. A structure defines data as a key-value pair." }, { "code": null, "e": 62884, "s": 62604, "text": "The struct keyword is used to declare a structure. Since structures are statically typed, every field in the structure must be associated with a data type. The naming rules and conventions for a structure is like that of a variable. The structure block must end with a semicolon." }, { "code": null, "e": 62976, "s": 62884, "text": "struct Name_of_structure {\n field1:data_type,\n field2:data_type,\n field3:data_type\n}\n" }, { "code": null, "e": 63074, "s": 62976, "text": "After declaring a struct, each field should be assigned a value. This is known as initialization." }, { "code": null, "e": 63616, "s": 63074, "text": "let instance_name = Name_of_structure {\n field1:value1,\n field2:value2,\n field3:value3\n}; \n//NOTE the semicolon\nSyntax: Accessing values in a structure\nUse the dot notation to access value of a specific field.\ninstance_name.field1\nIllustration\nstruct Employee {\n name:String,\n company:String,\n age:u32\n}\nfn main() {\n let emp1 = Employee {\n company:String::from(\"TutorialsPoint\"),\n name:String::from(\"Mohtashim\"),\n age:50\n };\n println!(\"Name is :{} company is {} age is {}\",emp1.name,emp1.company,emp1.age);\n}" }, { "code": null, "e": 63834, "s": 63616, "text": "The above example declares a struct Employee with three fields – name, company and age of types. The main() initializes the structure. It uses the println! macro to print values of the fields defined in the structure." }, { "code": null, "e": 63890, "s": 63834, "text": "Name is :Mohtashim company is TutorialsPoint age is 50\n" }, { "code": null, "e": 64088, "s": 63890, "text": "To modify an instance, the instance variable should be marked mutable. The below example declares and initializes a structure named Employee and later modifies value of the age field to 40 from 50." }, { "code": null, "e": 64302, "s": 64088, "text": "let mut emp1 = Employee {\n company:String::from(\"TutorialsPoint\"),\n name:String::from(\"Mohtashim\"),\n age:50\n};\nemp1.age = 40;\nprintln!(\"Name is :{} company is {} age is \n{}\",emp1.name,emp1.company,emp1.age);" }, { "code": null, "e": 64358, "s": 64302, "text": "Name is :Mohtashim company is TutorialsPoint age is 40\n" }, { "code": null, "e": 64516, "s": 64358, "text": "The following example shows how to pass instance of struct as a parameter. The display method takes an Employee instance as parameter and prints the details." }, { "code": null, "e": 64632, "s": 64516, "text": "fn display( emp:Employee) {\n println!(\"Name is :{} company is {} age is \n {}\",emp.name,emp.company,emp.age);\n}\n" }, { "code": null, "e": 64663, "s": 64632, "text": "Here is the complete program −" }, { "code": null, "e": 65328, "s": 64663, "text": "//declare a structure\nstruct Employee {\n name:String,\n company:String,\n age:u32\n}\nfn main() {\n //initialize a structure\n let emp1 = Employee {\n company:String::from(\"TutorialsPoint\"),\n name:String::from(\"Mohtashim\"),\n age:50\n };\n let emp2 = Employee{\n company:String::from(\"TutorialsPoint\"),\n name:String::from(\"Kannan\"),\n age:32\n };\n //pass emp1 and emp2 to display()\n display(emp1);\n display(emp2);\n}\n// fetch values of specific structure fields using the \n// operator and print it to the console\nfn display( emp:Employee){\n println!(\"Name is :{} company is {} age is \n {}\",emp.name,emp.company,emp.age);\n}" }, { "code": null, "e": 65436, "s": 65328, "text": "Name is :Mohtashim company is TutorialsPoint age is 50\nName is :Kannan company is TutorialsPoint age is 32\n" }, { "code": null, "e": 65539, "s": 65436, "text": "Let us consider a function who_is_elder(), which compares two employees age and returns the elder one." }, { "code": null, "e": 65680, "s": 65539, "text": "fn who_is_elder (emp1:Employee,emp2:Employee)->Employee {\n if emp1.age>emp2.age {\n return emp1;\n } else {\n return emp2;\n }\n}" }, { "code": null, "e": 65711, "s": 65680, "text": "Here is the complete program −" }, { "code": null, "e": 66584, "s": 65711, "text": "fn main() {\n //initialize structure\n let emp1 = Employee{\n company:String::from(\"TutorialsPoint\"),\n name:String::from(\"Mohtashim\"),\n age:50\n };\n let emp2 = Employee {\n company:String::from(\"TutorialsPoint\"),\n name:String::from(\"Kannan\"),\n age:32\n };\n let elder = who_is_elder(emp1,emp2);\n println!(\"elder is:\");\n\n //prints details of the elder employee\n display(elder);\n}\n//accepts instances of employee structure and compares their age\nfn who_is_elder (emp1:Employee,emp2:Employee)->Employee {\n if emp1.age>emp2.age {\n return emp1;\n } else {\n return emp2;\n }\n}\n//display name, comapny and age of the employee\nfn display( emp:Employee) {\n println!(\"Name is :{} company is {} age is {}\",emp.name,emp.company,emp.age);\n}\n//declare a structure\nstruct Employee {\n name:String,\n company:String,\n age:u32\n}" }, { "code": null, "e": 66650, "s": 66584, "text": "elder is:\nName is :Mohtashim company is TutorialsPoint age is 50\n" }, { "code": null, "e": 66827, "s": 66650, "text": "Methods are like functions. They are a logical group of programming instructions. Methods are declared with the fn keyword. The scope of a method is within the structure block." }, { "code": null, "e": 67117, "s": 66827, "text": "Methods are declared outside the structure block. The impl keyword is used to define a method within the context of a structure. The first parameter of a method will be always self, which represents the calling instance of the structure. Methods operate on the data members of a structure." }, { "code": null, "e": 67238, "s": 67117, "text": "To invoke a method, we need to first instantiate the structure. The method can be called using the structure's instance." }, { "code": null, "e": 67361, "s": 67238, "text": "struct My_struct {}\nimpl My_struct { \n //set the method's context\n fn method_name() { \n //define a method\n }\n}\n" }, { "code": null, "e": 67611, "s": 67361, "text": "The following example defines a structure Rectangle with fields − width and height. A method area is defined within the structure's context. The area method accesses the structure's fields via the self keyword and calculates the area of a rectangle." }, { "code": null, "e": 68144, "s": 67611, "text": "//define dimensions of a rectangle\nstruct Rectangle {\n width:u32, height:u32\n}\n\n//logic to calculate area of a rectangle\nimpl Rectangle {\n fn area(&self)->u32 {\n //use the . operator to fetch the value of a field via the self keyword\n self.width * self.height\n }\n}\n\nfn main() {\n // instanatiate the structure\n let small = Rectangle {\n width:10,\n height:20\n };\n //print the rectangle's area\n println!(\"width is {} height is {} area of Rectangle \n is {}\",small.width,small.height,small.area());\n}" }, { "code": null, "e": 68195, "s": 68144, "text": "width is 10 height is 20 area of Rectangle is 200\n" }, { "code": null, "e": 68474, "s": 68195, "text": "Static methods can be used as utility methods. These methods exist even before the structure is instantiated. Static methods are invoked using the structure's name and can be accessed without an instance. Unlike normal methods, a static method will not take the &self parameter." }, { "code": null, "e": 68558, "s": 68474, "text": "A static method like functions and other methods can optionally contain parameters." }, { "code": null, "e": 68746, "s": 68558, "text": "impl Structure_Name {\n //static method that creates objects of the Point structure\n fn method_name(param1: datatype, param2: datatype) -> return_type {\n // logic goes here\n }\n}" }, { "code": null, "e": 68810, "s": 68746, "text": "The structure_name :: syntax is used to access a static method." }, { "code": null, "e": 68846, "s": 68810, "text": "structure_name::method_name(v1,v2)\n" }, { "code": null, "e": 68974, "s": 68846, "text": "The following example uses the getInstance method as a factory class that creates and returns instances of the structure Point." }, { "code": null, "e": 69407, "s": 68974, "text": "//declare a structure\nstruct Point {\n x: i32,\n y: i32,\n}\nimpl Point {\n //static method that creates objects of the Point structure\n fn getInstance(x: i32, y: i32) -> Point {\n Point { x: x, y: y }\n }\n //display values of the structure's field\n fn display(&self){\n println!(\"x ={} y={}\",self.x,self.y );\n }\n}\nfn main(){\n // Invoke the static method\n let p1 = Point::getInstance(10,20);\n p1.display();\n}" }, { "code": null, "e": 69419, "s": 69407, "text": "x =10 y=20\n" }, { "code": null, "e": 69624, "s": 69419, "text": "In Rust programming, when we have to select a value from a list of possible variants we use enumeration data types. An enumerated type is declared using the enum keyword. Following is the syntax of enum −" }, { "code": null, "e": 69682, "s": 69624, "text": "enum enum_name {\n variant1,\n variant2,\n variant3\n}\n" }, { "code": null, "e": 69974, "s": 69682, "text": "The example declares an enum − GenderCategory, which has variants as Male and Female. The print! macro displays value of the enum. The compiler will throw an error the trait std::fmt::Debug is not implemented for GenderCategory. The attribute #[derive(Debug)] is used to suppress this error." }, { "code": null, "e": 70304, "s": 69974, "text": "// The `derive` attribute automatically creates the implementation\n// required to make this `enum` printable with `fmt::Debug`.\n#[derive(Debug)]\nenum GenderCategory {\n Male,Female\n}\nfn main() {\n let male = GenderCategory::Male;\n let female = GenderCategory::Female;\n\n println!(\"{:?}\",male);\n println!(\"{:?}\",female);\n}\n" }, { "code": null, "e": 70317, "s": 70304, "text": "Male\nFemale\n" }, { "code": null, "e": 70485, "s": 70317, "text": "The following example defines a structure Person. The field gender is of the type GenderCategory (which is an enum) and can be assigned either Male or Female as value." }, { "code": null, "e": 71136, "s": 70485, "text": "// The `derive` attribute automatically creates the \nimplementation\n// required to make this `enum` printable with \n`fmt::Debug`.\n\n#[derive(Debug)]\nenum GenderCategory {\n Male,Female\n}\n\n// The `derive` attribute automatically creates the implementation\n// required to make this `struct` printable with `fmt::Debug`.\n#[derive(Debug)]\nstruct Person {\n name:String,\n gender:GenderCategory\n}\n\nfn main() {\n let p1 = Person {\n name:String::from(\"Mohtashim\"),\n gender:GenderCategory::Male\n };\n let p2 = Person {\n name:String::from(\"Amy\"),\n gender:GenderCategory::Female\n };\n println!(\"{:?}\",p1);\n println!(\"{:?}\",p2);\n}" }, { "code": null, "e": 71264, "s": 71136, "text": "The example creates objects p1 and p2 of type Person and initializes the attributes, name and gender for each of these objects." }, { "code": null, "e": 71347, "s": 71264, "text": "Person { name: \"Mohtashim\", gender: Male }\nPerson { name: \"Amy\", gender: Female }\n" }, { "code": null, "e": 71453, "s": 71347, "text": "Option is a predefined enum in the Rust standard library. This enum has two values − Some(data) and None." }, { "code": null, "e": 71601, "s": 71453, "text": "enum Option<T> {\n Some(T), //used to return a value\n None // used to return null, as Rust doesn't support \n the null keyword\n}\n" }, { "code": null, "e": 71648, "s": 71601, "text": "Here, the type T represents value of any type." }, { "code": null, "e": 71837, "s": 71648, "text": "Rust does not support the null keyword. The value None, in the enumOption, can be used by a function to return a null value. If there is data to return, the function can return Some(data)." }, { "code": null, "e": 71878, "s": 71837, "text": "Let us understand this with an example −" }, { "code": null, "e": 72093, "s": 71878, "text": "The program defines a function is_even(), with a return type Option. The function verifies if the value passed is an even number. If the input is even, then a value true is returned, else the function returns None." }, { "code": null, "e": 72296, "s": 72093, "text": "fn main() {\n let result = is_even(3);\n println!(\"{:?}\",result);\n println!(\"{:?}\",is_even(30));\n}\nfn is_even(no:i32)->Option<bool> {\n if no%2 == 0 {\n Some(true)\n } else {\n None\n }\n}" }, { "code": null, "e": 72313, "s": 72296, "text": "None\nSome(true)\n" }, { "code": null, "e": 72592, "s": 72313, "text": "The match statement can be used to compare values stored in an enum. The following example defines a function, print_size, which takes CarType enum as parameter. The function compares the parameter values with a pre-defined set of constants and displays the appropriate message." }, { "code": null, "e": 73022, "s": 72592, "text": "enum CarType {\n Hatch,\n Sedan,\n SUV\n}\nfn print_size(car:CarType) {\n match car {\n CarType::Hatch => {\n println!(\"Small sized car\");\n },\n CarType::Sedan => {\n println!(\"medium sized car\");\n },\n CarType::SUV =>{\n println!(\"Large sized Sports Utility car\");\n }\n }\n}\nfn main(){\n print_size(CarType::SUV);\n print_size(CarType::Hatch);\n print_size(CarType::Sedan);\n}" }, { "code": null, "e": 73087, "s": 73022, "text": "Large sized Sports Utility car\nSmall sized car\nmedium sized car\n" }, { "code": null, "e": 73209, "s": 73087, "text": "The example of is_even function, which returns Option type, can also be implemented with match statement as shown below −" }, { "code": null, "e": 73505, "s": 73209, "text": "fn main() {\n match is_even(5) {\n Some(data) => {\n if data==true {\n println!(\"Even no\");\n }\n },\n None => {\n println!(\"not even\");\n }\n }\n}\nfn is_even(no:i32)->Option<bool> {\n if no%2 == 0 {\n Some(true)\n } else {\n None\n }\n}" }, { "code": null, "e": 73515, "s": 73505, "text": "not even\n" }, { "code": null, "e": 73772, "s": 73515, "text": "It is possible to add data type to each variant of an enum. In the following example, Name and Usr_ID variants of the enum are of String and integer types respectively. The following example shows the use of match statement with an enum having a data type." }, { "code": null, "e": 74301, "s": 73772, "text": "// The `derive` attribute automatically creates the implementation\n// required to make this `enum` printable with `fmt::Debug`.\n#[derive(Debug)]\nenum GenderCategory {\n Name(String),Usr_ID(i32)\n}\nfn main() {\n let p1 = GenderCategory::Name(String::from(\"Mohtashim\"));\n let p2 = GenderCategory::Usr_ID(100);\n println!(\"{:?}\",p1);\n println!(\"{:?}\",p2);\n\n match p1 {\n GenderCategory::Name(val)=> {\n println!(\"{}\",val);\n }\n GenderCategory::Usr_ID(val)=> {\n println!(\"{}\",val);\n }\n }\n}" }, { "code": null, "e": 74342, "s": 74301, "text": "Name(\"Mohtashim\")\nUsr_ID(100)\nMohtashim\n" }, { "code": null, "e": 75043, "s": 74342, "text": "A logical group of code is called a Module. Multiple modules are compiled into a unit called crate. Rust programs may contain a binary crate or a library crate. A binary crate is an executable project that has a main() method. A library crate is a group of components that can be reused in other projects. Unlike a binary crate, a library crate does not have an entry point (main() method). The Cargo tool is used to manage crates in Rust. For example, the network module contains networking related functions and the graphics module contains drawing-related functions. Modules are similar to namespaces in other programming languages. Third-party crates can be downloaded using cargo from crates.io." }, { "code": null, "e": 75049, "s": 75043, "text": "crate" }, { "code": null, "e": 75120, "s": 75049, "text": "Is a compilation unit in Rust; Crate is compiled to binary or library." }, { "code": null, "e": 75126, "s": 75120, "text": "cargo" }, { "code": null, "e": 75180, "s": 75126, "text": "The official Rust package management tool for crates." }, { "code": null, "e": 75187, "s": 75180, "text": "module" }, { "code": null, "e": 75225, "s": 75187, "text": "Logically groups code within a crate." }, { "code": null, "e": 75235, "s": 75225, "text": "crates.io" }, { "code": null, "e": 75271, "s": 75235, "text": "The official Rust package registry." }, { "code": null, "e": 75512, "s": 75271, "text": "//public module\npub mod a_public_module {\n pub fn a_public_function() {\n //public function\n }\n fn a_private_function() {\n //private function\n }\n}\n//private module\nmod a_private_module {\n fn a_private_function() {\n }\n}\n" }, { "code": null, "e": 75856, "s": 75512, "text": "Modules can be public or private. Components in a private module cannot be accessed by other modules. Modules in Rust are private by default. On the contrary, functions in a public module can be accessed by other modules. Modules should be prefixed with pub keyword to make it public. Functions within a public module must also be made public." }, { "code": null, "e": 75987, "s": 75856, "text": "The example defines a public module − movies. The module contains a function play() that accepts a parameter and prints its value." }, { "code": null, "e": 76144, "s": 75987, "text": "pub mod movies {\n pub fn play(name:String) {\n println!(\"Playing movie {}\",name);\n }\n}\nfn main(){\n movies::play(\"Herold and Kumar\".to_string());\n}" }, { "code": null, "e": 76176, "s": 76144, "text": "Playing movie Herold and Kumar\n" }, { "code": null, "e": 76225, "s": 76176, "text": "The use keyword helps to import a public module." }, { "code": null, "e": 76265, "s": 76225, "text": "use public_module_name::function_name;\n" }, { "code": null, "e": 76433, "s": 76265, "text": "pub mod movies {\n pub fn play(name:String) {\n println!(\"Playing movie {}\",name);\n }\n}\nuse movies::play;\nfn main(){\n play(\"Herold and Kumar \".to_string());\n}" }, { "code": null, "e": 76465, "s": 76433, "text": "Playing movie Herold and Kumar\n" }, { "code": null, "e": 76683, "s": 76465, "text": "Modules can also be nested. The comedy module is nested within the english module, which is further nested in the movies module. The example given below defines a function play inside the movies/english/comedy module." }, { "code": null, "e": 77124, "s": 76683, "text": "pub mod movies {\n pub mod english {\n pub mod comedy {\n pub fn play(name:String) {\n println!(\"Playing comedy movie {}\",name);\n }\n }\n }\n}\nuse movies::english::comedy::play; \n// importing a public module\n\nfn main() {\n // short path syntax\n play(\"Herold and Kumar\".to_string());\n play(\"The Hangover\".to_string());\n\n //full path syntax\n movies::english::comedy::play(\"Airplane!\".to_string());\n}" }, { "code": null, "e": 77228, "s": 77124, "text": "Playing comedy movie Herold and Kumar\nPlaying comedy movie The Hangover\nPlaying comedy movie Airplane!\n" }, { "code": null, "e": 77373, "s": 77228, "text": "Let us create a library crate named movie_lib, which contains a module movies. To build the movie_lib library crate, we will use the tool cargo." }, { "code": null, "e": 77744, "s": 77373, "text": "Create a folder movie-app followed by a sub-folder movie-lib. After the folder and sub-folder are created, create an src folder and a Cargo.toml file in this directory. The source code should go in the src folder. Create the files lib.rs and movies.rs in the src folder. The Cargo.toml file will contain the metadata of the project like version number, author name, etc." }, { "code": null, "e": 77801, "s": 77744, "text": "The project directory structure will be as shown below −" }, { "code": null, "e": 77895, "s": 77801, "text": "movie-app\n movie-lib/\n -->Cargo.toml\n -->src/\n lib.rs\n movies.rs\n" }, { "code": null, "e": 77968, "s": 77895, "text": "[package]\nname = \"movies_lib\"\nversion = \"0.1.0\"\nauthors = [\"Mohtashim\"]\n" }, { "code": null, "e": 78018, "s": 77968, "text": "Add the following module definition to this file." }, { "code": null, "e": 78035, "s": 78018, "text": "pub mod movies;\n" }, { "code": null, "e": 78084, "s": 78035, "text": "The above line creates a public module − movies." }, { "code": null, "e": 78143, "s": 78084, "text": "This file will define all functions for the movies module." }, { "code": null, "e": 78222, "s": 78143, "text": "pub fn play(name:String){\n println!(\"Playing movie {} :movies-app\",name);\n}\n" }, { "code": null, "e": 78318, "s": 78222, "text": "The above code defines a function play() that accepts a parameter and prints it to the console." }, { "code": null, "e": 78553, "s": 78318, "text": "Build app using the cargo build command to verify if the library crate is structured properly. Make sure you are at root of project − the movie-app folder. The following message will be displayed in the terminal if the build succeeds." }, { "code": null, "e": 78705, "s": 78553, "text": "D:\\Rust\\movie-lib> cargo build\n Compiling movies_lib v0.1.0 (file:///D:/Rust/movie-lib)\n Finished dev [unoptimized + debuginfo] target(s) in 0.67s\n" }, { "code": null, "e": 79017, "s": 78705, "text": "Create another folder movie-lib-test in the movie-app folder followed by a Cargo.toml file and the src folder. This project should have main method as this is a binary crate, which will consume the library crate created previously. Create a main.rs file in the src folder. The folder structure will be as shown." }, { "code": null, "e": 79137, "s": 79017, "text": "movie-app\n movie-lib \n // already completed\n\n movie-lib-test/\n -->Cargo.toml\n -->src/\n main.rs\n" }, { "code": null, "e": 79273, "s": 79137, "text": "[package]\nname = \"test_for_movie_lib\"\nversion = \"0.1.0\"\nauthors = [\"Mohtashim\"]\n\n[dependencies]\nmovies_lib = { path = \"../movie-lib\" }\n" }, { "code": null, "e": 79398, "s": 79273, "text": "NOTE − The path to the library folder is set as dependencies. The following diagram shows the contents of both the projects." }, { "code": null, "e": 79543, "s": 79398, "text": "extern crate movies_lib;\nuse movies_lib::movies::play;\nfn main() {\n println!(\"inside main of test \");\n play(\"Tutorialspoint\".to_string())\n}\n" }, { "code": null, "e": 79671, "s": 79543, "text": "The above code imports an external package called movies_lib. Check the Cargo.toml of current project to verify the crate name." }, { "code": null, "e": 79773, "s": 79671, "text": "We will use the cargo build and cargo run to build the binary project and execute it as shown below −" }, { "code": null, "e": 80013, "s": 79773, "text": "Rust's standard collection library provides efficient implementations of the most common general-purpose programming data structures. This chapter discusses the implementation of the commonly used collections − Vector, HashMap and HashSet." }, { "code": null, "e": 80192, "s": 80013, "text": "A Vector is a resizable array. It stores values in contiguous memory blocks. The predefined structure Vec can be used to create vectors. Some important features of a Vector are −" }, { "code": null, "e": 80232, "s": 80192, "text": "A Vector can grow or shrink at runtime." }, { "code": null, "e": 80272, "s": 80232, "text": "A Vector can grow or shrink at runtime." }, { "code": null, "e": 80310, "s": 80272, "text": "A Vector is a homogeneous collection." }, { "code": null, "e": 80348, "s": 80310, "text": "A Vector is a homogeneous collection." }, { "code": null, "e": 80682, "s": 80348, "text": "A Vector stores data as sequence of elements in a particular order. Every element in a Vector is assigned a unique index number. The index starts from 0 and goes up to n-1 where, n is the size of the collection. For example, in a collection of 5 elements, the first element will be at index 0 and the last element will be at index 4." }, { "code": null, "e": 81016, "s": 80682, "text": "A Vector stores data as sequence of elements in a particular order. Every element in a Vector is assigned a unique index number. The index starts from 0 and goes up to n-1 where, n is the size of the collection. For example, in a collection of 5 elements, the first element will be at index 0 and the last element will be at index 4." }, { "code": null, "e": 81130, "s": 81016, "text": "A Vector will only append values to (or near) the end. In other words, a Vector can be used to implement a stack." }, { "code": null, "e": 81244, "s": 81130, "text": "A Vector will only append values to (or near) the end. In other words, a Vector can be used to implement a stack." }, { "code": null, "e": 81290, "s": 81244, "text": "Memory for a Vector is allocated in the heap." }, { "code": null, "e": 81336, "s": 81290, "text": "Memory for a Vector is allocated in the heap." }, { "code": null, "e": 81373, "s": 81336, "text": "let mut instance_name = Vec::new();\n" }, { "code": null, "e": 81454, "s": 81373, "text": "The static method new() of the Vecstructure is used to create a vector instance." }, { "code": null, "e": 81551, "s": 81454, "text": "Alternatively, a vector can also be created using the vec! macro. The syntax is as given below −" }, { "code": null, "e": 81591, "s": 81551, "text": "let vector_name = vec![val1,val2,val3]\n" }, { "code": null, "e": 81668, "s": 81591, "text": "The following table lists some commonly used functions of the Vec structure." }, { "code": null, "e": 81687, "s": 81668, "text": "pub fn new()->Vect" }, { "code": null, "e": 81780, "s": 81687, "text": "Constructs a new, empty Vec. The vector will not allocate until elements are pushed onto it." }, { "code": null, "e": 81813, "s": 81780, "text": "pub fn push(&mut self, value: T)" }, { "code": null, "e": 81861, "s": 81813, "text": "Appends an element to the back of a collection." }, { "code": null, "e": 81905, "s": 81861, "text": "pub fn remove(&mut self, index: usize) -> T" }, { "code": null, "e": 82018, "s": 81905, "text": "Removes and returns the element at position index within the vector, shifting all elements after it to the left." }, { "code": null, "e": 82056, "s": 82018, "text": "pub fn contains(&self, x: &T) -> bool" }, { "code": null, "e": 82124, "s": 82056, "text": "Returns true if the slice contains an element with the given value." }, { "code": null, "e": 82151, "s": 82124, "text": "pub fn len(&self) -> usize" }, { "code": null, "e": 82231, "s": 82151, "text": "Returns the number of elements in the vector, also referred to as its 'length'." }, { "code": null, "e": 82281, "s": 82231, "text": "To create a vector, we use the static method new−" }, { "code": null, "e": 82437, "s": 82281, "text": "fn main() {\n let mut v = Vec::new();\n v.push(20);\n v.push(30);\n v.push(40);\n\n println!(\"size of vector is :{}\",v.len());\n println!(\"{:?}\",v);\n}" }, { "code": null, "e": 82669, "s": 82437, "text": "The above example creates a Vector using the static method new() that is defined in structure Vec. The push(val) function appends the value passed as parameter to the collection. The len() function returns the length of the vector." }, { "code": null, "e": 82704, "s": 82669, "text": "size of vector is :3\n[20, 30, 40]\n" }, { "code": null, "e": 82842, "s": 82704, "text": "The following code creates a vector using the vec! macro. The data type of the vector is inferred the first value that is assigned to it." }, { "code": null, "e": 82903, "s": 82842, "text": "fn main() {\n let v = vec![1,2,3];\n println!(\"{:?}\",v);\n}" }, { "code": null, "e": 82914, "s": 82903, "text": "[1, 2, 3]\n" }, { "code": null, "e": 83065, "s": 82914, "text": "As mentioned earlier, a vector can only contain values of the same data type. The following snippet will throw a error[E0308]: mismatched types error." }, { "code": null, "e": 83134, "s": 83065, "text": "fn main() {\n let v = vec![1,2,3,\"hello\"];\n println!(\"{:?}\",v);\n}" }, { "code": null, "e": 83181, "s": 83134, "text": "Appends an element to the end of a collection." }, { "code": null, "e": 83294, "s": 83181, "text": "fn main() {\n let mut v = Vec::new();\n v.push(20);\n v.push(30);\n v.push(40);\n \n println!(\"{:?}\",v);\n}" }, { "code": null, "e": 83308, "s": 83294, "text": "[20, 30, 40]\n" }, { "code": null, "e": 83421, "s": 83308, "text": "Removes and returns the element at position index within the vector, shifting all elements after it to the left." }, { "code": null, "e": 83505, "s": 83421, "text": "fn main() {\n let mut v = vec![10,20,30];\n v.remove(1);\n println!(\"{:?}\",v);\n}" }, { "code": null, "e": 83515, "s": 83505, "text": "[10, 30]\n" }, { "code": null, "e": 83584, "s": 83515, "text": "Returns true if the slice contains an element with the given value −" }, { "code": null, "e": 83705, "s": 83584, "text": "fn main() {\n let v = vec![10,20,30];\n if v.contains(&10) {\n println!(\"found 10\");\n }\n println!(\"{:?}\",v);\n}" }, { "code": null, "e": 83728, "s": 83705, "text": "found 10\n[10, 20, 30]\n" }, { "code": null, "e": 83808, "s": 83728, "text": "Returns the number of elements in the vector, also referred to as its 'length'." }, { "code": null, "e": 83892, "s": 83808, "text": "fn main() {\n let v = vec![1,2,3];\n println!(\"size of vector is :{}\",v.len());\n}" }, { "code": null, "e": 83914, "s": 83892, "text": "size of vector is :3\n" }, { "code": null, "e": 84084, "s": 83914, "text": "Individual elements in a vector can be accessed using their corresponding index numbers. The following example creates a vector ad prints the value of the first element." }, { "code": null, "e": 84195, "s": 84084, "text": "fn main() {\n let mut v = Vec::new();\n v.push(20);\n v.push(30);\n\n println!(\"{:?}\",v[0]);\n}\nOutput: `20`" }, { "code": null, "e": 84269, "s": 84195, "text": "Values in a vector can also be fetched using reference to the collection." }, { "code": null, "e": 84441, "s": 84269, "text": "fn main() {\n let mut v = Vec::new();\n v.push(20);\n v.push(30);\n v.push(40);\n v.push(500);\n\n for i in &v {\n println!(\"{}\",i);\n }\n println!(\"{:?}\",v);\n}" }, { "code": null, "e": 84473, "s": 84441, "text": "20\n30\n40\n500\n[20, 30, 40, 500]\n" }, { "code": null, "e": 84907, "s": 84473, "text": "A map is a collection of key-value pairs (called entries). No two entries in a map can have the same key. In short, a map is a lookup table. A HashMap stores the keys and values in a hash table. The entries are stored in an arbitrary order. The key is used to search for values in the HashMap. The HashMap structure is defined in the std::collections module. This module should be explicitly imported to access the HashMap structure." }, { "code": null, "e": 84948, "s": 84907, "text": "let mut instance_name = HashMap::new();\n" }, { "code": null, "e": 85071, "s": 84948, "text": "The static method new() of the HashMap structure is used to create a HashMap object. This method creates an empty HashMap." }, { "code": null, "e": 85132, "s": 85071, "text": "The commonly used functions of HashMap are discussed below −" }, { "code": null, "e": 85179, "s": 85132, "text": "pub fn insert(&mut self, k: K, v: V) -> Option" }, { "code": null, "e": 85275, "s": 85179, "text": "Inserts a key/value pair, if no key then None is returned. After update, old value is returned." }, { "code": null, "e": 85302, "s": 85275, "text": "pub fn len(&self) -> usize" }, { "code": null, "e": 85345, "s": 85302, "text": "Returns the number of elements in the map." }, { "code": null, "e": 85422, "s": 85345, "text": "pub fn get<Q: ?Sized>(&lself, k: &Q) -> Option<&V> where K:Borrow Q:Hash+ Eq" }, { "code": null, "e": 85481, "s": 85422, "text": "Returns a reference to the value corresponding to the key." }, { "code": null, "e": 85514, "s": 85481, "text": "pub fn iter(&self) -> Iter<K, V>" }, { "code": null, "e": 85620, "s": 85514, "text": "An iterator visiting all key-value pairs in arbitrary order. The iterator element type is (&'a K, &'a V)." }, { "code": null, "e": 85673, "s": 85620, "text": "pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool" }, { "code": null, "e": 85737, "s": 85673, "text": "Returns true if the map contains a value for the specified key." }, { "code": null, "e": 85804, "s": 85737, "text": "pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)>" }, { "code": null, "e": 85905, "s": 85804, "text": "Removes a key from the map, returning the stored key and value if the key was previously in the map." }, { "code": null, "e": 85948, "s": 85905, "text": "Inserts a key/value pair into the HashMap." }, { "code": null, "e": 86143, "s": 85948, "text": "use std::collections::HashMap;\nfn main(){\n let mut stateCodes = HashMap::new();\n stateCodes.insert(\"KL\",\"Kerala\");\n stateCodes.insert(\"MH\",\"Maharashtra\");\n println!(\"{:?}\",stateCodes);\n}" }, { "code": null, "e": 86222, "s": 86143, "text": "The above program creates a HashMap and initializes it with 2 key-value pairs." }, { "code": null, "e": 86261, "s": 86222, "text": "{\"KL\": \"Kerala\", \"MH\": \"Maharashtra\"}\n" }, { "code": null, "e": 86303, "s": 86261, "text": "Returns the number of elements in the map" }, { "code": null, "e": 86518, "s": 86303, "text": "use std::collections::HashMap;\nfn main() {\n let mut stateCodes = HashMap::new();\n stateCodes.insert(\"KL\",\"Kerala\");\n stateCodes.insert(\"MH\",\"Maharashtra\");\n println!(\"size of map is {}\",stateCodes.len());\n}" }, { "code": null, "e": 86601, "s": 86518, "text": "The above example creates a HashMap and prints the total number of elements in it." }, { "code": null, "e": 86619, "s": 86601, "text": "size of map is 2\n" }, { "code": null, "e": 86747, "s": 86619, "text": "Returns a reference to the value corresponding to the key. The following example retrieves the value for key KL in the HashMap." }, { "code": null, "e": 87174, "s": 86747, "text": "use std::collections::HashMap;\nfn main() {\n let mut stateCodes = HashMap::new();\n stateCodes.insert(\"KL\",\"Kerala\");\n stateCodes.insert(\"MH\",\"Maharashtra\");\n println!(\"size of map is {}\",stateCodes.len());\n println!(\"{:?}\",stateCodes);\n\n match stateCodes.get(&\"KL\") {\n Some(value)=> {\n println!(\"Value for key KL is {}\",value);\n }\n None => {\n println!(\"nothing found\");\n }\n }\n}" }, { "code": null, "e": 87257, "s": 87174, "text": "size of map is 2\n{\"KL\": \"Kerala\", \"MH\": \"Maharashtra\"}\nValue for key KL is Kerala\n" }, { "code": null, "e": 87344, "s": 87257, "text": "Returns an iterator containing reference to all key-value pairs in an arbitrary order." }, { "code": null, "e": 87600, "s": 87344, "text": "use std::collections::HashMap;\nfn main() {\n let mut stateCodes = HashMap::new();\n stateCodes.insert(\"KL\",\"Kerala\");\n stateCodes.insert(\"MH\",\"Maharashtra\");\n\n for (key, val) in stateCodes.iter() {\n println!(\"key: {} val: {}\", key, val);\n }\n}" }, { "code": null, "e": 87646, "s": 87600, "text": "key: MH val: Maharashtra\nkey: KL val: Kerala\n" }, { "code": null, "e": 87710, "s": 87646, "text": "Returns true if the map contains a value for the specified key." }, { "code": null, "e": 87986, "s": 87710, "text": "use std::collections::HashMap;\nfn main() {\n let mut stateCodes = HashMap::new();\n stateCodes.insert(\"KL\",\"Kerala\");\n stateCodes.insert(\"MH\",\"Maharashtra\");\n stateCodes.insert(\"GJ\",\"Gujarat\");\n\n if stateCodes.contains_key(&\"GJ\") {\n println!(\"found key\");\n }\n}" }, { "code": null, "e": 87997, "s": 87986, "text": "found key\n" }, { "code": null, "e": 88025, "s": 87997, "text": "Removes a key from the map." }, { "code": null, "e": 88388, "s": 88025, "text": "use std::collections::HashMap;\nfn main() {\n let mut stateCodes = HashMap::new();\n stateCodes.insert(\"KL\",\"Kerala\");\n stateCodes.insert(\"MH\",\"Maharashtra\");\n stateCodes.insert(\"GJ\",\"Gujarat\");\n\n println!(\"length of the hashmap {}\",stateCodes.len());\n stateCodes.remove(&\"GJ\");\n println!(\"length of the hashmap after remove() {}\",stateCodes.len());\n}" }, { "code": null, "e": 88452, "s": 88388, "text": "length of the hashmap 3\nlength of the hashmap after remove() 2\n" }, { "code": null, "e": 88739, "s": 88452, "text": "HashSet is a set of unique values of type T. Adding and removing values is fast, and it is fast to ask whether a given value is in the set or not. The HashSet structure is defined in the std::collections module. This module should be explicitly imported to access the HashSet structure." }, { "code": null, "e": 88780, "s": 88739, "text": "let mut hash_set_name = HashSet::new();\n" }, { "code": null, "e": 88892, "s": 88780, "text": "The static method, new, of HashSet structure is used to create a HashSet. This method creates an empty HashSet." }, { "code": null, "e": 88978, "s": 88892, "text": "The following table lists some of the commonly used methods of the HashSet structure." }, { "code": null, "e": 89021, "s": 88978, "text": "pub fn insert(&mut self, value: T) -> bool" }, { "code": null, "e": 89119, "s": 89021, "text": "Adds a value to the set. If the set did not have this value present, true is returned else false." }, { "code": null, "e": 89146, "s": 89119, "text": "pub fn len(&self) -> usize" }, { "code": null, "e": 89189, "s": 89146, "text": "Returns the number of elements in the set." }, { "code": null, "e": 89272, "s": 89189, "text": "pub fn get<Q:?Sized>(&self, value: &Q) -> Option<&T> where T: Borrow,Q: Hash + Eq," }, { "code": null, "e": 89358, "s": 89272, "text": "Returns a reference to the value in the set, if any that is equal to the given value." }, { "code": null, "e": 89385, "s": 89358, "text": "pub fn iter(&self) -> Iter" }, { "code": null, "e": 89483, "s": 89385, "text": "Returns an iterator visiting all elements in arbitrary order. The iterator element type is &'a T." }, { "code": null, "e": 89536, "s": 89483, "text": "pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool" }, { "code": null, "e": 89578, "s": 89536, "text": "Returns true if the set contains a value." }, { "code": null, "e": 89633, "s": 89578, "text": "pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool" }, { "code": null, "e": 89713, "s": 89633, "text": "Removes a value from the set. Returns true if the value was present in the set." }, { "code": null, "e": 89797, "s": 89713, "text": "Adds a value to the set. A HashSet does not add duplicate values to the collection." }, { "code": null, "e": 90050, "s": 89797, "text": "use std::collections::HashSet;\nfn main() {\n let mut names = HashSet::new();\n\n names.insert(\"Mohtashim\");\n names.insert(\"Kannan\");\n names.insert(\"TutorialsPoint\");\n names.insert(\"Mohtashim\");//duplicates not added\n\n println!(\"{:?}\",names);\n}" }, { "code": null, "e": 90093, "s": 90050, "text": "{\"TutorialsPoint\", \"Kannan\", \"Mohtashim\"}\n" }, { "code": null, "e": 90136, "s": 90093, "text": "Returns the number of elements in the set." }, { "code": null, "e": 90358, "s": 90136, "text": "use std::collections::HashSet;\nfn main() {\n let mut names = HashSet::new();\n names.insert(\"Mohtashim\");\n names.insert(\"Kannan\");\n names.insert(\"TutorialsPoint\");\n println!(\"size of the set is {}\",names.len());\n}" }, { "code": null, "e": 90380, "s": 90358, "text": "size of the set is 3\n" }, { "code": null, "e": 90442, "s": 90380, "text": "Retruns an iterator visiting all elements in arbitrary order." }, { "code": null, "e": 90707, "s": 90442, "text": "use std::collections::HashSet;\nfn main() {\n let mut names = HashSet::new();\n names.insert(\"Mohtashim\");\n names.insert(\"Kannan\");\n names.insert(\"TutorialsPoint\");\n names.insert(\"Mohtashim\");\n\n for name in names.iter() {\n println!(\"{}\",name);\n }\n}" }, { "code": null, "e": 90740, "s": 90707, "text": "TutorialsPoint\nMohtashim\nKannan\n" }, { "code": null, "e": 90828, "s": 90740, "text": "Returns a reference to the value in the set, if any, which is equal to the given value." }, { "code": null, "e": 91218, "s": 90828, "text": "use std::collections::HashSet;\nfn main() {\n let mut names = HashSet::new();\n names.insert(\"Mohtashim\");\n names.insert(\"Kannan\");\n names.insert(\"TutorialsPoint\");\n names.insert(\"Mohtashim\");\n\n match names.get(&\"Mohtashim\"){\n Some(value)=>{\n println!(\"found {}\",value);\n }\n None =>{\n println!(\"not found\");\n }\n }\n println!(\"{:?}\",names);\n}" }, { "code": null, "e": 91277, "s": 91218, "text": "found Mohtashim\n{\"Kannan\", \"Mohtashim\", \"TutorialsPoint\"}\n" }, { "code": null, "e": 91319, "s": 91277, "text": "Returns true if the set contains a value." }, { "code": null, "e": 91564, "s": 91319, "text": "use std::collections::HashSet;\n\nfn main() {\n let mut names = HashSet::new();\n names.insert(\"Mohtashim\");\n names.insert(\"Kannan\");\n names.insert(\"TutorialsPoint\");\n\n if names.contains(&\"Kannan\") {\n println!(\"found name\");\n } \n}" }, { "code": null, "e": 91576, "s": 91564, "text": "found name\n" }, { "code": null, "e": 91606, "s": 91576, "text": "Removes a value from the set." }, { "code": null, "e": 91931, "s": 91606, "text": "use std::collections::HashSet;\n\nfn main() {\n let mut names = HashSet::new();\n names.insert(\"Mohtashim\");\n names.insert(\"Kannan\");\n names.insert(\"TutorialsPoint\");\n println!(\"length of the Hashset: {}\",names.len());\n names.remove(&\"Kannan\");\n println!(\"length of the Hashset after remove() : {}\",names.len());\n}" }, { "code": null, "e": 91998, "s": 91931, "text": "length of the Hashset: 3\nlength of the Hashset after remove() : 2\n" }, { "code": null, "e": 92087, "s": 91998, "text": "In Rust, errors can be classified into two major categories as shown in the table below." }, { "code": null, "e": 92099, "s": 92087, "text": "Recoverable" }, { "code": null, "e": 92127, "s": 92099, "text": "Errors which can be handled" }, { "code": null, "e": 92141, "s": 92127, "text": "UnRecoverable" }, { "code": null, "e": 92172, "s": 92141, "text": "Errors which cannot be handled" }, { "code": null, "e": 92468, "s": 92172, "text": "A recoverable error is an error that can be corrected. A program can retry the failed operation or specify an alternate course of action when it encounters a recoverable error. Recoverable errors do not cause a program to fail abruptly. An example of a recoverable error is File Not Found error." }, { "code": null, "e": 92753, "s": 92468, "text": "Unrecoverable errors cause a program to fail abruptly. A program cannot revert to its normal state if an unrecoverable error occurs. It cannot retry the failed operation or undo the error. An example of an unrecoverable error is trying to access a location beyond the end of an array." }, { "code": null, "e": 93010, "s": 92753, "text": "Unlike other programming languages, Rust does not have exceptions. It returns an enum Result<T, E> for recoverable errors, while it calls the panic macro if the program encounters an unrecoverable error. The panic macro causes the program to exit abruptly." }, { "code": null, "e": 93181, "s": 93010, "text": "panic! macro allows a program to terminate immediately and provide feedback to the caller of the program. It should be used when a program reaches an unrecoverable state." }, { "code": null, "e": 93267, "s": 93181, "text": "fn main() {\n panic!(\"Hello\");\n println!(\"End of main\"); //unreachable statement\n}" }, { "code": null, "e": 93365, "s": 93267, "text": "In the above example, the program will terminate immediately when it encounters the panic! macro." }, { "code": null, "e": 93411, "s": 93365, "text": "thread 'main' panicked at 'Hello', main.rs:3\n" }, { "code": null, "e": 93509, "s": 93411, "text": "fn main() {\n let a = [10,20,30];\n a[10]; //invokes a panic since index 10 cannot be reached\n}" }, { "code": null, "e": 93536, "s": 93509, "text": "Output is as shown below −" }, { "code": null, "e": 93831, "s": 93536, "text": "warning: this expression will panic at run-time\n--> main.rs:4:4\n |\n4 | a[10];\n | ^^^^^ index out of bounds: the len is 3 but the index is 10\n\n$main\nthread 'main' panicked at 'index out of bounds: the len \nis 3 but the index is 10', main.rs:4\nnote: Run with `RUST_BACKTRACE=1` for a backtrace." }, { "code": null, "e": 93932, "s": 93831, "text": "A program can invoke the panic! macro if business rules are violated as shown in the example below −" }, { "code": null, "e": 94129, "s": 93932, "text": "fn main() {\n let no = 13; \n //try with odd and even\n if no%2 == 0 {\n println!(\"Thank you , number is even\");\n } else {\n panic!(\"NOT_AN_EVEN\"); \n }\n println!(\"End of main\");\n}" }, { "code": null, "e": 94210, "s": 94129, "text": "The above example returns an error if the value assigned to the variable is odd." }, { "code": null, "e": 94313, "s": 94210, "text": "thread 'main' panicked at 'NOT_AN_EVEN', main.rs:9\nnote: Run with `RUST_BACKTRACE=1` for a backtrace.\n" }, { "code": null, "e": 94647, "s": 94313, "text": "Enum Result – <T,E> can be used to handle recoverable errors. It has two variants − OK and Err. T and E are generic type parameters. T represents the type of the value that will be returned in a success case within the OK variant, and E represents the type of the error that will be returned in a failure case within the Err variant." }, { "code": null, "e": 94689, "s": 94647, "text": "enum Result<T,E> {\n OK(T),\n Err(E)\n}\n" }, { "code": null, "e": 94742, "s": 94689, "text": "Let us understand this with the help of an example −" }, { "code": null, "e": 94864, "s": 94742, "text": "use std::fs::File;\nfn main() {\n let f = File::open(\"main.jpg\"); \n //this file does not exist\n println!(\"{:?}\",f);\n}" }, { "code": null, "e": 94961, "s": 94864, "text": "The program returns OK(File) if the file already exists and Err(Error) if the file is not found." }, { "code": null, "e": 95036, "s": 94961, "text": "Err(Error { repr: Os { code: 2, message: \"No such file or directory\" } })\n" }, { "code": null, "e": 95082, "s": 95036, "text": "Let us now see how to handle the Err variant." }, { "code": null, "e": 95175, "s": 95082, "text": "The following example handles an error returned while opening file using the match statement" }, { "code": null, "e": 95471, "s": 95175, "text": "use std::fs::File;\nfn main() {\n let f = File::open(\"main.jpg\"); // main.jpg doesn't exist\n match f {\n Ok(f)=> {\n println!(\"file found {:?}\",f);\n },\n Err(e)=> {\n println!(\"file not found \\n{:?}\",e); //handled error\n }\n }\n println!(\"end of main\");\n}" }, { "code": null, "e": 95599, "s": 95471, "text": "NOTE − The program prints end of the main event though file was not found. This means the program has handled error gracefully." }, { "code": null, "e": 95713, "s": 95599, "text": "file not found\nOs { code: 2, kind: NotFound, message: \"The system cannot find the file specified.\" }\nend of main\n" }, { "code": null, "e": 95828, "s": 95713, "text": "The is_even function returns an error if the number is not an even number. The main() function handles this error." }, { "code": null, "e": 96196, "s": 95828, "text": "fn main(){\n let result = is_even(13);\n match result {\n Ok(d)=>{\n println!(\"no is even {}\",d);\n },\n Err(msg)=>{\n println!(\"Error msg is {}\",msg);\n }\n }\n println!(\"end of main\");\n}\nfn is_even(no:i32)->Result<bool,String> {\n if no%2==0 {\n return Ok(true);\n } else {\n return Err(\"NOT_AN_EVEN\".to_string());\n }\n}" }, { "code": null, "e": 96291, "s": 96196, "text": "NOTE − Since the main function handles error gracefully, the end of main statement is printed." }, { "code": null, "e": 96329, "s": 96291, "text": "Error msg is NOT_AN_EVEN\nend of main\n" }, { "code": null, "e": 96623, "s": 96329, "text": "The standard library contains a couple of helper methods that both enums − Result<T,E> and Option<T> implement. You can use them to simplify error cases where you really do not expect things to fail. In case of success from a method, the \"unwrap\" function is used to extract the actual result." }, { "code": null, "e": 96639, "s": 96623, "text": "unwrap(self): T" }, { "code": null, "e": 96796, "s": 96639, "text": "Expects self to be Ok/Some and returns the value contained within. If it is Err or None instead, it raises a panic with the contents of the error displayed." }, { "code": null, "e": 96823, "s": 96796, "text": "expect(self, msg: &str): T" }, { "code": null, "e": 96943, "s": 96823, "text": "Behaves like unwrap, except that it outputs a custom message before panicking in addition to the contents of the error." }, { "code": null, "e": 97172, "s": 96943, "text": "The unwrap() function returns the actual result an operation succeeds. It returns a panic with a default error message if an operation fails. This function is a shorthand for match statement. This is shown in the example below −" }, { "code": null, "e": 97459, "s": 97172, "text": "fn main(){\n let result = is_even(10).unwrap();\n println!(\"result is {}\",result);\n println!(\"end of main\");\n}\nfn is_even(no:i32)->Result<bool,String> {\n if no%2==0 {\n return Ok(true);\n } else {\n return Err(\"NOT_AN_EVEN\".to_string());\n }\n}\nresult is true\nend of main" }, { "code": null, "e": 97530, "s": 97459, "text": "Modify the above code to pass an odd number to the is_even() function." }, { "code": null, "e": 97613, "s": 97530, "text": "The unwrap() function will panic and return a default error message as shown below" }, { "code": null, "e": 97777, "s": 97613, "text": "thread 'main' panicked at 'called `Result::unwrap()` on \nan `Err` value: \"NOT_AN_EVEN\"', libcore\\result.rs:945:5\nnote: Run with `RUST_BACKTRACE=1` for a backtrace\n" }, { "code": null, "e": 97884, "s": 97777, "text": "The program can return a custom error message in case of a panic. This is shown in the following example −" }, { "code": null, "e": 98035, "s": 97884, "text": "use std::fs::File;\nfn main(){\n let f = File::open(\"pqr.txt\").expect(\"File not able to open\");\n //file does not exist\n println!(\"end of main\");\n}" }, { "code": null, "e": 98163, "s": 98035, "text": "The function expect() is similar to unwrap(). The only difference is that a custom error message can be displayed using expect." }, { "code": null, "e": 98363, "s": 98163, "text": "thread 'main' panicked at 'File not able to open: Error { repr: Os \n{ code: 2, message: \"No such file or directory\" } }', src/libcore/result.rs:860\nnote: Run with `RUST_BACKTRACE=1` for a backtrace.\n" }, { "code": null, "e": 98740, "s": 98363, "text": "Generics are a facility to write code for multiple contexts with different types. In Rust, generics refer to the parameterization of data types and traits. Generics allows to write more concise and clean code by reducing code duplication and providing type-safety. The concept of Generics can be applied to methods, functions, structures, enumerations, collections and traits." }, { "code": null, "e": 98852, "s": 98740, "text": "The <T> syntax known as the type parameter, is used to declare a generic construct. T represents any data-type." }, { "code": null, "e": 98922, "s": 98852, "text": "The following example declares a vector that can store only integers." }, { "code": null, "e": 99050, "s": 98922, "text": "fn main(){\n let mut vector_integer: Vec<i32> = vec![20,30];\n vector_integer.push(40);\n println!(\"{:?}\",vector_integer);\n}" }, { "code": null, "e": 99064, "s": 99050, "text": "[20, 30, 40]\n" }, { "code": null, "e": 99097, "s": 99064, "text": "Consider the following snippet −" }, { "code": null, "e": 99296, "s": 99097, "text": "fn main() {\n let mut vector_integer: Vec<i32> = vec![20,30];\n vector_integer.push(40);\n vector_integer.push(\"hello\"); \n //error[E0308]: mismatched types\n println!(\"{:?}\",vector_integer);\n}" }, { "code": null, "e": 99516, "s": 99296, "text": "The above example shows that a vector of integer type can only store integer values. So, if we try to push a string value into the collection, the compiler will return an error. Generics make collections more type safe." }, { "code": null, "e": 99593, "s": 99516, "text": "The type parameter represents a type, which the compiler will fill in later." }, { "code": null, "e": 99862, "s": 99593, "text": "struct Data<T> {\n value:T,\n}\nfn main() {\n //generic type of i32\n let t:Data<i32> = Data{value:350};\n println!(\"value is :{} \",t.value);\n //generic type of String\n let t2:Data<String> = Data{value:\"Tom\".to_string()};\n println!(\"value is :{} \",t2.value);\n}" }, { "code": null, "e": 100065, "s": 99862, "text": "The above example declares a generic structure named Data. The <T> type indicates some data type. The main() function creates two instances − an integer instance and a string instance, of the structure." }, { "code": null, "e": 100094, "s": 100065, "text": "value is :350\nvalue is :Tom\n" }, { "code": null, "e": 100291, "s": 100094, "text": "Traits can be used to implement a standard set of behaviors (methods) across multiple structures. Traits are like interfaces in Object-oriented Programming. The syntax of trait is as shown below −" }, { "code": null, "e": 100482, "s": 100291, "text": "trait some_trait {\n //abstract or method which is empty\n fn method1(&self);\n // this is already implemented , this is free\n fn method2(&self){\n //some contents of method2\n }\n}" }, { "code": null, "e": 100765, "s": 100482, "text": "Traits can contain concrete methods (methods with body) or abstract methods (methods without a body). Use a concrete method if the method definition will be shared by all structures implementing the Trait. However, a structure can choose to override a function defined by the trait." }, { "code": null, "e": 100851, "s": 100765, "text": "Use abstract methods if the method definition varies for the implementing structures." }, { "code": null, "e": 100953, "s": 100851, "text": "impl some_trait for structure_name {\n // implement method1() there..\n fn method1(&self ){\n }\n}\n" }, { "code": null, "e": 101069, "s": 100953, "text": "The following examples defines a trait Printable with a method print(), which is implemented by the structure book." }, { "code": null, "e": 101482, "s": 101069, "text": "fn main(){\n //create an instance of the structure\n let b1 = Book {\n id:1001,\n name:\"Rust in Action\"\n };\n b1.print();\n}\n//declare a structure\nstruct Book {\n name:&'static str,\n id:u32\n}\n//declare a trait\ntrait Printable {\n fn print(&self);\n}\n//implement the trait\nimpl Printable for Book {\n fn print(&self){\n println!(\"Printing book with id:{} and name {}\",self.id,self.name)\n }\n}" }, { "code": null, "e": 101534, "s": 101482, "text": "Printing book with id:1001 and name Rust in Action\n" }, { "code": null, "e": 101759, "s": 101534, "text": "The example defines a generic function that displays a parameter passed to it. The parameter can be of any type. The parameter’s type should implement the Display trait so that its value can be printed by the println! macro." }, { "code": null, "e": 101988, "s": 101759, "text": "use std::fmt::Display;\n\nfn main(){\n print_pro(10 as u8);\n print_pro(20 as u16);\n print_pro(\"Hello TutorialsPoint\");\n}\n\nfn print_pro<T:Display>(t:T){\n println!(\"Inside print_pro generic function:\");\n println!(\"{}\",t);\n}" }, { "code": null, "e": 102121, "s": 101988, "text": "Inside print_pro generic function:\n10\nInside print_pro generic function:\n20\nInside print_pro generic function:\nHello TutorialsPoint\n" }, { "code": null, "e": 102323, "s": 102121, "text": "This chapter discusses how to accept values from the standard input (keyboard) and display values to the standard output (console). In this chapter, we will also discuss passing command line arguments." }, { "code": null, "e": 102411, "s": 102323, "text": "Rust’s standard library features for input and output are organized around two traits −" }, { "code": null, "e": 102416, "s": 102411, "text": "Read" }, { "code": null, "e": 102422, "s": 102416, "text": "Write" }, { "code": null, "e": 102427, "s": 102422, "text": "Read" }, { "code": null, "e": 102514, "s": 102427, "text": "Types that implement Read have methods for byte-oriented input. They’re called readers" }, { "code": null, "e": 102520, "s": 102514, "text": "Write" }, { "code": null, "e": 102621, "s": 102520, "text": "Types that implement Write support both byte-oriented and UTF-8 text output. They’re called writers." }, { "code": null, "e": 102866, "s": 102621, "text": "Readers are components that your program can read bytes from. Examples include reading input from the keyboard, files, etc. The read_line() method of this trait can be used to read data, one line at a time, from a file or standard input stream." }, { "code": null, "e": 102895, "s": 102866, "text": "read_line(&mut line)->Result" }, { "code": null, "e": 103020, "s": 102895, "text": "Reads a line of text and appends it to line, which is a String. The return value is an io::Result, the number of bytes read." }, { "code": null, "e": 103188, "s": 103020, "text": "Rust programs might have to accept values from the user at runtime. The following example reads values from the standard input (Keyboard) and prints it to the console." }, { "code": null, "e": 103403, "s": 103188, "text": "fn main(){\n let mut line = String::new();\n println!(\"Enter your name :\");\n let b1 = std::io::stdin().read_line(&mut line).unwrap();\n println!(\"Hello , {}\", line);\n println!(\"no of bytes read , {}\", b1);\n}" }, { "code": null, "e": 103662, "s": 103403, "text": "The stdin() function returns a handle to the standard input stream of the current process, to which the read_line function can be applied. This function tries to read all the characters present in the input buffer when it encounters an end-of-line character." }, { "code": null, "e": 103731, "s": 103662, "text": "Enter your name :\nMohtashim\nHello , Mohtashim\nno of bytes read , 10\n" }, { "code": null, "e": 103960, "s": 103731, "text": "Writers are components that your program can write bytes to. Examples include printing values to the console, writing to files, etc. The write() method of this trait can be used to write data to a file or standard output stream." }, { "code": null, "e": 103980, "s": 103960, "text": "write(&buf)->Result" }, { "code": null, "e": 104103, "s": 103980, "text": "Writes some of the bytes in the slice buf to the underlying stream. It returns an io::Result, the number of bytes written." }, { "code": null, "e": 104286, "s": 104103, "text": "The print! or println! macros can be used to display text on the console. However, you can also use the write() standard library function to display some text to the standard output." }, { "code": null, "e": 104333, "s": 104286, "text": "Let us consider an example to understand this." }, { "code": null, "e": 104605, "s": 104333, "text": "use std::io::Write;\nfn main() {\n let b1 = std::io::stdout().write(\"Tutorials \".as_bytes()).unwrap();\n let b2 = std::io::stdout().write(String::from(\"Point\").as_bytes()).unwrap();\n std::io::stdout().write(format!(\"\\nbytes written {}\",(b1+b2)).as_bytes()).unwrap();\n}" }, { "code": null, "e": 104639, "s": 104605, "text": "Tutorials Point\nbytes written 15\n" }, { "code": null, "e": 104974, "s": 104639, "text": "The stdout() standard library function returns a handle to the standard output stream of the current process, to which the write function can be applied. The write() method returns an enum, Result. The unwrap() is a helper method to extract the actual result from the enumeration. The unwrap method will send panic if an error occurs." }, { "code": null, "e": 105023, "s": 104974, "text": "NOTE − File IO is discussed in the next chapter." }, { "code": null, "e": 105266, "s": 105023, "text": "CommandLine arguments are passed to a program before executing it. They are like parameters passed to functions. CommandLine parameters can be used to pass values to the main() function. The std::env::args() returns the commandline arguments." }, { "code": null, "e": 105398, "s": 105266, "text": "The following example passes values as commandLine arguments to the main() function. The program is created in a file name main.rs." }, { "code": null, "e": 105681, "s": 105398, "text": "//main.rs\nfn main(){\n let cmd_line = std::env::args();\n println!(\"No of elements in arguments is :{}\",cmd_line.len()); \n //print total number of values passed\n for arg in cmd_line {\n println!(\"[{}]\",arg); //print all values passed \n as commandline arguments\n }\n}" }, { "code": null, "e": 105870, "s": 105681, "text": "The program will generate a file main.exe once compiled. Multiple command line parameters should be separated by space. Execute main.exe from the terminal as main.exe hello tutorialspoint." }, { "code": null, "e": 105929, "s": 105870, "text": "NOTE − hello and tutorialspoint are commandline arguments." }, { "code": null, "e": 106000, "s": 105929, "text": "No of elements in arguments is :3\n[main.exe]\n[hello]\n[tutorialspoint]\n" }, { "code": null, "e": 106068, "s": 106000, "text": "The output shows 3 arguments as the main.exe is the first argument." }, { "code": null, "e": 106215, "s": 106068, "text": "The following program calculates the sum of values passed as commandline arguments. A list integer values separated by space is passed to program." }, { "code": null, "e": 106808, "s": 106215, "text": "fn main(){\n let cmd_line = std::env::args();\n println!(\"No of elements in arguments is \n :{}\",cmd_line.len()); \n // total number of elements passed\n\n let mut sum = 0;\n let mut has_read_first_arg = false;\n\n //iterate through all the arguments and calculate their sum\n\n for arg in cmd_line {\n if has_read_first_arg { //skip the first argument since it is the exe file name\n sum += arg.parse::<i32>().unwrap();\n }\n has_read_first_arg = true; \n // set the flag to true to calculate sum for the subsequent arguments.\n }\n println!(\"sum is {}\",sum);\n}" }, { "code": null, "e": 106875, "s": 106808, "text": "On executing the program as main.exe 1 2 3 4, the output will be −" }, { "code": null, "e": 106920, "s": 106875, "text": "No of elements in arguments is :5\nsum is 10\n" }, { "code": null, "e": 107009, "s": 106920, "text": "In addition to reading and writing to console, Rust allows reading and writing to files." }, { "code": null, "e": 107187, "s": 107009, "text": "The File struct represents a file. It allows a program to perform read-write operations on a file. All methods in the File struct return a variant of the io::Result enumeration." }, { "code": null, "e": 107264, "s": 107187, "text": "The commonly used methods of the File struct are listed in the table below −" }, { "code": null, "e": 107321, "s": 107264, "text": "Let us see an example to understand how to write a file." }, { "code": null, "e": 107638, "s": 107321, "text": "The following program creates a file 'data.txt'. The create() method is used to create a file. The method returns a file handle if the file is created successfully. The last line write_all function will write bytes in newly created file. If any of the operations fail, the expect() function returns an error message." }, { "code": null, "e": 107928, "s": 107638, "text": "use std::io::Write;\nfn main() {\n let mut file = std::fs::File::create(\"data.txt\").expect(\"create failed\");\n file.write_all(\"Hello World\".as_bytes()).expect(\"write failed\");\n file.write_all(\"\\nTutorialsPoint\".as_bytes()).expect(\"write failed\");\n println!(\"data written to file\" );\n}" }, { "code": null, "e": 107950, "s": 107928, "text": "data written to file\n" }, { "code": null, "e": 108379, "s": 107950, "text": "The following program reads the contents in a file data.txt and prints it to the console. The \"open\" function is used to open an existing file. An absolute or relative path to the file is passed to the open() function as a parameter. The open() function throws an exception if the file does not exist, or if it is not accessible for whatever reason. If it succeeds, a file handle to such file is assigned to the \"file\" variable." }, { "code": null, "e": 108492, "s": 108379, "text": "The \"read_to_string\" function of the \"file\" handle is used to read contents of that file into a string variable." }, { "code": null, "e": 108697, "s": 108492, "text": "use std::io::Read;\n\nfn main(){\n let mut file = std::fs::File::open(\"data.txt\").unwrap();\n let mut contents = String::new();\n file.read_to_string(&mut contents).unwrap();\n print!(\"{}\", contents);\n}" }, { "code": null, "e": 108725, "s": 108697, "text": "Hello World\nTutorialsPoint\n" }, { "code": null, "e": 108869, "s": 108725, "text": "The following example uses the remove_file() function to delete a file. The expect() function returns a custom message in case an error occurs." }, { "code": null, "e": 108992, "s": 108869, "text": "use std::fs;\nfn main() {\n fs::remove_file(\"data.txt\").expect(\"could not remove file\");\n println!(\"file is removed\");\n}" }, { "code": null, "e": 109009, "s": 108992, "text": "file is removed\n" }, { "code": null, "e": 109110, "s": 109009, "text": "The append() function writes data to the end of the file. This is shown in the example given below −" }, { "code": null, "e": 109450, "s": 109110, "text": "use std::fs::OpenOptions;\nuse std::io::Write;\n\nfn main() {\n let mut file = OpenOptions::new().append(true).open(\"data.txt\").expect(\n \"cannot open file\");\n file.write_all(\"Hello World\".as_bytes()).expect(\"write failed\");\n file.write_all(\"\\nTutorialsPoint\".as_bytes()).expect(\"write failed\");\n println!(\"file append success\");\n}" }, { "code": null, "e": 109471, "s": 109450, "text": "file append success\n" }, { "code": null, "e": 109538, "s": 109471, "text": "The following example copies the contents in a file to a new file." }, { "code": null, "e": 110202, "s": 109538, "text": "use std::io::Read;\nuse std::io::Write;\n\nfn main() {\n let mut command_line: std::env::Args = std::env::args();\n command_line.next().unwrap();\n // skip the executable file name\n // accept the source file\n let source = command_line.next().unwrap();\n // accept the destination file\n let destination = command_line.next().unwrap();\n let mut file_in = std::fs::File::open(source).unwrap();\n let mut file_out = std::fs::File::create(destination).unwrap();\n let mut buffer = [0u8; 4096];\n loop {\n let nbytes = file_in.read(&mut buffer).unwrap();\n file_out.write(&buffer[..nbytes]).unwrap();\n if nbytes < buffer.len() { break; }\n }\n}" }, { "code": null, "e": 110328, "s": 110202, "text": "Execute the above program as main.exe data.txt datacopy.txt. Two command line arguments are passed while executing the file −" }, { "code": null, "e": 110356, "s": 110328, "text": "the path to the source file" }, { "code": null, "e": 110377, "s": 110356, "text": "the destination file" }, { "code": null, "e": 110465, "s": 110377, "text": "Cargo is the package manager for RUST. This acts like a tool and manages Rust projects." }, { "code": null, "e": 110531, "s": 110465, "text": "Some commonly used cargo commands are listed in the table below −" }, { "code": null, "e": 110543, "s": 110531, "text": "cargo build" }, { "code": null, "e": 110573, "s": 110543, "text": "Compiles the current project." }, { "code": null, "e": 110585, "s": 110573, "text": "cargo check" }, { "code": null, "e": 110663, "s": 110585, "text": "Analyzes the current project and report errors, but don't build object files." }, { "code": null, "e": 110673, "s": 110663, "text": "cargo run" }, { "code": null, "e": 110706, "s": 110673, "text": "Builds and executes src/main.rs." }, { "code": null, "e": 110718, "s": 110706, "text": "cargo clean" }, { "code": null, "e": 110748, "s": 110718, "text": "Removes the target directory." }, { "code": null, "e": 110761, "s": 110748, "text": "cargo update" }, { "code": null, "e": 110804, "s": 110761, "text": "Updates dependencies listed in Cargo.lock." }, { "code": null, "e": 110814, "s": 110804, "text": "cargo new" }, { "code": null, "e": 110843, "s": 110814, "text": "Creates a new cargo project." }, { "code": null, "e": 111025, "s": 110843, "text": "Cargo helps to download third party libraries. Therefore, it acts like a package manager. You can also build your own libraries. Cargo is installed by default when you install Rust." }, { "code": null, "e": 111093, "s": 111025, "text": "To create a new cargo project, we can use the commands given below." }, { "code": null, "e": 111123, "s": 111093, "text": "cargo new project_name --bin\n" }, { "code": null, "e": 111153, "s": 111123, "text": "cargo new project_name --lib\n" }, { "code": null, "e": 111224, "s": 111153, "text": "To check the current version of cargo, execute the following command −" }, { "code": null, "e": 111241, "s": 111224, "text": "cargo --version\n" }, { "code": null, "e": 111318, "s": 111241, "text": "The game generates a random number and prompts the user to guess the number." }, { "code": null, "e": 111399, "s": 111318, "text": "Open the terminal and type the following command cargo new guess-game-app --bin." }, { "code": null, "e": 111448, "s": 111399, "text": "This will create the following folder structure." }, { "code": null, "e": 111507, "s": 111448, "text": "guess-game-app/\n -->Cargo.toml\n -->src/\n main.rs\n" }, { "code": null, "e": 111715, "s": 111507, "text": "The cargo new command is used to create a crate. The --bin flag indicates that the crate being created is a binary crate. Public crates are stored in a central repository called crates.io https://crates.io/." }, { "code": null, "e": 111969, "s": 111715, "text": "This example needs to generate a random number. Since the internal standard library does not provide random number generation logic, we need to look at external libraries or crates. Let us use rand crate which is available at crates.io website crates.io" }, { "code": null, "e": 112194, "s": 111969, "text": "The https://crates.io/crates/rand is a rust library for random number generation. Rand provides utilities to generate random numbers, to convert them to useful types and distributions, and some randomness-related algorithms." }, { "code": null, "e": 112273, "s": 112194, "text": "The following diagram shows crate.io website and search result for rand crate." }, { "code": null, "e": 112343, "s": 112273, "text": "Copy the version of rand crate to the Cargo.toml file rand = \"0.5.5\"." }, { "code": null, "e": 112451, "s": 112343, "text": "[package]\nname = \"guess-game-app\"\nversion = \"0.1.0\"\nauthors = [\"Mohtashim\"]\n\n[dependencies]\nrand = \"0.5.5\"\n" }, { "code": null, "e": 112540, "s": 112451, "text": "Navigate to the project folder. Execute the command cargo build on the terminal window −" }, { "code": null, "e": 113003, "s": 112540, "text": "Updating registry `https://github.com/rust-lang/crates.io-index`\nDownloading rand v0.5.5\nDownloading rand_core v0.2.2\nDownloading winapi v0.3.6\nDownloading rand_core v0.3.0\n Compiling winapi v0.3.6\n Compiling rand_core v0.3.0\n Compiling rand_core v0.2.2\n Compiling rand v0.5.5\n Compiling guess-game-app v0.1.0 \n (file:///E:/RustWorks/RustRepo/Code_Snippets/cargo-projects/guess-game-app)\n Finished dev [unoptimized + debuginfo] target(s) in 1m 07s\n" }, { "code": null, "e": 113113, "s": 113003, "text": "The rand crate and all transitive dependencies (inner dependencies of rand) will be automatically downloaded." }, { "code": null, "e": 113188, "s": 113113, "text": "Let us now see how the business logic works for the number guessing game −" }, { "code": null, "e": 113230, "s": 113188, "text": "Game initially generates a random number." }, { "code": null, "e": 113272, "s": 113230, "text": "Game initially generates a random number." }, { "code": null, "e": 113325, "s": 113272, "text": "A user is asked to enter input and guess the number." }, { "code": null, "e": 113378, "s": 113325, "text": "A user is asked to enter input and guess the number." }, { "code": null, "e": 113455, "s": 113378, "text": "If number is less than the generated number, a message “Too low” is printed." }, { "code": null, "e": 113532, "s": 113455, "text": "If number is less than the generated number, a message “Too low” is printed." }, { "code": null, "e": 113613, "s": 113532, "text": "If number is greater than the generated number, a message “Too high” is printed." }, { "code": null, "e": 113694, "s": 113613, "text": "If number is greater than the generated number, a message “Too high” is printed." }, { "code": null, "e": 113766, "s": 113694, "text": "If the user enters the number generated by the program, the game exits." }, { "code": null, "e": 113838, "s": 113766, "text": "If the user enters the number generated by the program, the game exits." }, { "code": null, "e": 113878, "s": 113838, "text": "Add the business logic to main.rs file." }, { "code": null, "e": 114821, "s": 113878, "text": "use std::io;\nextern crate rand; \n//importing external crate\nuse rand::random;\nfn get_guess() -> u8 {\n loop {\n println!(\"Input guess\") ;\n let mut guess = String::new();\n io::stdin().read_line(&mut guess)\n .expect(\"could not read from stdin\");\n match guess.trim().parse::<u8>(){ //remember to trim input to avoid enter spaces\n Ok(v) => return v,\n Err(e) => println!(\"could not understand input {}\",e)\n }\n }\n}\nfn handle_guess(guess:u8,correct:u8)-> bool {\n if guess < correct {\n println!(\"Too low\");\n false\n\n } else if guess> correct {\n println!(\"Too high\");\n false\n } else {\n println!(\"You go it ..\");\n true\n }\n}\nfn main() {\n println!(\"Welcome to no guessing game\");\n\n let correct:u8 = random();\n println!(\"correct value is {}\",correct);\n loop {\n let guess = get_guess();\n if handle_guess(guess,correct){\n break;\n }\n }\n}" }, { "code": null, "e": 114929, "s": 114821, "text": "Execute the command cargo run on the terminal. Make sure that the terminal points to the Project directory." }, { "code": null, "e": 115055, "s": 114929, "text": "Welcome to no guessing game\ncorrect value is 97\nInput guess\n20\nToo low\nInput guess\n100\nToo high\nInput guess\n97\nYou got it ..\n" }, { "code": null, "e": 115127, "s": 115055, "text": "In this chapter, we will learn how iterators and closures work in RUST." }, { "code": null, "e": 115575, "s": 115127, "text": "An iterator helps to iterate over a collection of values such as arrays, vectors, maps, etc. Iterators implement the Iterator trait that is defined in the Rust standard library. The iter() method returns an iterator object of the collection. Values in an iterator object are called items. The next() method of the iterator can be used to traverse through the items. The next() method returns a value None when it reaches the end of the collection." }, { "code": null, "e": 115644, "s": 115575, "text": "The following example uses an iterator to read values from an array." }, { "code": null, "e": 115991, "s": 115644, "text": "fn main() {\n //declare an array\n let a = [10,20,30];\n\n let mut iter = a.iter(); \n // fetch an iterator object for the array\n println!(\"{:?}\",iter);\n\n //fetch individual values from the iterator object\n println!(\"{:?}\",iter.next());\n println!(\"{:?}\",iter.next());\n println!(\"{:?}\",iter.next());\n println!(\"{:?}\",iter.next());\n}" }, { "code": null, "e": 116043, "s": 115991, "text": "Iter([10, 20, 30])\nSome(10)\nSome(20)\nSome(30)\nNone\n" }, { "code": null, "e": 116173, "s": 116043, "text": "If a collection like array or Vector implements Iterator trait then it can be traversed using the for...in syntax as shown below-" }, { "code": null, "e": 116288, "s": 116173, "text": "fn main() {\n let a = [10,20,30];\n let iter = a.iter();\n for data in iter{\n print!(\"{}\\t\",data);\n }\n}\n" }, { "code": null, "e": 116298, "s": 116288, "text": "10 20 30\n" }, { "code": null, "e": 116416, "s": 116298, "text": "The following 3 methods return an iterator object from a collection, where T represents the elements in a collection." }, { "code": null, "e": 116423, "s": 116416, "text": "iter()" }, { "code": null, "e": 116465, "s": 116423, "text": "gives an iterator over &T(reference to T)" }, { "code": null, "e": 116477, "s": 116465, "text": "into_iter()" }, { "code": null, "e": 116502, "s": 116477, "text": "gives an iterator over T" }, { "code": null, "e": 116513, "s": 116502, "text": "iter_mut()" }, { "code": null, "e": 116543, "s": 116513, "text": "gives an iterator over &mut T" }, { "code": null, "e": 116725, "s": 116543, "text": "The iter() function uses the concept of borrowing. It returns a reference to each element of the collection, leaving the collection untouched and available for reuse after the loop." }, { "code": null, "e": 117038, "s": 116725, "text": "fn main() {\n let names = vec![\"Kannan\", \"Mohtashim\", \"Kiran\"];\n for name in names.iter() {\n match name {\n &\"Mohtashim\" => println!(\"There is a rustacean among us!\"),\n _ => println!(\"Hello {}\", name),\n }\n }\n println!(\"{:?}\",names); \n // reusing the collection after iteration\n}" }, { "code": null, "e": 117128, "s": 117038, "text": "Hello Kannan\nThere is a rustacean among us!\nHello Kiran\n[\"Kannan\", \"Mohtashim\", \"Kiran\"]\n" }, { "code": null, "e": 117302, "s": 117128, "text": "This function uses the concept of ownership. It moves values in the collection into an iter object, i.e., the collection is consumed and it is no longer available for reuse." }, { "code": null, "e": 117671, "s": 117302, "text": "fn main(){\n let names = vec![\"Kannan\", \"Mohtashim\", \"Kiran\"];\n for name in names.into_iter() {\n match name {\n \"Mohtashim\" => println!(\"There is a rustacean among us!\"),\n _ => println!(\"Hello {}\", name),\n }\n }\n // cannot reuse the collection after iteration\n //println!(\"{:?}\",names); \n //Error:Cannot access after ownership move\n}" }, { "code": null, "e": 117728, "s": 117671, "text": "Hello Kannan\nThere is a rustacean among us!\nHello Kiran\n" }, { "code": null, "e": 117837, "s": 117728, "text": "This function is like the iter() function. However, this function can modify elements within the collection." }, { "code": null, "e": 118163, "s": 117837, "text": "fn main() {\n let mut names = vec![\"Kannan\", \"Mohtashim\", \"Kiran\"];\n for name in names.iter_mut() {\n match name {\n &mut \"Mohtashim\" => println!(\"There is a rustacean among us!\"),\n _ => println!(\"Hello {}\", name),\n }\n }\n println!(\"{:?}\",names);\n //// reusing the collection after iteration\n}" }, { "code": null, "e": 118253, "s": 118163, "text": "Hello Kannan\nThere is a rustacean among us!\nHello Kiran\n[\"Kannan\", \"Mohtashim\", \"Kiran\"]\n" }, { "code": null, "e": 118611, "s": 118253, "text": "Closure refers to a function within another function. These are anonymous functions – functions without a name. Closure can be used to assign a function to a variable. This allows a program to pass a function as a parameter to other functions. Closure is also known as an inline function. Variables in the outer function can be accessed by inline functions." }, { "code": null, "e": 118714, "s": 118611, "text": "A closure definition may optionally have parameters. Parameters are enclosed within two vertical bars." }, { "code": null, "e": 118765, "s": 118714, "text": "let closure_function = |parameter| {\n //logic\n}\n" }, { "code": null, "e": 118855, "s": 118765, "text": "The syntax invoking a Closure implements Fn traits. So, it can be invoked with () syntax." }, { "code": null, "e": 118899, "s": 118855, "text": "closure_function(parameter); //invoking\n" }, { "code": null, "e": 119060, "s": 118899, "text": "The following example defines a closure is_even within the function main(). The closure returns true if a number is even and returns false if the number is odd." }, { "code": null, "e": 119178, "s": 119060, "text": "fn main(){\n let is_even = |x| {\n x%2==0\n };\n let no = 13;\n println!(\"{} is even ? {}\",no,is_even(no));\n}" }, { "code": null, "e": 119198, "s": 119178, "text": "13 is even ? false\n" }, { "code": null, "e": 119372, "s": 119198, "text": "fn main(){\n let val = 10; \n // declared outside\n let closure2 = |x| {\n x + val //inner function accessing outer fn variable\n };\n println!(\"{}\",closure2(2));\n}" }, { "code": null, "e": 119504, "s": 119372, "text": "The main() function declares a variable val and a closure. The closure accesses the variable declared in the outer function main()." }, { "code": null, "e": 119508, "s": 119504, "text": "12\n" }, { "code": null, "e": 119835, "s": 119508, "text": "Rust allocates everything on the stack by default. You can store things on the heap by wrapping them in smart pointers like Box. Types like Vec and String implicitly help heap allocation. Smart pointers implement traits listed in the table below. These traits of the smart pointers differentiate them from an ordinary struct −" }, { "code": null, "e": 119851, "s": 119835, "text": "std::ops::Deref" }, { "code": null, "e": 119905, "s": 119851, "text": "Used for immutable dereferencing operations, like *v." }, { "code": null, "e": 119920, "s": 119905, "text": "std::ops::Drop" }, { "code": null, "e": 120012, "s": 119920, "text": "Used to run some code when a value goes out of scope. This is sometimes called a destructor" }, { "code": null, "e": 120138, "s": 120012, "text": "In this chapter, we will learn about the Box smart pointer. We will also learn how to create a custom smart pointer like Box." }, { "code": null, "e": 120372, "s": 120138, "text": "The Box smart pointer also called a box allows you to store data on the heap rather than the stack. The stack contains the pointer to the heap data. A Box does not have performance overhead, other than storing their data on the heap." }, { "code": null, "e": 120435, "s": 120372, "text": "Let us see how to use a box to store an i32 value on the heap." }, { "code": null, "e": 120548, "s": 120435, "text": "fn main() {\n let var_i32 = 5; \n //stack\n let b = Box::new(var_i32); \n //heap\n println!(\"b = {}\", b);\n}" }, { "code": null, "e": 120555, "s": 120548, "text": "b = 5\n" }, { "code": null, "e": 120709, "s": 120555, "text": "In order to access a value pointed by a variable, use dereferencing. The * is used as a dereference operator. Let us see how to use dereference with Box." }, { "code": null, "e": 120903, "s": 120709, "text": "fn main() {\n let x = 5; \n //value type variable\n let y = Box::new(x); \n //y points to a new value 5 in the heap\n\n println!(\"{}\",5==x);\n println!(\"{}\",5==*y); \n //dereferencing y\n}" }, { "code": null, "e": 121146, "s": 120903, "text": "The variable x is a value-type with the value 5. So, the expression 5==x will return true. Variable y points to the heap. To access the value in heap, we need to dereference using *y. *y returns value 5. So, the expression 5==*y returns true." }, { "code": null, "e": 121157, "s": 121146, "text": "true\ntrue\n" }, { "code": null, "e": 121485, "s": 121157, "text": "The Deref trait, provided by the standard library, requires us to implement one method named deref, that borrows self and returns a reference to the inner data. The following example creates a structure MyBox, which is a generic type. It implements the trait Deref. This trait helps us access heap values wrapped by y using *y." }, { "code": null, "e": 121986, "s": 121485, "text": "use std::ops::Deref;\nstruct MyBox<T>(T);\nimpl<T> MyBox<T> { \n // Generic structure with static method new\n fn new(x:T)-> MyBox<T> {\n MyBox(x)\n }\n}\nimpl<T> Deref for MyBox<T> {\n type Target = T;\n fn deref(&self) -> &T {\n &self.0 //returns data\n }\n}\nfn main() {\n let x = 5;\n let y = MyBox::new(x); \n // calling static method\n \n println!(\"5==x is {}\",5==x);\n println!(\"5==*y is {}\",5==*y); \n // dereferencing y\n println!(\"x==*y is {}\",x==*y);\n //dereferencing y\n}" }, { "code": null, "e": 122028, "s": 121986, "text": "5==x is true\n5==*y is true\nx==*y is true\n" }, { "code": null, "e": 122368, "s": 122028, "text": "The Drop trait contains the drop() method. This method is called when a structure that implemented this trait goes out of scope. In some languages, the programmer must call code to free memory or resources every time they finish using an instance of a smart pointer. In Rust, you can achieve automatic memory deallocation using Drop trait." }, { "code": null, "e": 122759, "s": 122368, "text": "use std::ops::Deref;\n\nstruct MyBox<T>(T);\nimpl<T> MyBox<T> {\n fn new(x:T)->MyBox<T>{\n MyBox(x)\n }\n}\nimpl<T> Deref for MyBox<T> {\n type Target = T;\n fn deref(&self) -< &T {\n &self.0\n }\n}\nimpl<T> Drop for MyBox<T>{\n fn drop(&mut self){\n println!(\"dropping MyBox object from memory \");\n }\n}\nfn main() {\n let x = 50;\n MyBox::new(x);\n MyBox::new(\"Hello\");\n}" }, { "code": null, "e": 122862, "s": 122759, "text": "In the above example, the drop method will be called twice as we are creating two objects in the heap." }, { "code": null, "e": 122931, "s": 122862, "text": "dropping MyBox object from memory\ndropping MyBox object from memory\n" }, { "code": null, "e": 123210, "s": 122931, "text": "In Concurrent programming, different parts of a program execute independently. On the other hand, in parallel programming, different parts of a program execute at the same time. Both the models are equally important as more computers take advantage of their multiple processors." }, { "code": null, "e": 123545, "s": 123210, "text": "We can use threads to run codes simultaneously. In current operating systems, an executed program’s code is run in a process, and the operating system manages multiple processes at once. Within your program, you can also have independent parts that run simultaneously. The features that run these independent parts are called threads." }, { "code": null, "e": 123809, "s": 123545, "text": "The thread::spawn function is used to create a new thread. The spawn function takes a closure as parameter. The closure defines code that should be executed by the thread. The following example prints some text from a main thread and other text from a new thread." }, { "code": null, "e": 124261, "s": 123809, "text": "//import the necessary modules\nuse std::thread;\nuse std::time::Duration;\n\nfn main() {\n //create a new thread\n thread::spawn(|| {\n for i in 1..10 {\n println!(\"hi number {} from the spawned thread!\", i);\n thread::sleep(Duration::from_millis(1));\n }\n });\n //code executed by the main thread\n for i in 1..5 {\n println!(\"hi number {} from the main thread!\", i);\n thread::sleep(Duration::from_millis(1));\n }\n}" }, { "code": null, "e": 124546, "s": 124261, "text": "hi number 1 from the main thread!\nhi number 1 from the spawned thread!\nhi number 2 from the main thread!\nhi number 2 from the spawned thread!\nhi number 3 from the main thread!\nhi number 3 from the spawned thread!\nhi number 4 from the spawned thread!\nhi number 4 from the main thread!\n" }, { "code": null, "e": 124589, "s": 124546, "text": "The main thread prints values from 1 to 4." }, { "code": null, "e": 124723, "s": 124589, "text": "NOTE − The new thread will be stopped when the main thread ends. The output from this program might be a little different every time." }, { "code": null, "e": 125231, "s": 124723, "text": "The thread::sleep function forces a thread to stop its execution for a short duration, allowing a different thread to run. The threads will probably take turns, but that is not guaranteed – it depends on how the operating system schedules the threads. In this run, the main thread is printed first, even though the print statement from the spawned thread appears first in the code. Moreover, even if the spawned thread is programmed to print values till 9, it only got to 5 before the main thread shut down." }, { "code": null, "e": 125493, "s": 125231, "text": "A spawned thread may not get a chance to run or run completely. This is because the main thread completes quickly. The function spawn<F, T>(f: F) -> JoinHandlelt;T> returns a JoinHandle. The join() method on JoinHandle waits for the associated thread to finish." }, { "code": null, "e": 125891, "s": 125493, "text": "use std::thread;\nuse std::time::Duration;\n\nfn main() {\n let handle = thread::spawn(|| {\n for i in 1..10 {\n println!(\"hi number {} from the spawned thread!\", i);\n thread::sleep(Duration::from_millis(1));\n }\n });\n for i in 1..5 {\n println!(\"hi number {} from the main thread!\", i);\n thread::sleep(Duration::from_millis(1));\n }\n handle.join().unwrap();\n}" }, { "code": null, "e": 126361, "s": 125891, "text": "hi number 1 from the main thread!\nhi number 1 from the spawned thread!\nhi number 2 from the spawned thread!\nhi number 2 from the main thread!\nhi number 3 from the spawned thread!\nhi number 3 from the main thread!\nhi number 4 from the main thread!\nhi number 4 from the spawned thread!\nhi number 5 from the spawned thread!\nhi number 6 from the spawned thread!\nhi number 7 from the spawned thread!\nhi number 8 from the spawned thread!\nhi number 9 from the spawned thread!\n" }, { "code": null, "e": 126416, "s": 126361, "text": "The main thread and spawned thread continue switching." }, { "code": null, "e": 126518, "s": 126416, "text": "NOTE − The main thread waits for spawned thread to complete because of the call to the join() method." }, { "code": null, "e": 126553, "s": 126518, "text": "\n 45 Lectures \n 4.5 hours \n" }, { "code": null, "e": 126576, "s": 126553, "text": " Stone River ELearning" }, { "code": null, "e": 126608, "s": 126576, "text": "\n 10 Lectures \n 33 mins\n" }, { "code": null, "e": 126619, "s": 126608, "text": " Ken Burke" }, { "code": null, "e": 126626, "s": 126619, "text": " Print" }, { "code": null, "e": 126637, "s": 126626, "text": " Add Notes" } ]
How to increase the width of axes using ggplot2 in R?
To increase the width of axes (both X-axis and Y-axis at the same time) using ggplot2 in R, we can use theme function with axis.line argument where we can set element_line argument to a larger value. Check out the Example given below to understand how it can be done. Following snippet creates a sample data frame − x<-sample(0:9,20,replace=TRUE) y<-sample(0:9,20,replace=TRUE) df<-data.frame(x,y) df The following dataframe is created x y 1 6 9 2 7 8 3 1 3 4 2 4 5 1 2 6 2 5 7 2 4 8 1 6 9 4 1 10 7 6 11 0 8 12 9 0 13 9 4 14 1 8 15 6 5 16 7 7 17 0 0 18 6 7 19 1 6 20 6 8 To load ggplot2 package and create scatterplot between x and y on the above created data frame, add the following code to the above snippet − x<-sample(0:9,20,replace=TRUE) y<-sample(0:9,20,replace=TRUE) df<-data.frame(x,y) library(ggplot2) ggplot(df,aes(x,y))+geom_point() If you execute all the above given snippets as a single program, it generates the following Output − To create scatterplot between x and y with increased width of both the axes on the above created data frame, add the following code to the above snippet − x<-sample(0:9,20,replace=TRUE) y<-sample(0:9,20,replace=TRUE) df<-data.frame(x,y) library(ggplot2) ggplot(df,aes(x,y))+geom_point()+theme(axis.line=element_line(size=2)) If you execute all the above given snippets as a single program, it generates the following Output −
[ { "code": null, "e": 1262, "s": 1062, "text": "To increase the width of axes (both X-axis and Y-axis at the same time) using ggplot2 in\nR, we can use theme function with axis.line argument where we can set element_line\nargument to a larger value." }, { "code": null, "e": 1330, "s": 1262, "text": "Check out the Example given below to understand how it can be done." }, { "code": null, "e": 1378, "s": 1330, "text": "Following snippet creates a sample data frame −" }, { "code": null, "e": 1463, "s": 1378, "text": "x<-sample(0:9,20,replace=TRUE)\ny<-sample(0:9,20,replace=TRUE)\ndf<-data.frame(x,y)\ndf" }, { "code": null, "e": 1498, "s": 1463, "text": "The following dataframe is created" }, { "code": null, "e": 1645, "s": 1498, "text": " x y\n 1 6 9\n 2 7 8\n 3 1 3\n 4 2 4\n 5 1 2\n 6 2 5\n 7 2 4\n 8 1 6\n 9 4 1\n10 7 6\n11 0 8\n12 9 0\n13 9 4\n14 1 8\n15 6 5\n16 7 7\n17 0 0\n18 6 7\n19 1 6\n20 6 8" }, { "code": null, "e": 1787, "s": 1645, "text": "To load ggplot2 package and create scatterplot between x and y on the above created\ndata frame, add the following code to the above snippet −" }, { "code": null, "e": 1919, "s": 1787, "text": "x<-sample(0:9,20,replace=TRUE)\ny<-sample(0:9,20,replace=TRUE)\ndf<-data.frame(x,y)\nlibrary(ggplot2)\nggplot(df,aes(x,y))+geom_point()" }, { "code": null, "e": 2020, "s": 1919, "text": "If you execute all the above given snippets as a single program, it generates the following Output −" }, { "code": null, "e": 2175, "s": 2020, "text": "To create scatterplot between x and y with increased width of both the axes on the\nabove created data frame, add the following code to the above snippet −" }, { "code": null, "e": 2345, "s": 2175, "text": "x<-sample(0:9,20,replace=TRUE)\ny<-sample(0:9,20,replace=TRUE)\ndf<-data.frame(x,y)\nlibrary(ggplot2)\nggplot(df,aes(x,y))+geom_point()+theme(axis.line=element_line(size=2))" }, { "code": null, "e": 2446, "s": 2345, "text": "If you execute all the above given snippets as a single program, it generates the following Output −" } ]
How to show current location on a google map on Android?
This example demonstrates how do I show current location on a google map on 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"?> <fragment xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/myMap" android:name="com.google.android.gms.maps.SupportMapFragment" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" /> Step 3 – Add the following dependency in the build.gradle (Module: app) implementation 'com.google.android.gms:play-services-maps:17.0.0' implementation 'com.google.android.gms:play-services-location:17.0.0' Step 4 − Add the following code to src/MainActivity.java import android.Manifest; import android.content.pm.PackageManager; import android.location.Location; import android.os.Bundle; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import androidx.annotation.NonNull; import androidx.core.app.ActivityCompat; import androidx.fragment.app.FragmentActivity; public class MainActivity extends FragmentActivity implements OnMapReadyCallback { Location currentLocation; FusedLocationProviderClient fusedLocationProviderClient; private static final int REQUEST_CODE = 101 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this); fetchLocation(); } private void fetchLocation() { if (ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE); return; } Task<Location> task = fusedLocationProviderClient.getLastLocation(); task.addOnSuccessListener(new OnSuccessListener<Location>() { @Override public void onSuccess(Location location) { if (location != null) { currentLocation = location; Toast.makeText(getApplicationContext(), currentLocation.getLatitude() + "" + currentLocation.getLongitude(), Toast.LENGTH_SHORT).show(); SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.myMap); assert supportMapFragment != null; supportMapFragment.getMapAsync(MainActivity.this); } } }); } @Override public void onMapReady(GoogleMap googleMap) { LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()); MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("I am here!"); googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng)); googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 5)); googleMap.addMarker(markerOptions); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case REQUEST_CODE: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { fetchLocation(); } break; } } } Step 5 – Open strings.xml and add the following code − <resources> <string name="app_name">Sample</string> <string name="map_key" translatable="false">Enter your google API key here</string> </resources> Step 6 – To get the google API key (map_key), kindly follow the steps below Visit the Google Cloud Platform Console. Click the project drop-down and select or create the project for which you want to add an API key. Click the menu button and select APIs & Services > Credentials. On the Credentials page, click Create credentials > API key. The API key created dialog displays your newly created API key. Click Close. The new API key is listed on the Credentials page under API keys. (Remember to restrict the API key before using it in production.) The new API key is listed on the Credentials page under API keys. (Remember to restrict the API key before using it in production.) Step 7 − 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"> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <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"> <meta-data android:name="com.google.android.geo.API_KEY" android:value="@string/map_key"/> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code.
[ { "code": null, "e": 1147, "s": 1062, "text": "This example demonstrates how do I show current location on a google map on Android." }, { "code": null, "e": 1276, "s": 1147, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1341, "s": 1276, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1706, "s": 1341, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<fragment xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:id=\"@+id/myMap\"\n android:name=\"com.google.android.gms.maps.SupportMapFragment\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\" />" }, { "code": null, "e": 1778, "s": 1706, "text": "Step 3 – Add the following dependency in the build.gradle (Module: app)" }, { "code": null, "e": 1914, "s": 1778, "text": "implementation 'com.google.android.gms:play-services-maps:17.0.0'\nimplementation 'com.google.android.gms:play-services-location:17.0.0'" }, { "code": null, "e": 1971, "s": 1914, "text": "Step 4 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 5288, "s": 1971, "text": "import android.Manifest;\nimport android.content.pm.PackageManager;\nimport android.location.Location;\nimport android.os.Bundle;\nimport android.widget.Toast;\nimport com.google.android.gms.maps.CameraUpdateFactory;\nimport com.google.android.gms.maps.SupportMapFragment;\nimport com.google.android.gms.location.FusedLocationProviderClient;\nimport com.google.android.gms.location.LocationServices;\nimport com.google.android.gms.maps.GoogleMap;\nimport com.google.android.gms.maps.OnMapReadyCallback;\nimport com.google.android.gms.maps.model.LatLng;\nimport com.google.android.gms.maps.model.MarkerOptions;\nimport com.google.android.gms.tasks.OnSuccessListener;\nimport com.google.android.gms.tasks.Task;\nimport androidx.annotation.NonNull;\nimport androidx.core.app.ActivityCompat;\nimport androidx.fragment.app.FragmentActivity;\npublic class MainActivity extends FragmentActivity implements OnMapReadyCallback {\n Location currentLocation;\n FusedLocationProviderClient fusedLocationProviderClient;\n private static final int REQUEST_CODE = 101\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);\n fetchLocation();\n }\n private void fetchLocation() {\n if (ActivityCompat.checkSelfPermission(\n this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(\n this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {\n ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);\n return;\n }\n Task<Location> task = fusedLocationProviderClient.getLastLocation();\n task.addOnSuccessListener(new OnSuccessListener<Location>() {\n @Override\n public void onSuccess(Location location) {\n if (location != null) {\n currentLocation = location;\n Toast.makeText(getApplicationContext(), currentLocation.getLatitude() + \"\" + currentLocation.getLongitude(), Toast.LENGTH_SHORT).show();\n SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.myMap);\n assert supportMapFragment != null;\n supportMapFragment.getMapAsync(MainActivity.this);\n }\n }\n });\n }\n @Override\n public void onMapReady(GoogleMap googleMap) {\n LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());\n MarkerOptions markerOptions = new MarkerOptions().position(latLng).title(\"I am here!\");\n googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));\n googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 5));\n googleMap.addMarker(markerOptions);\n }\n @Override\n public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {\n switch (requestCode) {\n case REQUEST_CODE:\n if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {\n fetchLocation();\n }\n break;\n }\n }\n}" }, { "code": null, "e": 5343, "s": 5288, "text": "Step 5 – Open strings.xml and add the following code −" }, { "code": null, "e": 5498, "s": 5343, "text": "<resources>\n <string name=\"app_name\">Sample</string>\n <string name=\"map_key\" translatable=\"false\">Enter your google API key here</string>\n</resources>" }, { "code": null, "e": 5574, "s": 5498, "text": "Step 6 – To get the google API key (map_key), kindly follow the steps below" }, { "code": null, "e": 5615, "s": 5574, "text": "Visit the Google Cloud Platform Console." }, { "code": null, "e": 5714, "s": 5615, "text": "Click the project drop-down and select or create the project for which you want to add an API key." }, { "code": null, "e": 5779, "s": 5714, "text": "Click the menu button and select APIs & Services > Credentials." }, { "code": null, "e": 5904, "s": 5779, "text": "On the Credentials page, click Create credentials > API key. The API key created dialog displays your newly created API key." }, { "code": null, "e": 5917, "s": 5904, "text": "Click Close." }, { "code": null, "e": 6049, "s": 5917, "text": "The new API key is listed on the Credentials page under API keys. (Remember to restrict the API key before using it in production.)" }, { "code": null, "e": 6181, "s": 6049, "text": "The new API key is listed on the Credentials page under API keys. (Remember to restrict the API key before using it in production.)" }, { "code": null, "e": 6236, "s": 6181, "text": "Step 7 − Add the following code to androidManifest.xml" }, { "code": null, "e": 7224, "s": 6236, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <uses-permission android:name=\"android.permission.INTERNET\"/>\n <uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\"/>\n <uses-permission android:name=\"android.permission.ACCESS_COARSE_LOCATION\"/>\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <meta-data android:name=\"com.google.android.geo.API_KEY\" android:value=\"@string/map_key\"/>\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 7571, "s": 7224, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 7612, "s": 7571, "text": "Click here to download the project code." } ]
Lodash - parseInt method
_.parseInt(string, [radix=10]) Converts string to an integer of the specified radix. If radix is undefined or 0, a radix of 10 is used unless value is a hexadecimal, in which case a radix of 16 is used. [string=''] (string) − The string to convert. [string=''] (string) − The string to convert. [radix=10] (number) − The radix to interpret value by. [radix=10] (number) − The radix to interpret value by. (number) − Returns the converted integer. (number) − Returns the converted integer. var _ = require('lodash'); var result = _.parseInt('010'); console.log(result); result = _.map(['6', '08', '10'], _.parseInt); console.log(result); Save the above program in tester.js. Run the following command to execute this program. \>node tester.js 10 [ 6, 8, 10 ] Print Add Notes Bookmark this page
[ { "code": null, "e": 1859, "s": 1827, "text": "_.parseInt(string, [radix=10])\n" }, { "code": null, "e": 2031, "s": 1859, "text": "Converts string to an integer of the specified radix. If radix is undefined or 0, a radix of 10 is used unless value is a hexadecimal, in which case a radix of 16 is used." }, { "code": null, "e": 2077, "s": 2031, "text": "[string=''] (string) − The string to convert." }, { "code": null, "e": 2123, "s": 2077, "text": "[string=''] (string) − The string to convert." }, { "code": null, "e": 2178, "s": 2123, "text": "[radix=10] (number) − The radix to interpret value by." }, { "code": null, "e": 2233, "s": 2178, "text": "[radix=10] (number) − The radix to interpret value by." }, { "code": null, "e": 2275, "s": 2233, "text": "(number) − Returns the converted integer." }, { "code": null, "e": 2317, "s": 2275, "text": "(number) − Returns the converted integer." }, { "code": null, "e": 2467, "s": 2317, "text": "var _ = require('lodash');\nvar result = _.parseInt('010');\n\nconsole.log(result);\n\nresult = _.map(['6', '08', '10'], _.parseInt);\nconsole.log(result);" }, { "code": null, "e": 2555, "s": 2467, "text": "Save the above program in tester.js. Run the following command to execute this program." }, { "code": null, "e": 2573, "s": 2555, "text": "\\>node tester.js\n" }, { "code": null, "e": 2590, "s": 2573, "text": "10\n[ 6, 8, 10 ]\n" }, { "code": null, "e": 2597, "s": 2590, "text": " Print" }, { "code": null, "e": 2608, "s": 2597, "text": " Add Notes" } ]
C# | Check whether a Hashtable contains a specific key or not - GeeksforGeeks
01 Feb, 2019 Hashtable.Contains(Object) Method is used to check whether the Hashtable contains a specific key or not. Syntax: public virtual bool Contains (object key); Here, key is the Key of Object type which is to be located in the Hashtable. Return Value: This method returns true if the Hashtable contains an element with the specified key otherwise returns false. Exception: This method will give ArgumentNullException if the key is null. Note: Hashtable.ContainsKey(Object) Method is also used to check whether the Hashtable contains a specific key or not. This method behaves same as Contains() method. Contains method implements IDictionary.Contains. It behaves exactly as ContainsKey and this method is an O(1) operation. Below programs illustrate the use of above-discussed method: Example 1: // C# code to check whether the Hashtable// contains a specific key or notusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Hashtable Hashtable myTable = new Hashtable(); // Adding elements in Hashtable myTable.Add("g", "geeks"); myTable.Add("c", "c++"); myTable.Add("d", "data structures"); myTable.Add("q", "quiz"); // Checking if Hashtable contains // the key "Brazil" Console.WriteLine(myTable.Contains("d")); }} Output: True Example 2: // C# code to check whether the Hashtable// contains a specific key or notusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Hashtable Hashtable myTable = new Hashtable(); // Adding elements in Hashtable myTable.Add("1", "C"); myTable.Add("2", "C++"); myTable.Add("3", "Java"); myTable.Add("4", "Python"); // Checking if Hashtable contains // the key null. It will give exception // ArgumentNullException Console.WriteLine(myTable.Contains(null)); }} Runtime Error: Unhandled Exception:System.ArgumentNullException: Key cannot be null.Parameter name: key Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.hashtable.contains?view=netframework-4.7.2 CSharp-Collections-Hashtable CSharp-Collections-Namespace CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Destructors in C# Extension Method in C# HashSet in C# with Examples Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? Partial Classes in C# C# | Inheritance C# | List Class Difference between Hashtable and Dictionary in C# C# | Generics - Introduction
[ { "code": null, "e": 24302, "s": 24274, "text": "\n01 Feb, 2019" }, { "code": null, "e": 24407, "s": 24302, "text": "Hashtable.Contains(Object) Method is used to check whether the Hashtable contains a specific key or not." }, { "code": null, "e": 24415, "s": 24407, "text": "Syntax:" }, { "code": null, "e": 24458, "s": 24415, "text": "public virtual bool Contains (object key);" }, { "code": null, "e": 24535, "s": 24458, "text": "Here, key is the Key of Object type which is to be located in the Hashtable." }, { "code": null, "e": 24659, "s": 24535, "text": "Return Value: This method returns true if the Hashtable contains an element with the specified key otherwise returns false." }, { "code": null, "e": 24734, "s": 24659, "text": "Exception: This method will give ArgumentNullException if the key is null." }, { "code": null, "e": 24740, "s": 24734, "text": "Note:" }, { "code": null, "e": 24900, "s": 24740, "text": "Hashtable.ContainsKey(Object) Method is also used to check whether the Hashtable contains a specific key or not. This method behaves same as Contains() method." }, { "code": null, "e": 25021, "s": 24900, "text": "Contains method implements IDictionary.Contains. It behaves exactly as ContainsKey and this method is an O(1) operation." }, { "code": null, "e": 25082, "s": 25021, "text": "Below programs illustrate the use of above-discussed method:" }, { "code": null, "e": 25093, "s": 25082, "text": "Example 1:" }, { "code": "// C# code to check whether the Hashtable// contains a specific key or notusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Hashtable Hashtable myTable = new Hashtable(); // Adding elements in Hashtable myTable.Add(\"g\", \"geeks\"); myTable.Add(\"c\", \"c++\"); myTable.Add(\"d\", \"data structures\"); myTable.Add(\"q\", \"quiz\"); // Checking if Hashtable contains // the key \"Brazil\" Console.WriteLine(myTable.Contains(\"d\")); }}", "e": 25659, "s": 25093, "text": null }, { "code": null, "e": 25667, "s": 25659, "text": "Output:" }, { "code": null, "e": 25673, "s": 25667, "text": "True\n" }, { "code": null, "e": 25684, "s": 25673, "text": "Example 2:" }, { "code": "// C# code to check whether the Hashtable// contains a specific key or notusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Hashtable Hashtable myTable = new Hashtable(); // Adding elements in Hashtable myTable.Add(\"1\", \"C\"); myTable.Add(\"2\", \"C++\"); myTable.Add(\"3\", \"Java\"); myTable.Add(\"4\", \"Python\"); // Checking if Hashtable contains // the key null. It will give exception // ArgumentNullException Console.WriteLine(myTable.Contains(null)); }}", "e": 26290, "s": 25684, "text": null }, { "code": null, "e": 26305, "s": 26290, "text": "Runtime Error:" }, { "code": null, "e": 26394, "s": 26305, "text": "Unhandled Exception:System.ArgumentNullException: Key cannot be null.Parameter name: key" }, { "code": null, "e": 26405, "s": 26394, "text": "Reference:" }, { "code": null, "e": 26511, "s": 26405, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.hashtable.contains?view=netframework-4.7.2" }, { "code": null, "e": 26540, "s": 26511, "text": "CSharp-Collections-Hashtable" }, { "code": null, "e": 26569, "s": 26540, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 26583, "s": 26569, "text": "CSharp-method" }, { "code": null, "e": 26586, "s": 26583, "text": "C#" }, { "code": null, "e": 26684, "s": 26586, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26702, "s": 26684, "text": "Destructors in C#" }, { "code": null, "e": 26725, "s": 26702, "text": "Extension Method in C#" }, { "code": null, "e": 26753, "s": 26725, "text": "HashSet in C# with Examples" }, { "code": null, "e": 26793, "s": 26753, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 26836, "s": 26793, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 26858, "s": 26836, "text": "Partial Classes in C#" }, { "code": null, "e": 26875, "s": 26858, "text": "C# | Inheritance" }, { "code": null, "e": 26891, "s": 26875, "text": "C# | List Class" }, { "code": null, "e": 26941, "s": 26891, "text": "Difference between Hashtable and Dictionary in C#" } ]
Machine Learning Project 17 — Compare Classification Algorithms | by Omair Aasim | Towards Data Science
In the past 7 projects, we implemented the same project using different classification algorithms namely — “Logistic Regression”, “KNN”, “SVM”, “Kernel SVM”, “Naive Bayes”, “Decision Tree” and “Random Forest”. The reason I wrote a separate article for each is to understand the intuition behind each algorithm. #100DaysOfMLCode #100ProjectsInML In a real scenario, when we are given a problem, we cannot predict which algorithm will perform best. Obviously from the problem, we can tell whether we need to apply Regression or Classification algorithm. But it is difficult to know which Regression or Classification algorithm to apply beforehand. It is only through trial and error and checking the performance metrics, we can narrow down and pick certain algorithms. Today, I will show you how to compare different classification algorithms and pick the best ones. Rather than implementing the entire project using an algorithm and then finding out that the performance is not good, we will first check the performance of a bunch of algorithms and then decide which one to use to implement the project. Let’s get started. We are going to use the same dataset we used in Project 10. Our objective is to evaluate several classification algorithms and pick the best ones based on accuracy. The sample rows are shown below. The full dataset can be accessed here. We are going to assign the independent variables “Gender”, “Salary” and “Age” to X. The dependent variable “Purchased iphone” captures whether the user has purchased the phone or not. We will assign this to y. We have a categorical variable “Gender” that we have to convert to number. We will use the class LabelEncoder to convert Gender to number. Apart from the Decision Tree and Random Forest classifiers, the other classifiers require that we scale the data. So let’s do that now. This is where all the fun stuff happens :) I am going to compare 6 classification algorithms — the ones I have covered in previous projects. Feel free to add and test others as well. Logistic Regression KNN Kernel SVM Naive Bayes Decision Tree Random Forest We will use 10 fold cross validation to evaluate each algorithm and we will find the mean accuracy and the standard deviation accuracy. First, we will create a list and add objects of the different classifiers we want to evaluate. Then we loop through the list and use the cross_val_score method to get the accuracies. Here is the output:Logistic Regression: Mean Accuracy = 82.75% — SD Accuracy = 11.37%K Nearest Neighbor: Mean Accuracy = 90.50% — SD Accuracy = 7.73%Kernel SVM: Mean Accuracy = 90.75% — SD Accuracy = 9.15%Naive Bayes: Mean Accuracy = 85.25% — SD Accuracy = 10.34%Decision Tree: Mean Accuracy = 84.50% — SD Accuracy = 8.50%Random Forest: Mean Accuracy = 88.75% — SD Accuracy = 8.46% From the results, we can see that for this particular dataset, KNN and Kernel SVM have performed better than the rest. So we can shortlist these 2 to work on this project. This is exactly the same conclusion we arrived at by implementing each of those algorithms individually. Hope you had fun. You can find the entire source code here.
[ { "code": null, "e": 257, "s": 47, "text": "In the past 7 projects, we implemented the same project using different classification algorithms namely — “Logistic Regression”, “KNN”, “SVM”, “Kernel SVM”, “Naive Bayes”, “Decision Tree” and “Random Forest”." }, { "code": null, "e": 358, "s": 257, "text": "The reason I wrote a separate article for each is to understand the intuition behind each algorithm." }, { "code": null, "e": 392, "s": 358, "text": "#100DaysOfMLCode #100ProjectsInML" }, { "code": null, "e": 814, "s": 392, "text": "In a real scenario, when we are given a problem, we cannot predict which algorithm will perform best. Obviously from the problem, we can tell whether we need to apply Regression or Classification algorithm. But it is difficult to know which Regression or Classification algorithm to apply beforehand. It is only through trial and error and checking the performance metrics, we can narrow down and pick certain algorithms." }, { "code": null, "e": 1150, "s": 814, "text": "Today, I will show you how to compare different classification algorithms and pick the best ones. Rather than implementing the entire project using an algorithm and then finding out that the performance is not good, we will first check the performance of a bunch of algorithms and then decide which one to use to implement the project." }, { "code": null, "e": 1169, "s": 1150, "text": "Let’s get started." }, { "code": null, "e": 1334, "s": 1169, "text": "We are going to use the same dataset we used in Project 10. Our objective is to evaluate several classification algorithms and pick the best ones based on accuracy." }, { "code": null, "e": 1406, "s": 1334, "text": "The sample rows are shown below. The full dataset can be accessed here." }, { "code": null, "e": 1616, "s": 1406, "text": "We are going to assign the independent variables “Gender”, “Salary” and “Age” to X. The dependent variable “Purchased iphone” captures whether the user has purchased the phone or not. We will assign this to y." }, { "code": null, "e": 1755, "s": 1616, "text": "We have a categorical variable “Gender” that we have to convert to number. We will use the class LabelEncoder to convert Gender to number." }, { "code": null, "e": 1891, "s": 1755, "text": "Apart from the Decision Tree and Random Forest classifiers, the other classifiers require that we scale the data. So let’s do that now." }, { "code": null, "e": 1934, "s": 1891, "text": "This is where all the fun stuff happens :)" }, { "code": null, "e": 2074, "s": 1934, "text": "I am going to compare 6 classification algorithms — the ones I have covered in previous projects. Feel free to add and test others as well." }, { "code": null, "e": 2094, "s": 2074, "text": "Logistic Regression" }, { "code": null, "e": 2098, "s": 2094, "text": "KNN" }, { "code": null, "e": 2109, "s": 2098, "text": "Kernel SVM" }, { "code": null, "e": 2121, "s": 2109, "text": "Naive Bayes" }, { "code": null, "e": 2135, "s": 2121, "text": "Decision Tree" }, { "code": null, "e": 2149, "s": 2135, "text": "Random Forest" }, { "code": null, "e": 2285, "s": 2149, "text": "We will use 10 fold cross validation to evaluate each algorithm and we will find the mean accuracy and the standard deviation accuracy." }, { "code": null, "e": 2468, "s": 2285, "text": "First, we will create a list and add objects of the different classifiers we want to evaluate. Then we loop through the list and use the cross_val_score method to get the accuracies." }, { "code": null, "e": 2850, "s": 2468, "text": "Here is the output:Logistic Regression: Mean Accuracy = 82.75% — SD Accuracy = 11.37%K Nearest Neighbor: Mean Accuracy = 90.50% — SD Accuracy = 7.73%Kernel SVM: Mean Accuracy = 90.75% — SD Accuracy = 9.15%Naive Bayes: Mean Accuracy = 85.25% — SD Accuracy = 10.34%Decision Tree: Mean Accuracy = 84.50% — SD Accuracy = 8.50%Random Forest: Mean Accuracy = 88.75% — SD Accuracy = 8.46%" }, { "code": null, "e": 3127, "s": 2850, "text": "From the results, we can see that for this particular dataset, KNN and Kernel SVM have performed better than the rest. So we can shortlist these 2 to work on this project. This is exactly the same conclusion we arrived at by implementing each of those algorithms individually." } ]
How to save a matrix as CSV file using R?
To save a matrix as CSV file using R, we can use write.matrix function of MASS package. For Example, if we have a matrix called M and we want to save it as CSV file then we can use the below mentioned command − write.matrix(M,file="Mat.csv") Following snippet creates a sample matrix − M<-matrix(rpois(80,10),ncol=4) M The following matrix is created − [,1] [,2] [,3] [,4] [1,] 10 10 13 4 [2,] 13 9 6 9 [3,] 16 9 13 10 [4,] 12 11 11 13 [5,] 8 7 8 6 [6,] 7 6 5 11 [7,] 9 10 6 12 [8,] 8 9 10 12 [9,] 10 6 12 6 [10,] 8 6 8 8 [11,] 5 11 14 9 [12,] 12 7 8 11 [13,] 18 9 9 10 [14,] 7 5 8 7 [15,] 10 12 8 12 [16,] 8 7 8 15 [17,] 9 13 12 11 [18,] 7 9 10 8 [19,] 9 8 10 6 [20,] 12 7 10 10 To load MASS package and save matrix M as CSV file on the above created matrix, add the following code to the above snippet − M<-matrix(rpois(80,10),ncol=4) library(MASS) write.matrix(M,file="Mat.csv") If you execute all the above given snippets as a single program, it generates the following Output −
[ { "code": null, "e": 1273, "s": 1062, "text": "To save a matrix as CSV file using R, we can use write.matrix function of MASS package.\nFor Example, if we have a matrix called M and we want to save it as CSV file then we can\nuse the below mentioned command −" }, { "code": null, "e": 1304, "s": 1273, "text": "write.matrix(M,file=\"Mat.csv\")" }, { "code": null, "e": 1348, "s": 1304, "text": "Following snippet creates a sample matrix −" }, { "code": null, "e": 1381, "s": 1348, "text": "M<-matrix(rpois(80,10),ncol=4)\nM" }, { "code": null, "e": 1415, "s": 1381, "text": "The following matrix is created −" }, { "code": null, "e": 1858, "s": 1415, "text": " [,1] [,2] [,3] [,4]\n [1,] 10 10 13 4\n [2,] 13 9 6 9\n [3,] 16 9 13 10\n [4,] 12 11 11 13\n [5,] 8 7 8 6\n [6,] 7 6 5 11\n [7,] 9 10 6 12\n [8,] 8 9 10 12\n [9,] 10 6 12 6\n[10,] 8 6 8 8\n[11,] 5 11 14 9\n[12,] 12 7 8 11\n[13,] 18 9 9 10\n[14,] 7 5 8 7\n[15,] 10 12 8 12\n[16,] 8 7 8 15\n[17,] 9 13 12 11\n[18,] 7 9 10 8\n[19,] 9 8 10 6\n[20,] 12 7 10 10" }, { "code": null, "e": 1984, "s": 1858, "text": "To load MASS package and save matrix M as CSV file on the above created matrix, add\nthe following code to the above snippet −" }, { "code": null, "e": 2061, "s": 1984, "text": "M<-matrix(rpois(80,10),ncol=4)\nlibrary(MASS)\nwrite.matrix(M,file=\"Mat.csv\")\n" }, { "code": null, "e": 2162, "s": 2061, "text": "If you execute all the above given snippets as a single program, it generates the following Output −" } ]
11 Examples to Master Pandas Groupby Function | by Soner Yıldırım | Towards Data Science
Pandas Groupby function is a versatile and easy-to-use function that helps to get an overview of the data. It makes it easier to explore the dataset and unveil the underlying relationships among variables. In this post, we will go through 11 different examples to have a comprehensive understanding of the groupby function and see how it can be useful in exploring the data. I will use a customer churn dataset for the examples. The first step is to read the dataset into a pandas dataframe. import pandas as pdimport numpy as npdf = pd.read_csv("/content/Churn_Modelling.csv")df.head() We have some features about the customers and their products at a bank. The goal here is to predict whether a customer will churn (i.e. exited = 1) using the provided features. In terms of machine earning, this is a classification problem. Groupby function can be used to explore how features are related or have an effect on the target variable (“Exited”). The following figure represents the logic and working principle of groupby function. Let’s start with the examples. The first one is to check if gender makes any difference in customer churn. #example 1df[['Gender','Exited']].groupby('Gender').mean() We take a subset of the dataframe which consists of gender and exited columns. We then group the rows based on the values in the gender column which are male and female. Finally, an aggregate function is applied. The result is the average churn rate for females and males. In addition to the mean, you may also want to see how many males and females exist in the dataset. If there is an extreme imbalance, checking the mean may cause false assumptions. The solution is to apply both mean and count as aggregate functions. #example 2df[['Gender','Exited']].groupby('Gender').agg(['mean','count']) The number of females and males are close so there is not a considerable imbalance. On average, the churn rate for females is higher than that of males. You may think that it is too general to make a comparison based on gender only. In this case, we can group by multiple columns by passing a list of columns to groupby function. #example 3df[['Gender','Geography','Exited']].groupby(['Gender','Geography']).mean() Churn rate is higher for females in the three countries in our dataset. We can also sort the results. #example 4df[['Gender','Geography','Exited']].groupby(['Gender','Geography']).mean().sort_values(by='Exited') The results are in ascending order but we can change it using the ascending parameter. #example 5df[['Gender','Geography','Exited']].groupby(['Gender','Geography']).mean().sort_values(by='Exited', ascending=False) We can also check multiple features based on groups in another feature. Let’s check how age and tenure changes in different countries. #example 6df[['Geography','Age','Tenure']].groupby(['Geography']).agg(['mean','max']) The average and maximum values of age and tenure columns are pretty close in the three countries. Let’s also add the “Exited” column to example 6. #example 7df[['Exited','Geography','Age','Tenure']].groupby(['Exited','Geography']).agg(['mean','count']) We can sort the results based on any column. However, since it is a multi-index, we need to pass a tuple to the sort_values function. #example 8df[['Exited','Geography','Age','Tenure']].groupby(['Exited','Geography']).agg(['mean','count']).sort_values(by=[('Age','mean')]) The results are sorted by (‘Age’, ‘mean’) column. The variables in the groupby function are returned as the index of the resulting dataframe. We can change it by setting the as_index parameter as false. #example 9df[['Exited','IsActiveMember','NumOfProducts','Balance']].groupby(['Exited','IsActiveMember'], as_index=False).mean() Each column in the groupby function is represented with a column. There is a row for each combination of categories. The groupby function drops the missing values by default. Our dataset does not have any missing values. Let’s add some missing values and see how the dropna parameter is used. #example 10df['Geography'][30:50] = np.nandf[['Geography','Exited']].groupby('Geography').mean() Although we have missing values in the geography column, they are ignored. We can change it by setting the dropna parameter as false. #example 11df[['Geography','Exited']].groupby('Geography', dropna=False).agg(['mean','count']) As you can see, there is another category for missing values. Note: In order to use the dropna parameter of the groupby function, you need to have pandas version 1.1.0 or higher. We can diversify the examples but the underlying logic is the same. Groupby function can be used as a first step in the exploratory data analysis process because it gives us an idea about the relationships between variables in the dataset. Thanks for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 252, "s": 46, "text": "Pandas Groupby function is a versatile and easy-to-use function that helps to get an overview of the data. It makes it easier to explore the dataset and unveil the underlying relationships among variables." }, { "code": null, "e": 421, "s": 252, "text": "In this post, we will go through 11 different examples to have a comprehensive understanding of the groupby function and see how it can be useful in exploring the data." }, { "code": null, "e": 538, "s": 421, "text": "I will use a customer churn dataset for the examples. The first step is to read the dataset into a pandas dataframe." }, { "code": null, "e": 633, "s": 538, "text": "import pandas as pdimport numpy as npdf = pd.read_csv(\"/content/Churn_Modelling.csv\")df.head()" }, { "code": null, "e": 810, "s": 633, "text": "We have some features about the customers and their products at a bank. The goal here is to predict whether a customer will churn (i.e. exited = 1) using the provided features." }, { "code": null, "e": 991, "s": 810, "text": "In terms of machine earning, this is a classification problem. Groupby function can be used to explore how features are related or have an effect on the target variable (“Exited”)." }, { "code": null, "e": 1076, "s": 991, "text": "The following figure represents the logic and working principle of groupby function." }, { "code": null, "e": 1107, "s": 1076, "text": "Let’s start with the examples." }, { "code": null, "e": 1183, "s": 1107, "text": "The first one is to check if gender makes any difference in customer churn." }, { "code": null, "e": 1242, "s": 1183, "text": "#example 1df[['Gender','Exited']].groupby('Gender').mean()" }, { "code": null, "e": 1515, "s": 1242, "text": "We take a subset of the dataframe which consists of gender and exited columns. We then group the rows based on the values in the gender column which are male and female. Finally, an aggregate function is applied. The result is the average churn rate for females and males." }, { "code": null, "e": 1695, "s": 1515, "text": "In addition to the mean, you may also want to see how many males and females exist in the dataset. If there is an extreme imbalance, checking the mean may cause false assumptions." }, { "code": null, "e": 1764, "s": 1695, "text": "The solution is to apply both mean and count as aggregate functions." }, { "code": null, "e": 1838, "s": 1764, "text": "#example 2df[['Gender','Exited']].groupby('Gender').agg(['mean','count'])" }, { "code": null, "e": 1991, "s": 1838, "text": "The number of females and males are close so there is not a considerable imbalance. On average, the churn rate for females is higher than that of males." }, { "code": null, "e": 2168, "s": 1991, "text": "You may think that it is too general to make a comparison based on gender only. In this case, we can group by multiple columns by passing a list of columns to groupby function." }, { "code": null, "e": 2253, "s": 2168, "text": "#example 3df[['Gender','Geography','Exited']].groupby(['Gender','Geography']).mean()" }, { "code": null, "e": 2325, "s": 2253, "text": "Churn rate is higher for females in the three countries in our dataset." }, { "code": null, "e": 2355, "s": 2325, "text": "We can also sort the results." }, { "code": null, "e": 2465, "s": 2355, "text": "#example 4df[['Gender','Geography','Exited']].groupby(['Gender','Geography']).mean().sort_values(by='Exited')" }, { "code": null, "e": 2552, "s": 2465, "text": "The results are in ascending order but we can change it using the ascending parameter." }, { "code": null, "e": 2679, "s": 2552, "text": "#example 5df[['Gender','Geography','Exited']].groupby(['Gender','Geography']).mean().sort_values(by='Exited', ascending=False)" }, { "code": null, "e": 2814, "s": 2679, "text": "We can also check multiple features based on groups in another feature. Let’s check how age and tenure changes in different countries." }, { "code": null, "e": 2900, "s": 2814, "text": "#example 6df[['Geography','Age','Tenure']].groupby(['Geography']).agg(['mean','max'])" }, { "code": null, "e": 2998, "s": 2900, "text": "The average and maximum values of age and tenure columns are pretty close in the three countries." }, { "code": null, "e": 3047, "s": 2998, "text": "Let’s also add the “Exited” column to example 6." }, { "code": null, "e": 3153, "s": 3047, "text": "#example 7df[['Exited','Geography','Age','Tenure']].groupby(['Exited','Geography']).agg(['mean','count'])" }, { "code": null, "e": 3287, "s": 3153, "text": "We can sort the results based on any column. However, since it is a multi-index, we need to pass a tuple to the sort_values function." }, { "code": null, "e": 3426, "s": 3287, "text": "#example 8df[['Exited','Geography','Age','Tenure']].groupby(['Exited','Geography']).agg(['mean','count']).sort_values(by=[('Age','mean')])" }, { "code": null, "e": 3476, "s": 3426, "text": "The results are sorted by (‘Age’, ‘mean’) column." }, { "code": null, "e": 3629, "s": 3476, "text": "The variables in the groupby function are returned as the index of the resulting dataframe. We can change it by setting the as_index parameter as false." }, { "code": null, "e": 3757, "s": 3629, "text": "#example 9df[['Exited','IsActiveMember','NumOfProducts','Balance']].groupby(['Exited','IsActiveMember'], as_index=False).mean()" }, { "code": null, "e": 3874, "s": 3757, "text": "Each column in the groupby function is represented with a column. There is a row for each combination of categories." }, { "code": null, "e": 4050, "s": 3874, "text": "The groupby function drops the missing values by default. Our dataset does not have any missing values. Let’s add some missing values and see how the dropna parameter is used." }, { "code": null, "e": 4147, "s": 4050, "text": "#example 10df['Geography'][30:50] = np.nandf[['Geography','Exited']].groupby('Geography').mean()" }, { "code": null, "e": 4281, "s": 4147, "text": "Although we have missing values in the geography column, they are ignored. We can change it by setting the dropna parameter as false." }, { "code": null, "e": 4376, "s": 4281, "text": "#example 11df[['Geography','Exited']].groupby('Geography', dropna=False).agg(['mean','count'])" }, { "code": null, "e": 4438, "s": 4376, "text": "As you can see, there is another category for missing values." }, { "code": null, "e": 4555, "s": 4438, "text": "Note: In order to use the dropna parameter of the groupby function, you need to have pandas version 1.1.0 or higher." }, { "code": null, "e": 4795, "s": 4555, "text": "We can diversify the examples but the underlying logic is the same. Groupby function can be used as a first step in the exploratory data analysis process because it gives us an idea about the relationships between variables in the dataset." } ]
MATLAB - Logical Operations
MATLAB offers two types of logical operators and functions − Element-wise − these operators operate on corresponding elements of logical arrays. Element-wise − these operators operate on corresponding elements of logical arrays. Short-circuit − these operators operate on scalar, logical expressions. Short-circuit − these operators operate on scalar, logical expressions. Element-wise logical operators operate element-by-element on logical arrays. The symbols &, |, and ~ are the logical array operators AND, OR, and NOT. Short-circuit logical operators allow short-circuiting on logical operations. The symbols && and || are the logical short-circuit operators AND and OR. Create a script file and type the following code − a = 5; b = 20; if ( a && b ) disp('Line 1 - Condition is true'); end if ( a || b ) disp('Line 2 - Condition is true'); end % lets change the value of a and b a = 0; b = 10; if ( a && b ) disp('Line 3 - Condition is true'); else disp('Line 3 - Condition is not true'); end if (~(a && b)) disp('Line 4 - Condition is true'); end When you run the file, it produces following result − Line 1 - Condition is true Line 2 - Condition is true Line 3 - Condition is not true Line 4 - Condition is true Apart from the above-mentioned logical operators, MATLAB provides the following commands or functions used for the same purpose − and(A, B) Finds logical AND of array or scalar inputs; performs a logical AND of all input arrays A, B, etc. and returns an array containing elements set to either logical 1 (true) or logical 0 (false). An element of the output array is set to 1 if all input arrays contain a nonzero element at that same array location. Otherwise, that element is set to 0. not(A) Finds logical NOT of array or scalar input; performs a logical NOT of input array A and returns an array containing elements set to either logical 1 (true) or logical 0 (false). An element of the output array is set to 1 if the input array contains a zero value element at that same array location. Otherwise, that element is set to 0. or(A, B) Finds logical OR of array or scalar inputs; performs a logical OR of all input arrays A, B, etc. and returns an array containing elements set to either logical 1 (true) or logical 0 (false). An element of the output array is set to 1 if any input arrays contain a nonzero element at that same array location. Otherwise, that element is set to 0. xor(A, B) Logical exclusive-OR; performs an exclusive OR operation on the corresponding elements of arrays A and B. The resulting element C(i,j,...) is logical true (1) if A(i,j,...) or B(i,j,...), but not both, is nonzero. all(A) Determine if all array elements of array A are nonzero or true. If A is a vector, all(A) returns logical 1 (true) if all the elements are nonzero and returns logical 0 (false) if one or more elements are zero. If A is a vector, all(A) returns logical 1 (true) if all the elements are nonzero and returns logical 0 (false) if one or more elements are zero. If A is a nonempty matrix, all(A) treats the columns of A as vectors, returning a row vector of logical 1's and 0's. If A is a nonempty matrix, all(A) treats the columns of A as vectors, returning a row vector of logical 1's and 0's. If A is an empty 0-by-0 matrix, all(A) returns logical 1 (true). If A is an empty 0-by-0 matrix, all(A) returns logical 1 (true). If A is a multidimensional array, all(A) acts along the first non-singleton dimension and returns an array of logical values. The size of this dimension reduces to 1 while the sizes of all other dimensions remain the same. If A is a multidimensional array, all(A) acts along the first non-singleton dimension and returns an array of logical values. The size of this dimension reduces to 1 while the sizes of all other dimensions remain the same. all(A, dim) Tests along the dimension of A specified by scalar dim. any(A) Determine if any array elements are nonzero; tests whether any of the elements along various dimensions of an array is a nonzero number or is logical 1 (true). The any function ignores entries that are NaN (Not a Number). If A is a vector, any(A) returns logical 1 (true) if any of the elements of A is a nonzero number or is logical 1 (true), and returns logical 0 (false) if all the elements are zero. If A is a vector, any(A) returns logical 1 (true) if any of the elements of A is a nonzero number or is logical 1 (true), and returns logical 0 (false) if all the elements are zero. If A is a nonempty matrix, any(A) treats the columns of A as vectors, returning a row vector of logical 1's and 0's. If A is a nonempty matrix, any(A) treats the columns of A as vectors, returning a row vector of logical 1's and 0's. If A is an empty 0-by-0 matrix, any(A) returns logical 0 (false). If A is an empty 0-by-0 matrix, any(A) returns logical 0 (false). If A is a multidimensional array, any(A) acts along the first non-singleton dimension and returns an array of logical values. The size of this dimension reduces to 1 while the sizes of all other dimensions remain the same. If A is a multidimensional array, any(A) acts along the first non-singleton dimension and returns an array of logical values. The size of this dimension reduces to 1 while the sizes of all other dimensions remain the same. any(A,dim) Tests along the dimension of A specified by scalar dim. false Logical 0 (false) false(n) is an n-by-n matrix of logical zeros false(m, n) is an m-by-n matrix of logical zeros. false(m, n, p, ...) is an m-by-n-by-p-by-... array of logical zeros. false(size(A)) is an array of logical zeros that is the same size as array A. false(...,'like',p) is an array of logical zeros of the same data type and sparsity as the logical array p. ind = find(X) Find indices and values of nonzero elements; locates all nonzero elements of array X, and returns the linear indices of those elements in a vector. If X is a row vector, then the returned vector is a row vector; otherwise, it returns a column vector. If X contains no nonzero elements or is an empty array, then an empty array is returned. ind = find(X, k) ind = find(X, k, 'first') Returns at most the first k indices corresponding to the nonzero entries of X. k must be a positive integer, but it can be of any numeric data type. ind = find(X, k, 'last') returns at most the last k indices corresponding to the nonzero entries of X. [row,col] = find(X, ...) Returns the row and column indices of the nonzero entries in the matrix X. This syntax is especially useful when working with sparse matrices. If X is an N-dimensional array with N > 2, col contains linear indices for the columns. [row,col,v] = find(X, ...) Returns a column or row vector v of the nonzero entries in X, as well as row and column indices. If X is a logical expression, then v is a logical array. Output v contains the non-zero elements of the logical array obtained by evaluating the expression X. islogical(A) Determine if input is logical array; returns true if A is a logical array and false otherwise. It also returns true if A is an instance of a class that is derived from the logical class. logical(A) Convert numeric values to logical; returns an array that can be used for logical indexing or logical tests. true Logical 1 (true) true(n) is an n-by-n matrix of logical ones. true(m, n) is an m-by-n matrix of logical ones. true(m, n, p, ...) is an m-by-n-by-p-by-... array of logical ones. true(size(A)) is an array of logical ones that is the same size as array A. true(...,'like', p) is an array of logical ones of the same data type and sparsity as the logical array p. 30 Lectures 4 hours Nouman Azam 127 Lectures 12 hours Nouman Azam 17 Lectures 3 hours Sanjeev 37 Lectures 5 hours TELCOMA Global 22 Lectures 4 hours TELCOMA Global 18 Lectures 3 hours Phinite Academy Print Add Notes Bookmark this page
[ { "code": null, "e": 2202, "s": 2141, "text": "MATLAB offers two types of logical operators and functions −" }, { "code": null, "e": 2286, "s": 2202, "text": "Element-wise − these operators operate on corresponding elements of logical arrays." }, { "code": null, "e": 2370, "s": 2286, "text": "Element-wise − these operators operate on corresponding elements of logical arrays." }, { "code": null, "e": 2442, "s": 2370, "text": "Short-circuit − these operators operate on scalar, logical expressions." }, { "code": null, "e": 2514, "s": 2442, "text": "Short-circuit − these operators operate on scalar, logical expressions." }, { "code": null, "e": 2665, "s": 2514, "text": "Element-wise logical operators operate element-by-element on logical arrays. The symbols &, |, and ~ are the logical array operators AND, OR, and NOT." }, { "code": null, "e": 2817, "s": 2665, "text": "Short-circuit logical operators allow short-circuiting on logical operations. The symbols && and || are the logical short-circuit operators AND and OR." }, { "code": null, "e": 2868, "s": 2817, "text": "Create a script file and type the following code −" }, { "code": null, "e": 3279, "s": 2868, "text": "a = 5;\nb = 20;\n if ( a && b )\n disp('Line 1 - Condition is true');\n end\n if ( a || b )\n disp('Line 2 - Condition is true');\n end\n \n % lets change the value of a and b \n a = 0;\n b = 10;\n \n if ( a && b )\n disp('Line 3 - Condition is true');\n else\n disp('Line 3 - Condition is not true');\n end\n \n if (~(a && b))\n \n disp('Line 4 - Condition is true');\n end" }, { "code": null, "e": 3333, "s": 3279, "text": "When you run the file, it produces following result −" }, { "code": null, "e": 3446, "s": 3333, "text": "Line 1 - Condition is true\nLine 2 - Condition is true\nLine 3 - Condition is not true\nLine 4 - Condition is true\n" }, { "code": null, "e": 3576, "s": 3446, "text": "Apart from the above-mentioned logical operators, MATLAB provides the following commands or functions used for the same purpose −" }, { "code": null, "e": 3586, "s": 3576, "text": "and(A, B)" }, { "code": null, "e": 3934, "s": 3586, "text": "Finds logical AND of array or scalar inputs; performs a logical AND of all input arrays A, B, etc. and returns an array containing elements set to either logical 1 (true) or logical 0 (false). An element of the output array is set to 1 if all input arrays contain a nonzero element at that same array location. Otherwise, that element is set to 0." }, { "code": null, "e": 3941, "s": 3934, "text": "not(A)" }, { "code": null, "e": 4277, "s": 3941, "text": "Finds logical NOT of array or scalar input; performs a logical NOT of input array A and returns an array containing elements set to either logical 1 (true) or logical 0 (false). An element of the output array is set to 1 if the input array contains a zero value element at that same array location. Otherwise, that element is set to 0." }, { "code": null, "e": 4286, "s": 4277, "text": "or(A, B)" }, { "code": null, "e": 4632, "s": 4286, "text": "Finds logical OR of array or scalar inputs; performs a logical OR of all input arrays A, B, etc. and returns an array containing elements set to either logical 1 (true) or logical 0 (false). An element of the output array is set to 1 if any input arrays contain a nonzero element at that same array location. Otherwise, that element is set to 0." }, { "code": null, "e": 4642, "s": 4632, "text": "xor(A, B)" }, { "code": null, "e": 4856, "s": 4642, "text": "Logical exclusive-OR; performs an exclusive OR operation on the corresponding elements of arrays A and B. The resulting element C(i,j,...) is logical true (1) if A(i,j,...) or B(i,j,...), but not both, is nonzero." }, { "code": null, "e": 4863, "s": 4856, "text": "all(A)" }, { "code": null, "e": 4927, "s": 4863, "text": "Determine if all array elements of array A are nonzero or true." }, { "code": null, "e": 5073, "s": 4927, "text": "If A is a vector, all(A) returns logical 1 (true) if all the elements are nonzero and returns logical 0 (false) if one or more elements are zero." }, { "code": null, "e": 5219, "s": 5073, "text": "If A is a vector, all(A) returns logical 1 (true) if all the elements are nonzero and returns logical 0 (false) if one or more elements are zero." }, { "code": null, "e": 5336, "s": 5219, "text": "If A is a nonempty matrix, all(A) treats the columns of A as vectors, returning a row vector of logical 1's and 0's." }, { "code": null, "e": 5453, "s": 5336, "text": "If A is a nonempty matrix, all(A) treats the columns of A as vectors, returning a row vector of logical 1's and 0's." }, { "code": null, "e": 5518, "s": 5453, "text": "If A is an empty 0-by-0 matrix, all(A) returns logical 1 (true)." }, { "code": null, "e": 5583, "s": 5518, "text": "If A is an empty 0-by-0 matrix, all(A) returns logical 1 (true)." }, { "code": null, "e": 5806, "s": 5583, "text": "If A is a multidimensional array, all(A) acts along the first non-singleton dimension and returns an array of logical values. The size of this dimension reduces to 1 while the sizes of all other dimensions remain the same." }, { "code": null, "e": 6029, "s": 5806, "text": "If A is a multidimensional array, all(A) acts along the first non-singleton dimension and returns an array of logical values. The size of this dimension reduces to 1 while the sizes of all other dimensions remain the same." }, { "code": null, "e": 6041, "s": 6029, "text": "all(A, dim)" }, { "code": null, "e": 6097, "s": 6041, "text": "Tests along the dimension of A specified by scalar dim." }, { "code": null, "e": 6104, "s": 6097, "text": "any(A)" }, { "code": null, "e": 6326, "s": 6104, "text": "Determine if any array elements are nonzero; tests whether any of the elements along various dimensions of an array is a nonzero number or is logical 1 (true). The any function ignores entries that are NaN (Not a Number)." }, { "code": null, "e": 6508, "s": 6326, "text": "If A is a vector, any(A) returns logical 1 (true) if any of the elements of A is a nonzero number or is logical 1 (true), and returns logical 0 (false) if all the elements are zero." }, { "code": null, "e": 6690, "s": 6508, "text": "If A is a vector, any(A) returns logical 1 (true) if any of the elements of A is a nonzero number or is logical 1 (true), and returns logical 0 (false) if all the elements are zero." }, { "code": null, "e": 6807, "s": 6690, "text": "If A is a nonempty matrix, any(A) treats the columns of A as vectors, returning a row vector of logical 1's and 0's." }, { "code": null, "e": 6924, "s": 6807, "text": "If A is a nonempty matrix, any(A) treats the columns of A as vectors, returning a row vector of logical 1's and 0's." }, { "code": null, "e": 6990, "s": 6924, "text": "If A is an empty 0-by-0 matrix, any(A) returns logical 0 (false)." }, { "code": null, "e": 7056, "s": 6990, "text": "If A is an empty 0-by-0 matrix, any(A) returns logical 0 (false)." }, { "code": null, "e": 7279, "s": 7056, "text": "If A is a multidimensional array, any(A) acts along the first non-singleton dimension and returns an array of logical values. The size of this dimension reduces to 1 while the sizes of all other dimensions remain the same." }, { "code": null, "e": 7502, "s": 7279, "text": "If A is a multidimensional array, any(A) acts along the first non-singleton dimension and returns an array of logical values. The size of this dimension reduces to 1 while the sizes of all other dimensions remain the same." }, { "code": null, "e": 7513, "s": 7502, "text": "any(A,dim)" }, { "code": null, "e": 7569, "s": 7513, "text": "Tests along the dimension of A specified by scalar dim." }, { "code": null, "e": 7575, "s": 7569, "text": "false" }, { "code": null, "e": 7593, "s": 7575, "text": "Logical 0 (false)" }, { "code": null, "e": 7602, "s": 7593, "text": "false(n)" }, { "code": null, "e": 7639, "s": 7602, "text": "is an n-by-n matrix of logical zeros" }, { "code": null, "e": 7651, "s": 7639, "text": "false(m, n)" }, { "code": null, "e": 7689, "s": 7651, "text": "is an m-by-n matrix of logical zeros." }, { "code": null, "e": 7709, "s": 7689, "text": "false(m, n, p, ...)" }, { "code": null, "e": 7758, "s": 7709, "text": "is an m-by-n-by-p-by-... array of logical zeros." }, { "code": null, "e": 7773, "s": 7758, "text": "false(size(A))" }, { "code": null, "e": 7836, "s": 7773, "text": "is an array of logical zeros that is the same size as array A." }, { "code": null, "e": 7856, "s": 7836, "text": "false(...,'like',p)" }, { "code": null, "e": 7944, "s": 7856, "text": "is an array of logical zeros of the same data type and sparsity as the logical array p." }, { "code": null, "e": 7959, "s": 7944, "text": "ind = find(X)" }, { "code": null, "e": 8299, "s": 7959, "text": "Find indices and values of nonzero elements; locates all nonzero elements of array X, and returns the linear indices of those elements in a vector. If X is a row vector, then the returned vector is a row vector; otherwise, it returns a column vector. If X contains no nonzero elements or is an empty array, then an empty array is returned." }, { "code": null, "e": 8316, "s": 8299, "text": "ind = find(X, k)" }, { "code": null, "e": 8342, "s": 8316, "text": "ind = find(X, k, 'first')" }, { "code": null, "e": 8491, "s": 8342, "text": "Returns at most the first k indices corresponding to the nonzero entries of X. k must be a positive integer, but it can be of any numeric data type." }, { "code": null, "e": 8516, "s": 8491, "text": "ind = find(X, k, 'last')" }, { "code": null, "e": 8594, "s": 8516, "text": "returns at most the last k indices corresponding to the nonzero entries of X." }, { "code": null, "e": 8619, "s": 8594, "text": "[row,col] = find(X, ...)" }, { "code": null, "e": 8850, "s": 8619, "text": "Returns the row and column indices of the nonzero entries in the matrix X. This syntax is especially useful when working with sparse matrices. If X is an N-dimensional array with N > 2, col contains linear indices for the columns." }, { "code": null, "e": 8877, "s": 8850, "text": "[row,col,v] = find(X, ...)" }, { "code": null, "e": 9133, "s": 8877, "text": "Returns a column or row vector v of the nonzero entries in X, as well as row and column indices. If X is a logical expression, then v is a logical array. Output v contains the non-zero elements of the logical array obtained by evaluating the expression X." }, { "code": null, "e": 9146, "s": 9133, "text": "islogical(A)" }, { "code": null, "e": 9333, "s": 9146, "text": "Determine if input is logical array; returns true if A is a logical array and false otherwise. It also returns true if A is an instance of a class that is derived from the logical class." }, { "code": null, "e": 9344, "s": 9333, "text": "logical(A)" }, { "code": null, "e": 9452, "s": 9344, "text": "Convert numeric values to logical; returns an array that can be used for logical indexing or logical tests." }, { "code": null, "e": 9457, "s": 9452, "text": "true" }, { "code": null, "e": 9474, "s": 9457, "text": "Logical 1 (true)" }, { "code": null, "e": 9482, "s": 9474, "text": "true(n)" }, { "code": null, "e": 9519, "s": 9482, "text": "is an n-by-n matrix of logical ones." }, { "code": null, "e": 9530, "s": 9519, "text": "true(m, n)" }, { "code": null, "e": 9567, "s": 9530, "text": "is an m-by-n matrix of logical ones." }, { "code": null, "e": 9586, "s": 9567, "text": "true(m, n, p, ...)" }, { "code": null, "e": 9634, "s": 9586, "text": "is an m-by-n-by-p-by-... array of logical ones." }, { "code": null, "e": 9648, "s": 9634, "text": "true(size(A))" }, { "code": null, "e": 9710, "s": 9648, "text": "is an array of logical ones that is the same size as array A." }, { "code": null, "e": 9730, "s": 9710, "text": "true(...,'like', p)" }, { "code": null, "e": 9817, "s": 9730, "text": "is an array of logical ones of the same data type and sparsity as the logical array p." }, { "code": null, "e": 9850, "s": 9817, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 9863, "s": 9850, "text": " Nouman Azam" }, { "code": null, "e": 9898, "s": 9863, "text": "\n 127 Lectures \n 12 hours \n" }, { "code": null, "e": 9911, "s": 9898, "text": " Nouman Azam" }, { "code": null, "e": 9944, "s": 9911, "text": "\n 17 Lectures \n 3 hours \n" }, { "code": null, "e": 9953, "s": 9944, "text": " Sanjeev" }, { "code": null, "e": 9986, "s": 9953, "text": "\n 37 Lectures \n 5 hours \n" }, { "code": null, "e": 10002, "s": 9986, "text": " TELCOMA Global" }, { "code": null, "e": 10035, "s": 10002, "text": "\n 22 Lectures \n 4 hours \n" }, { "code": null, "e": 10051, "s": 10035, "text": " TELCOMA Global" }, { "code": null, "e": 10084, "s": 10051, "text": "\n 18 Lectures \n 3 hours \n" }, { "code": null, "e": 10101, "s": 10084, "text": " Phinite Academy" }, { "code": null, "e": 10108, "s": 10101, "text": " Print" }, { "code": null, "e": 10119, "s": 10108, "text": " Add Notes" } ]
dnssec-keygen command in Linux with Examples - GeeksforGeeks
01 Sep, 2020 dnssec-keygen command is used to generate keys for DNSSEC (DNS Security Extensions). DNSSEC is an extension to the regular DNS (Domain Name System) technology but with added authentication for the DNS data. This authentication is carried out using public key cryptography technique and the above mentioned command produces the public/private key pair. Syntax: dnssec-keygen [options] name Example: dnssec-keygen gfg.org In the above example, keys are generated for gfg.org. Since no options are provided, the default algorithm (RSASHA1) is used for generation and the keys are of the default size (1024 bits). This option specifies the number of bits the key should contain. The size of the key depends upon the algorithm used. RSA Algorithm: 512-4096 bits DH Algorithm: 128-4096 bits DSA Algorithm: 512-1024 bits (multiples of 64) HMAC Algorithm: 1-512 bits Example: dnssec-keygen -b 1024 gfg.org This option is used to select the crypt algorithm for the key generation. If an algorithm is specified like this, use of the -b to set key size is mandatory. The available algorithms are: RSAMD5 RSASHA1 (default algorithm) RSASHA256 RSASHA512 DH DSA HMAC-MD5 HMAC-SHA1 HMAC-SHA224 HMAC-SHA256 HMAC-SHA384 HMAC-SHA512 Example: dnssec-keygen -a RSASHA1 -b 1024 gfg.org This option is used to specify the owner type of the key. The accepted values are: ZONE HOST/ENTITY USER Example: dnssec-keygen -n ZONE gfg.org This option mandates the creation of the keys using a NSEC3-capable algorithm. NSEC3RSASHA1 will be used by default if no algorithm is mentioned explicitly. Example: dnssec-keygen -a RSASHA256 -b 1024 -3 gfg.org This is used to specify a flag for the generated key. The recognized flags are: KSK (Key Signing Key) REVOKE Example : dnssec-keygen -a RSASHA256 -b 1024 -f KSK gfg.org DNS could be partitioned according to the class. This option is used to specify the class that the DNS record should have. If you do not specify anything using this option, IN is used by default. The following are a list of DNS classes: IN (Internet) – Default Class CH (CHAOS) HS (Hesiod) Example: dnssec-keygen -c CH gfg.org This option is used to specify the type of the key. AUTHCONF is used by default if not specified explicitly. The possible types are: AUTHCONF NOAUTHCONF NOAUTH NOCONF Example: dnssec-keygen -a RSASHA256 -b 1024 -t NOAUTH gfg.org Linux-networking-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. nohup Command in Linux with Examples scp command in Linux with Examples Thread functions in C/C++ mv command in Linux with examples chown command in Linux with Examples SED command in Linux | Set 2 Docker - COPY Instruction Array Basics in Shell Scripting | Set 1 Basic Operators in Shell Scripting nslookup command in Linux with Examples
[ { "code": null, "e": 24406, "s": 24378, "text": "\n01 Sep, 2020" }, { "code": null, "e": 24758, "s": 24406, "text": "dnssec-keygen command is used to generate keys for DNSSEC (DNS Security Extensions). DNSSEC is an extension to the regular DNS (Domain Name System) technology but with added authentication for the DNS data. This authentication is carried out using public key cryptography technique and the above mentioned command produces the public/private key pair." }, { "code": null, "e": 24766, "s": 24758, "text": "Syntax:" }, { "code": null, "e": 24796, "s": 24766, "text": "dnssec-keygen [options] name\n" }, { "code": null, "e": 24805, "s": 24796, "text": "Example:" }, { "code": null, "e": 24828, "s": 24805, "text": "dnssec-keygen gfg.org\n" }, { "code": null, "e": 25018, "s": 24828, "text": "In the above example, keys are generated for gfg.org. Since no options are provided, the default algorithm (RSASHA1) is used for generation and the keys are of the default size (1024 bits)." }, { "code": null, "e": 25136, "s": 25018, "text": "This option specifies the number of bits the key should contain. The size of the key depends upon the algorithm used." }, { "code": null, "e": 25165, "s": 25136, "text": "RSA Algorithm: 512-4096 bits" }, { "code": null, "e": 25193, "s": 25165, "text": "DH Algorithm: 128-4096 bits" }, { "code": null, "e": 25240, "s": 25193, "text": "DSA Algorithm: 512-1024 bits (multiples of 64)" }, { "code": null, "e": 25267, "s": 25240, "text": "HMAC Algorithm: 1-512 bits" }, { "code": null, "e": 25276, "s": 25267, "text": "Example:" }, { "code": null, "e": 25307, "s": 25276, "text": "dnssec-keygen -b 1024 gfg.org\n" }, { "code": null, "e": 25495, "s": 25307, "text": "This option is used to select the crypt algorithm for the key generation. If an algorithm is specified like this, use of the -b to set key size is mandatory. The available algorithms are:" }, { "code": null, "e": 25502, "s": 25495, "text": "RSAMD5" }, { "code": null, "e": 25530, "s": 25502, "text": "RSASHA1 (default algorithm)" }, { "code": null, "e": 25540, "s": 25530, "text": "RSASHA256" }, { "code": null, "e": 25550, "s": 25540, "text": "RSASHA512" }, { "code": null, "e": 25553, "s": 25550, "text": "DH" }, { "code": null, "e": 25557, "s": 25553, "text": "DSA" }, { "code": null, "e": 25566, "s": 25557, "text": "HMAC-MD5" }, { "code": null, "e": 25576, "s": 25566, "text": "HMAC-SHA1" }, { "code": null, "e": 25588, "s": 25576, "text": "HMAC-SHA224" }, { "code": null, "e": 25600, "s": 25588, "text": "HMAC-SHA256" }, { "code": null, "e": 25612, "s": 25600, "text": "HMAC-SHA384" }, { "code": null, "e": 25624, "s": 25612, "text": "HMAC-SHA512" }, { "code": null, "e": 25633, "s": 25624, "text": "Example:" }, { "code": null, "e": 25674, "s": 25633, "text": "dnssec-keygen -a RSASHA1 -b 1024 gfg.org" }, { "code": null, "e": 25757, "s": 25674, "text": "This option is used to specify the owner type of the key. The accepted values are:" }, { "code": null, "e": 25762, "s": 25757, "text": "ZONE" }, { "code": null, "e": 25774, "s": 25762, "text": "HOST/ENTITY" }, { "code": null, "e": 25779, "s": 25774, "text": "USER" }, { "code": null, "e": 25788, "s": 25779, "text": "Example:" }, { "code": null, "e": 25819, "s": 25788, "text": "dnssec-keygen -n ZONE gfg.org\n" }, { "code": null, "e": 25976, "s": 25819, "text": "This option mandates the creation of the keys using a NSEC3-capable algorithm. NSEC3RSASHA1 will be used by default if no algorithm is mentioned explicitly." }, { "code": null, "e": 25985, "s": 25976, "text": "Example:" }, { "code": null, "e": 26032, "s": 25985, "text": "dnssec-keygen -a RSASHA256 -b 1024 -3 gfg.org\n" }, { "code": null, "e": 26112, "s": 26032, "text": "This is used to specify a flag for the generated key. The recognized flags are:" }, { "code": null, "e": 26134, "s": 26112, "text": "KSK (Key Signing Key)" }, { "code": null, "e": 26141, "s": 26134, "text": "REVOKE" }, { "code": null, "e": 26151, "s": 26141, "text": "Example :" }, { "code": null, "e": 26202, "s": 26151, "text": "dnssec-keygen -a RSASHA256 -b 1024 -f KSK gfg.org\n" }, { "code": null, "e": 26439, "s": 26202, "text": "DNS could be partitioned according to the class. This option is used to specify the class that the DNS record should have. If you do not specify anything using this option, IN is used by default. The following are a list of DNS classes:" }, { "code": null, "e": 26469, "s": 26439, "text": "IN (Internet) – Default Class" }, { "code": null, "e": 26480, "s": 26469, "text": "CH (CHAOS)" }, { "code": null, "e": 26492, "s": 26480, "text": "HS (Hesiod)" }, { "code": null, "e": 26501, "s": 26492, "text": "Example:" }, { "code": null, "e": 26530, "s": 26501, "text": "dnssec-keygen -c CH gfg.org\n" }, { "code": null, "e": 26664, "s": 26530, "text": "This option is used to specify the type of the key. AUTHCONF is used by default if not specified explicitly. The possible types are: " }, { "code": null, "e": 26673, "s": 26664, "text": "AUTHCONF" }, { "code": null, "e": 26684, "s": 26673, "text": "NOAUTHCONF" }, { "code": null, "e": 26691, "s": 26684, "text": "NOAUTH" }, { "code": null, "e": 26698, "s": 26691, "text": "NOCONF" }, { "code": null, "e": 26707, "s": 26698, "text": "Example:" }, { "code": null, "e": 26761, "s": 26707, "text": "dnssec-keygen -a RSASHA256 -b 1024 -t NOAUTH gfg.org\n" }, { "code": null, "e": 26787, "s": 26761, "text": "Linux-networking-commands" }, { "code": null, "e": 26798, "s": 26787, "text": "Linux-Unix" }, { "code": null, "e": 26896, "s": 26798, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26933, "s": 26896, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 26968, "s": 26933, "text": "scp command in Linux with Examples" }, { "code": null, "e": 26994, "s": 26968, "text": "Thread functions in C/C++" }, { "code": null, "e": 27028, "s": 26994, "text": "mv command in Linux with examples" }, { "code": null, "e": 27065, "s": 27028, "text": "chown command in Linux with Examples" }, { "code": null, "e": 27094, "s": 27065, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 27120, "s": 27094, "text": "Docker - COPY Instruction" }, { "code": null, "e": 27160, "s": 27120, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 27195, "s": 27160, "text": "Basic Operators in Shell Scripting" } ]
Seaborn - Pair Grid
PairGrid allows us to draw a grid of subplots using the same plot type to visualize data. Unlike FacetGrid, it uses different pair of variable for each subplot. It forms a matrix of sub-plots. It is also sometimes called as “scatterplot matrix”. The usage of pairgrid is similar to facetgrid. First initialise the grid and then pass the plotting function. import pandas as pd import seaborn as sb from matplotlib import pyplot as plt df = sb.load_dataset('iris') g = sb.PairGrid(df) g.map(plt.scatter); plt.show() It is also possible to plot a different function on the diagonal to show the univariate distribution of the variable in each column. import pandas as pd import seaborn as sb from matplotlib import pyplot as plt df = sb.load_dataset('iris') g = sb.PairGrid(df) g.map_diag(plt.hist) g.map_offdiag(plt.scatter); plt.show() We can customize the color of these plots using another categorical variable. For example, the iris dataset has four measurements for each of three different species of iris flowers so you can see how they differ. import pandas as pd import seaborn as sb from matplotlib import pyplot as plt df = sb.load_dataset('iris') g = sb.PairGrid(df) g.map_diag(plt.hist) g.map_offdiag(plt.scatter); plt.show() We can use a different function in the upper and lower triangles to see different aspects of the relationship. import pandas as pd import seaborn as sb from matplotlib import pyplot as plt df = sb.load_dataset('iris') g = sb.PairGrid(df) g.map_upper(plt.scatter) g.map_lower(sb.kdeplot, cmap = "Blues_d") g.map_diag(sb.kdeplot, lw = 3, legend = False); plt.show() 11 Lectures 4 hours DATAhill Solutions Srinivas Reddy 11 Lectures 2.5 hours DATAhill Solutions Srinivas Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2129, "s": 2039, "text": "PairGrid allows us to draw a grid of subplots using the same plot type to visualize data." }, { "code": null, "e": 2285, "s": 2129, "text": "Unlike FacetGrid, it uses different pair of variable for each subplot. It forms a matrix of sub-plots. It is also sometimes called as “scatterplot matrix”." }, { "code": null, "e": 2395, "s": 2285, "text": "The usage of pairgrid is similar to facetgrid. First initialise the grid and then pass the plotting function." }, { "code": null, "e": 2554, "s": 2395, "text": "import pandas as pd\nimport seaborn as sb\nfrom matplotlib import pyplot as plt\ndf = sb.load_dataset('iris')\ng = sb.PairGrid(df)\ng.map(plt.scatter);\nplt.show()\n" }, { "code": null, "e": 2687, "s": 2554, "text": "It is also possible to plot a different function on the diagonal to show the univariate distribution of the variable in each column." }, { "code": null, "e": 2875, "s": 2687, "text": "import pandas as pd\nimport seaborn as sb\nfrom matplotlib import pyplot as plt\ndf = sb.load_dataset('iris')\ng = sb.PairGrid(df)\ng.map_diag(plt.hist)\ng.map_offdiag(plt.scatter);\nplt.show()\n" }, { "code": null, "e": 3089, "s": 2875, "text": "We can customize the color of these plots using another categorical variable. For example, the iris dataset has four measurements for each of three different species of iris flowers so you can see how they differ." }, { "code": null, "e": 3277, "s": 3089, "text": "import pandas as pd\nimport seaborn as sb\nfrom matplotlib import pyplot as plt\ndf = sb.load_dataset('iris')\ng = sb.PairGrid(df)\ng.map_diag(plt.hist)\ng.map_offdiag(plt.scatter);\nplt.show()\n" }, { "code": null, "e": 3388, "s": 3277, "text": "We can use a different function in the upper and lower triangles to see different aspects of the relationship." }, { "code": null, "e": 3642, "s": 3388, "text": "import pandas as pd\nimport seaborn as sb\nfrom matplotlib import pyplot as plt\ndf = sb.load_dataset('iris')\ng = sb.PairGrid(df)\ng.map_upper(plt.scatter)\ng.map_lower(sb.kdeplot, cmap = \"Blues_d\")\ng.map_diag(sb.kdeplot, lw = 3, legend = False);\nplt.show()\n" }, { "code": null, "e": 3675, "s": 3642, "text": "\n 11 Lectures \n 4 hours \n" }, { "code": null, "e": 3710, "s": 3675, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 3745, "s": 3710, "text": "\n 11 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3780, "s": 3745, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 3787, "s": 3780, "text": " Print" }, { "code": null, "e": 3798, "s": 3787, "text": " Add Notes" } ]
Interactive Pivot Tables in Jupyter Notebook | by Satyam Kumar | Towards Data Science
Python has achieved popularity in a short span of time, still, it falls short to interact with data in some cases, that is where excel takes a lead. For the development of a model, the initial steps are data understanding and Exploratory data analysis (EDA). For EDA you need the ability of flexibility to play around with data. Python falls short in terms of interacting with the data in the case of creating pivot tables. For creating pivot tables, Excel takes a lead, as it comes up with interactive and dynamic development of tables. Creating a pivot table in pandas is a bit combustion process. The structure of the pivot table needs to be decided in advance and accordingly, the script needs to be developed. To make some manipulation in the pivot table requires changing the code again and run the script. This is a combustion process to generate insights as to proceed with model building. pd.pivot_table(df, values='Survived', index=['Pclass'], columns=['Sex'], aggfunc='sum' ) pd.pivot_table(df, values='Survived', index=['Pclass','Embarked'], columns=['Sex'], aggfunc='sum' ) Pivot tables are used to get insights about the data during EDA, to generate pivot tables in pandas, code needs to be manipulated for each table, which makes it a bit of combustion. Here, PivotTable.js comes into the picture, and it helps to create interactive pivot tables. PivotTable.js is an open-source Javascript Pivot Table (aka Pivot Grid, Pivot Chart, Cross-Tab) implementation with drag’n’ drop functionality. pip install pivottablejs Now trying to generate the same pivot tables as developed using pandas earlier in this article. PivotTable.js provides the privilege of choosing the aggregate functions from the drop-down list. Different representations of pivot tables, and heatmaps. Several types of plots including bar plot, stacked bar plot, line chart, area chart, scatter chart, treemap, etc. Including PivotTable.js in the workflow enables us to generate insights about the data easily. This library comes up with features to generate several plots from the pivot table in real-time, which enables us to speed up the work during data wrangling. You can find the GitHub repository for PivotTable.js here. [1] PivotTable.js Examples:https://pivottable.js.org/examples/ Thank You for Reading
[ { "code": null, "e": 431, "s": 172, "text": "Python has achieved popularity in a short span of time, still, it falls short to interact with data in some cases, that is where excel takes a lead. For the development of a model, the initial steps are data understanding and Exploratory data analysis (EDA)." }, { "code": null, "e": 710, "s": 431, "text": "For EDA you need the ability of flexibility to play around with data. Python falls short in terms of interacting with the data in the case of creating pivot tables. For creating pivot tables, Excel takes a lead, as it comes up with interactive and dynamic development of tables." }, { "code": null, "e": 1070, "s": 710, "text": "Creating a pivot table in pandas is a bit combustion process. The structure of the pivot table needs to be decided in advance and accordingly, the script needs to be developed. To make some manipulation in the pivot table requires changing the code again and run the script. This is a combustion process to generate insights as to proceed with model building." }, { "code": null, "e": 1229, "s": 1070, "text": "pd.pivot_table(df, values='Survived', index=['Pclass'], columns=['Sex'], aggfunc='sum' )" }, { "code": null, "e": 1399, "s": 1229, "text": "pd.pivot_table(df, values='Survived', index=['Pclass','Embarked'], columns=['Sex'], aggfunc='sum' )" }, { "code": null, "e": 1581, "s": 1399, "text": "Pivot tables are used to get insights about the data during EDA, to generate pivot tables in pandas, code needs to be manipulated for each table, which makes it a bit of combustion." }, { "code": null, "e": 1674, "s": 1581, "text": "Here, PivotTable.js comes into the picture, and it helps to create interactive pivot tables." }, { "code": null, "e": 1818, "s": 1674, "text": "PivotTable.js is an open-source Javascript Pivot Table (aka Pivot Grid, Pivot Chart, Cross-Tab) implementation with drag’n’ drop functionality." }, { "code": null, "e": 1843, "s": 1818, "text": "pip install pivottablejs" }, { "code": null, "e": 1939, "s": 1843, "text": "Now trying to generate the same pivot tables as developed using pandas earlier in this article." }, { "code": null, "e": 2037, "s": 1939, "text": "PivotTable.js provides the privilege of choosing the aggregate functions from the drop-down list." }, { "code": null, "e": 2094, "s": 2037, "text": "Different representations of pivot tables, and heatmaps." }, { "code": null, "e": 2208, "s": 2094, "text": "Several types of plots including bar plot, stacked bar plot, line chart, area chart, scatter chart, treemap, etc." }, { "code": null, "e": 2461, "s": 2208, "text": "Including PivotTable.js in the workflow enables us to generate insights about the data easily. This library comes up with features to generate several plots from the pivot table in real-time, which enables us to speed up the work during data wrangling." }, { "code": null, "e": 2520, "s": 2461, "text": "You can find the GitHub repository for PivotTable.js here." }, { "code": null, "e": 2583, "s": 2520, "text": "[1] PivotTable.js Examples:https://pivottable.js.org/examples/" } ]
Line of Best Fit in Linear Regression | by Indhumathy Chelliah | Towards Data Science
Linear Regression is one of the most important algorithms in machine learning. It is the statistical way of measuring the relationship between one or more independent variables vs one dependent variable. The Linear Regression model attempts to find the relationship between variables by finding the best fit line. Let’s learn about how the model finds the best fit line and how to measure the goodness of fit in this article in detail Coefficient correlation rVisualizing coefficient correlationModel coefficient → m and c *Slope*InterceptLine of Best FitCost FunctionCoefficient of Determination →R2 → R-squaredCorrelation Coefficient vs Coefficient of Determination Coefficient correlation r Visualizing coefficient correlation Model coefficient → m and c *Slope*Intercept Line of Best Fit Cost Function Coefficient of Determination →R2 → R-squared Correlation Coefficient vs Coefficient of Determination Simple Linear Regression is the linear regression model with one independent variable and one dependent variable. Example: Years of Experience vs Salary, Area vs House Price Before building a simple linear regression model, we have to check the linear relationship between the two variables. We can measure the strength of the linear relationship, by using a correlation coefficient. It is the measure of linear association between two variables. It determines the strength of linear association and its direction. Covariance checks how the two variables vary together. Covariance depends on units of x and y. Covariance ranges from -∞ to + ∞.But Correlation coefficient is unit-free. It is just a number. Coefficient Correlation r ranges from -1 to +1 If r=0 → It means there is no linear relationship. It doesn’t mean that there is no relationship r will be negative if one variable increases, other variable decreases. r will be positive, if one variable increases, the other variable also increases. If r is close to 1 or -1 means, x and y are strongly correlated.If r is close to 0 means, x and y are not correlated. [No linear relationship] Example: “Years of experience” Vs “Salary”. Here we want to predict the salary for a given ‘Year of experience’. Salary → dependent variableYears_of_Experience →Independent Variable. Scatterplot to visualize the correlation Scatterplot to visualize the correlation df=pd.read_csv('salary.csv')sns.scatterplot(x='Years_Of_Exp',y='Salary',data=df,color='darkorange') 2. Exact r value -heatmap sns.heatmap(df.corr(),annot=True) r is 0.98 → It indicates both the variables are strongly correlated. After finding the correlation between the variables[independent variable and target variable], and if the variables are linearly correlated, we can proceed with the Linear Regression model. The Linear Regression model will find out the best fit line for the data points in the scatter cloud. Let’s learn how to find the best fit line. y=mx+c m →slopec →intercept Slope m and Intercept c are model coefficient/model parameters/regression coefficients. Slope basically says how steep the line is. The slope is calculated by a change in y divided by a change in x The slope will be negative if one increases and the other one decreases.The slope will be positive if x increases and y increases. The value of slope will range from -∞ to + ∞. [Since we didn’t normalize the value, the slope will depend on units. So, it can take any value from -∞ to + ∞] The value of y when x is 0. When the straight line passes through the origin intercept is 0. The slope will remain constant for a line. We can calculate the slope by taking any two points in the straight line, by using the formula dy/dx. The Linear Regression model have to find the line of best fit. We know the equation of a line is y=mx+c. There are infinite m and c possibilities, which one to chose? Out of all possible lines, how to find the best fit line? The line of best fit is calculated by using the cost function — Least Sum of Squares of Errors. The line of best fit will have the least sum of squares error. The least Sum of Squares of Errors is used as the cost function for Linear Regression. For all possible lines, calculate the sum of squares of errors. The line which has the least sum of squares of errors is the best fit line. Error is the difference between the actual value of y and the predicted value of y. We have to calculate error/residual for all data pointssquare the error/residuals.Then we have to calculate the sum of squares of all the errors.Out of all possible lines, the line which has the least sum of squares of errors is the line of best fit. We have to calculate error/residual for all data points square the error/residuals. Then we have to calculate the sum of squares of all the errors. Out of all possible lines, the line which has the least sum of squares of errors is the line of best fit. If we are not squaring the error, the negative and positive signs will cancel. We will end up with error=0So we are interested only in the magnitude of the error. How much the actual value deviates from the predicted value.So, why we didn’t consider the absolute value of error. Our motive is to find the least error. If the errors are squared, it will be easy to differentiate between the errors comparing to taking the absolute value of the error.Easier to differentiate the errors, it will be easier to identify the least sum of squares of error. If we are not squaring the error, the negative and positive signs will cancel. We will end up with error=0 So we are interested only in the magnitude of the error. How much the actual value deviates from the predicted value. So, why we didn’t consider the absolute value of error. Our motive is to find the least error. If the errors are squared, it will be easy to differentiate between the errors comparing to taking the absolute value of the error. Easier to differentiate the errors, it will be easier to identify the least sum of squares of error. Out of all possible lines, the linear regression model comes up with the best fit line with the least sum of squares of error. Slope and Intercept of the best fit line are the model coefficient. Now we have to measure how good is our best fit line? R-squared is one of the measures of goodness of the model. (best-fit line) SSE →Sum of squares of ErrorsSST →Sum of Squares Total What is the Total Error? Before building a linear regression model, we can say that the expected value of y is the mean/average value of y. The difference between the mean of y and the actual value of y is the Total Error. Total Error is the Total variance. Total Variance is the amount of variance present in the data. After building a linear regression model, our model predicts the y value. The difference between the mean of y and the predicted y value is the Regression Error.Regression Error is the Explained Variance. Explained Variance means the amount of variance captured by the model. Residual/Error is the difference between the actual y value and the predicted y value.Residual/Error is the Unexplained Variance. Total Error = Residual Error + Regression Error Coefficient of determination or R-squared measures how much variance in y is explained by the model. The R-squared value ranges between 0 and 1 0 → being a bad model and 1 being good. Correlation Coefficient- r ranges from -1 to +1 The coefficient of Determination- R2 ranges from 0 to 1 Slope and intercept are model coefficients or model parameters. Thank you for reading my article, I hope you found it helpful! towardsdatascience.com Watch this space for more articles on Python and DataScience. If you like to read more of my tutorials, follow me on Medium, LinkedIn, Twitter. Become a Medium Member by Clicking here: https://indhumathychelliah.medium.com/membership
[ { "code": null, "e": 375, "s": 171, "text": "Linear Regression is one of the most important algorithms in machine learning. It is the statistical way of measuring the relationship between one or more independent variables vs one dependent variable." }, { "code": null, "e": 606, "s": 375, "text": "The Linear Regression model attempts to find the relationship between variables by finding the best fit line. Let’s learn about how the model finds the best fit line and how to measure the goodness of fit in this article in detail" }, { "code": null, "e": 839, "s": 606, "text": "Coefficient correlation rVisualizing coefficient correlationModel coefficient → m and c *Slope*InterceptLine of Best FitCost FunctionCoefficient of Determination →R2 → R-squaredCorrelation Coefficient vs Coefficient of Determination" }, { "code": null, "e": 865, "s": 839, "text": "Coefficient correlation r" }, { "code": null, "e": 901, "s": 865, "text": "Visualizing coefficient correlation" }, { "code": null, "e": 946, "s": 901, "text": "Model coefficient → m and c *Slope*Intercept" }, { "code": null, "e": 963, "s": 946, "text": "Line of Best Fit" }, { "code": null, "e": 977, "s": 963, "text": "Cost Function" }, { "code": null, "e": 1022, "s": 977, "text": "Coefficient of Determination →R2 → R-squared" }, { "code": null, "e": 1078, "s": 1022, "text": "Correlation Coefficient vs Coefficient of Determination" }, { "code": null, "e": 1192, "s": 1078, "text": "Simple Linear Regression is the linear regression model with one independent variable and one dependent variable." }, { "code": null, "e": 1252, "s": 1192, "text": "Example: Years of Experience vs Salary, Area vs House Price" }, { "code": null, "e": 1370, "s": 1252, "text": "Before building a simple linear regression model, we have to check the linear relationship between the two variables." }, { "code": null, "e": 1462, "s": 1370, "text": "We can measure the strength of the linear relationship, by using a correlation coefficient." }, { "code": null, "e": 1593, "s": 1462, "text": "It is the measure of linear association between two variables. It determines the strength of linear association and its direction." }, { "code": null, "e": 1648, "s": 1593, "text": "Covariance checks how the two variables vary together." }, { "code": null, "e": 1784, "s": 1648, "text": "Covariance depends on units of x and y. Covariance ranges from -∞ to + ∞.But Correlation coefficient is unit-free. It is just a number." }, { "code": null, "e": 1831, "s": 1784, "text": "Coefficient Correlation r ranges from -1 to +1" }, { "code": null, "e": 1928, "s": 1831, "text": "If r=0 → It means there is no linear relationship. It doesn’t mean that there is no relationship" }, { "code": null, "e": 2000, "s": 1928, "text": "r will be negative if one variable increases, other variable decreases." }, { "code": null, "e": 2082, "s": 2000, "text": "r will be positive, if one variable increases, the other variable also increases." }, { "code": null, "e": 2225, "s": 2082, "text": "If r is close to 1 or -1 means, x and y are strongly correlated.If r is close to 0 means, x and y are not correlated. [No linear relationship]" }, { "code": null, "e": 2338, "s": 2225, "text": "Example: “Years of experience” Vs “Salary”. Here we want to predict the salary for a given ‘Year of experience’." }, { "code": null, "e": 2408, "s": 2338, "text": "Salary → dependent variableYears_of_Experience →Independent Variable." }, { "code": null, "e": 2449, "s": 2408, "text": "Scatterplot to visualize the correlation" }, { "code": null, "e": 2490, "s": 2449, "text": "Scatterplot to visualize the correlation" }, { "code": null, "e": 2590, "s": 2490, "text": "df=pd.read_csv('salary.csv')sns.scatterplot(x='Years_Of_Exp',y='Salary',data=df,color='darkorange')" }, { "code": null, "e": 2616, "s": 2590, "text": "2. Exact r value -heatmap" }, { "code": null, "e": 2650, "s": 2616, "text": "sns.heatmap(df.corr(),annot=True)" }, { "code": null, "e": 2719, "s": 2650, "text": "r is 0.98 → It indicates both the variables are strongly correlated." }, { "code": null, "e": 2909, "s": 2719, "text": "After finding the correlation between the variables[independent variable and target variable], and if the variables are linearly correlated, we can proceed with the Linear Regression model." }, { "code": null, "e": 3011, "s": 2909, "text": "The Linear Regression model will find out the best fit line for the data points in the scatter cloud." }, { "code": null, "e": 3054, "s": 3011, "text": "Let’s learn how to find the best fit line." }, { "code": null, "e": 3061, "s": 3054, "text": "y=mx+c" }, { "code": null, "e": 3082, "s": 3061, "text": "m →slopec →intercept" }, { "code": null, "e": 3170, "s": 3082, "text": "Slope m and Intercept c are model coefficient/model parameters/regression coefficients." }, { "code": null, "e": 3280, "s": 3170, "text": "Slope basically says how steep the line is. The slope is calculated by a change in y divided by a change in x" }, { "code": null, "e": 3411, "s": 3280, "text": "The slope will be negative if one increases and the other one decreases.The slope will be positive if x increases and y increases." }, { "code": null, "e": 3457, "s": 3411, "text": "The value of slope will range from -∞ to + ∞." }, { "code": null, "e": 3569, "s": 3457, "text": "[Since we didn’t normalize the value, the slope will depend on units. So, it can take any value from -∞ to + ∞]" }, { "code": null, "e": 3662, "s": 3569, "text": "The value of y when x is 0. When the straight line passes through the origin intercept is 0." }, { "code": null, "e": 3807, "s": 3662, "text": "The slope will remain constant for a line. We can calculate the slope by taking any two points in the straight line, by using the formula dy/dx." }, { "code": null, "e": 3870, "s": 3807, "text": "The Linear Regression model have to find the line of best fit." }, { "code": null, "e": 3974, "s": 3870, "text": "We know the equation of a line is y=mx+c. There are infinite m and c possibilities, which one to chose?" }, { "code": null, "e": 4032, "s": 3974, "text": "Out of all possible lines, how to find the best fit line?" }, { "code": null, "e": 4128, "s": 4032, "text": "The line of best fit is calculated by using the cost function — Least Sum of Squares of Errors." }, { "code": null, "e": 4191, "s": 4128, "text": "The line of best fit will have the least sum of squares error." }, { "code": null, "e": 4278, "s": 4191, "text": "The least Sum of Squares of Errors is used as the cost function for Linear Regression." }, { "code": null, "e": 4418, "s": 4278, "text": "For all possible lines, calculate the sum of squares of errors. The line which has the least sum of squares of errors is the best fit line." }, { "code": null, "e": 4502, "s": 4418, "text": "Error is the difference between the actual value of y and the predicted value of y." }, { "code": null, "e": 4753, "s": 4502, "text": "We have to calculate error/residual for all data pointssquare the error/residuals.Then we have to calculate the sum of squares of all the errors.Out of all possible lines, the line which has the least sum of squares of errors is the line of best fit." }, { "code": null, "e": 4809, "s": 4753, "text": "We have to calculate error/residual for all data points" }, { "code": null, "e": 4837, "s": 4809, "text": "square the error/residuals." }, { "code": null, "e": 4901, "s": 4837, "text": "Then we have to calculate the sum of squares of all the errors." }, { "code": null, "e": 5007, "s": 4901, "text": "Out of all possible lines, the line which has the least sum of squares of errors is the line of best fit." }, { "code": null, "e": 5557, "s": 5007, "text": "If we are not squaring the error, the negative and positive signs will cancel. We will end up with error=0So we are interested only in the magnitude of the error. How much the actual value deviates from the predicted value.So, why we didn’t consider the absolute value of error. Our motive is to find the least error. If the errors are squared, it will be easy to differentiate between the errors comparing to taking the absolute value of the error.Easier to differentiate the errors, it will be easier to identify the least sum of squares of error." }, { "code": null, "e": 5664, "s": 5557, "text": "If we are not squaring the error, the negative and positive signs will cancel. We will end up with error=0" }, { "code": null, "e": 5782, "s": 5664, "text": "So we are interested only in the magnitude of the error. How much the actual value deviates from the predicted value." }, { "code": null, "e": 6009, "s": 5782, "text": "So, why we didn’t consider the absolute value of error. Our motive is to find the least error. If the errors are squared, it will be easy to differentiate between the errors comparing to taking the absolute value of the error." }, { "code": null, "e": 6110, "s": 6009, "text": "Easier to differentiate the errors, it will be easier to identify the least sum of squares of error." }, { "code": null, "e": 6305, "s": 6110, "text": "Out of all possible lines, the linear regression model comes up with the best fit line with the least sum of squares of error. Slope and Intercept of the best fit line are the model coefficient." }, { "code": null, "e": 6359, "s": 6305, "text": "Now we have to measure how good is our best fit line?" }, { "code": null, "e": 6434, "s": 6359, "text": "R-squared is one of the measures of goodness of the model. (best-fit line)" }, { "code": null, "e": 6489, "s": 6434, "text": "SSE →Sum of squares of ErrorsSST →Sum of Squares Total" }, { "code": null, "e": 6514, "s": 6489, "text": "What is the Total Error?" }, { "code": null, "e": 6809, "s": 6514, "text": "Before building a linear regression model, we can say that the expected value of y is the mean/average value of y. The difference between the mean of y and the actual value of y is the Total Error. Total Error is the Total variance. Total Variance is the amount of variance present in the data." }, { "code": null, "e": 7085, "s": 6809, "text": "After building a linear regression model, our model predicts the y value. The difference between the mean of y and the predicted y value is the Regression Error.Regression Error is the Explained Variance. Explained Variance means the amount of variance captured by the model." }, { "code": null, "e": 7215, "s": 7085, "text": "Residual/Error is the difference between the actual y value and the predicted y value.Residual/Error is the Unexplained Variance." }, { "code": null, "e": 7263, "s": 7215, "text": "Total Error = Residual Error + Regression Error" }, { "code": null, "e": 7364, "s": 7263, "text": "Coefficient of determination or R-squared measures how much variance in y is explained by the model." }, { "code": null, "e": 7407, "s": 7364, "text": "The R-squared value ranges between 0 and 1" }, { "code": null, "e": 7447, "s": 7407, "text": "0 → being a bad model and 1 being good." }, { "code": null, "e": 7495, "s": 7447, "text": "Correlation Coefficient- r ranges from -1 to +1" }, { "code": null, "e": 7551, "s": 7495, "text": "The coefficient of Determination- R2 ranges from 0 to 1" }, { "code": null, "e": 7615, "s": 7551, "text": "Slope and intercept are model coefficients or model parameters." }, { "code": null, "e": 7678, "s": 7615, "text": "Thank you for reading my article, I hope you found it helpful!" }, { "code": null, "e": 7701, "s": 7678, "text": "towardsdatascience.com" }, { "code": null, "e": 7845, "s": 7701, "text": "Watch this space for more articles on Python and DataScience. If you like to read more of my tutorials, follow me on Medium, LinkedIn, Twitter." } ]
Time Series Modeling of Bitcoin Prices | by Paul Tune | Towards Data Science
While the world was (and still is) in the grip of a pandemic in 2020, Bitcoin has had a stellar run. From its spectacular crash in 2018 and a relatively uneventful year in 2019, it started 2020 with a price of USD$8,000 to an all new record high of USD$50,000 as of the writing of this article. That’s roughly more than a 600% return! It is one of the most successful investments of 2020. Yet Bitcoin is, to say the least, controversial. For one, academics cannot decide if it is a currency that can be used for transactions, a store of value like gold or a mere collectible. Some have used it as an example to fundamentally question the nature of money itself. Bitcoin’s supporters believe it and other cryptocurrencies are the future of money for good reason. We have seen the ease of the printing of currencies through stimulus programs demonstrated by world governments after the COVID-19 outbreak last year. With this in mind, Bitcoin supporters see the built-in scarcity of Bitcoin through the increasing difficulty in mining for new Bitcoins as a way to overcome its devaluation. Bitcoin’s deflationary nature makes it attractive as a store of value. It can be used for transactions in a completely decentralized manner, making it attractive for circumventing the middle man, often considered to be the banks. Companies are split about its potential. Square was one of the first major companies to buy $50 million USD worth of Bitcoins for transaction purposes, followed by Paypal. Tesla has recently announced that the company would be heavily invested in Bitcoin, buying about USD$1.5 billion worth of Bitcoin. Well-known investors have differing opinions if Bitcoin is an investment, or not. Warren Buffett said Cryptocurrencies basically have no value and they don’t produce anything. They don’t reproduce, they can’t mail you a check, they can’t do anything, and what you hope is that somebody else comes along and pays you more money for them later on, but then that person’s got the problem. In terms of value: zero. Some in the public dismiss Bitcoin as a currency for pirates and criminals. Some are increasingly worried about its energy consumption, which is higher than all of Argentina’s electricity consumption. Many still do not understand what it is and how its underlying technology, the blockchain works. And some have bought cryptocurrency just through the sheer fear of missing out! Whatever your stand is on the matter, Bitcoin has certainly produced no shortage of opinions. What does matter now is that we can improve our data science skills by learning some time series modeling. In this article, we learn about price forecasting and time series modelling using Facebook’s highly useful forecasting tool: Prophet. We will also learn how to factor in multiple data sources to improve our price estimates. All code shown in this article can be found here. Before we begin, a disclaimer. This article is by no means a way to accurately determine the price of Bitcoin, and is purely for educational purposes. Please understand the financial risks before buying Bitcoin or any other financial asset. Bitcoin has naturally attracted the attention of the public due to the potential of massive gains. It is then not surprising that there have been efforts to develop price forecasting models for Bitcoin and various cryptocurrencies. We’ll provide an overview of two models here. One model relies on Metcalfe’s law, simply stated as The value of a network is proportional to the square of the number of users in the network The proposed model by Timothy Peterson and the follow-up paper applied Metcalfe’s law to Bitcoin. Since the value of Bitcoin is driven by the number of users, we would have to model the growth of users of Bitcoin. The model uses a Gompertz function to model the growth instead of a logistic function. For reference, the growth of the number of users at time t is given by This function is fitted on the number of active Bitcoin addresses, as shown in the figure below. The forecast then serves as the foundation for the valuation of Bitcoin. The stock-to-flow model for Bitcoin (S2F) by the pseudonymous PlanB. It is considered a controversial model for its assumption: that Bitcoin is scarce, and therefore, the value is determined by how many coins there are in circulation (stock) and how many coins have been produced (flow). A follow-up article by PlanB proposed a new stock-to-flow model with cross asset pricing. The model is still fundamentally similar to the initial S2F model. However, this model formulates Bitcoin as going through distinct phases like water. The four distinct phases are the proof-of-concept phase the payments phase the E-gold phase the financial asset phase These clusters were found using a genetic search algorithm, with the price predictions coming from the aforementioned S2F model. There have been arguments against the S2F model (see here). The model has been accused of being a “chameleon”, a model that has no basis in reality, but sounds plausible. Regardless, the model’s price predictions has been on point throughout the whole of 2020 to the present As we have seen, like any new technology, Bitcoin and cryptocurrencies in general are hard to value because no one can know exactly what’s in store for the future. We expect a lot of uncertainty around pricing, and the large variance around pricing forecasts around Bitcoin reflects this uncertainty. Prophet is a tool developed by Sean J. Taylor and Benjamin Letham at Facebook for large scale time series forecasting. It was developed to account for time series data encountered in businesses. The underlying model accounts for a long term trend, seasonality (daily, monthly and yearly), and holidays. As we shall see, this allows us to visualize the decomposition of the modelled time series once a fit is performed. For simplicity, we use Bitcoin prices at the open of the market. We set our starting date to be the 1st of January 2016. The end date of the training dataset is set to the 31st of December 2020. The test set is set from the 1st of January 2021 to the 12th of February 2021. Our goal is to test how well Prophet fits on Bitcoin’s prices with and without additional side information. Our initial model only uses Bitcoin’s past price action to determine its future price. We will be using the Prophet’s Python API. Prophet is easy to use but it requires that your Pandas DataFrame is formatted with a Date and y column. In this case the y column is Bitcoin’s price in USD. We denote our model by init_model . I explicitly set the daily seasonality to False because our data is in days and we don’t have a finer timescale to model fluctuations in a day. Another important setting is to have seasonality_mode="multiplicative" . The reason for this is that Bitcoin’s seasonality fluctuations are increasing year-on-year, which fits a multiplicative model rather than an additive one. init_model = Prophet( daily_seasonality=False, seasonality_mode="multiplicative",)init_model.fit(input_df) No optimization of Prophet’s parameters were attempted. This forecast is the not the same as the forecast made here, since the forecast made there used an additive seasonality mode. I have also placed a hard constraint that price is at least $0. Another option to explore is to fit on the logarithm of Bitcoin’s price instead, which would ensure the constraint on the price is met. Constraints on the forecasts are still work in progress in Prophet, so we will have to make do for now. The fit is quite good on the training set. The R2 score for this model on the training set is 0.96. The root mean squared error (RMSE) is 946. However, the model unfortunately was not able to predict the recent run up in prices, but the trend is still going up. Prophet provides a prediction yhat with lower and upper predictions (given by yhat_lower and yhat_upper respectively) . The predictions vastly underpredicts prices at the end of January compared to the current price of Bitcoin (which exceeded USD$50,000 as of writing). We can do better. The Bitcoin network itself possesses a wealth of information. These include the number of unique addresses, transaction volumes, total Bitcoins currently in circulation, and the gradual difficulty in mining through the hash rate. These information is up-to-date and publicly available from Quandl. Moreover, macroeconomic factors do play a part in determining price. The overall market capitalization can be captured through the Standard and Poor’s (S&P) 500’s index. The US Treasury Bill rates captures the current interest rates, thereby providing an indicator of an appetite by investors for riskier assets. We can get these information from Yahoo! Finance. Finally, given the buzz about Bitcoin, we can add search trend information from Google Trends. We can see the correlation between the unique addresses with Bitcoin price over rolling 30-day windows. We can see that it is generally positive, so that would provide additional information to our price prediction. We can add regressors easily by calling the add_regressor method, as shown here: extended_model = Prophet( daily_seasonality=False, seasonality_mode="multiplicative",) for col in input_df.columns: if col not in ["ds", "y"]: extended_model.add_regressor(col, mode="additive") extended_model.fit(input_df) I have chosen the regressors to be additive. I have tested with multiplicative regressors, but the fit is far worse. The fit is marginally better than the previous model, with an R2 score of 0.97 with an RMSE of 822. The price prediction given by this model still vastly under predicts the actual price. The departure from the from actual price could mean that we lack additional information, which the model cannot account for. For instance, we have not added sentiment data from social media, or news outlets. A good example would be a jump in Bitcoin price when Elon Musk announced that Tesla has bought $1.5 billion dollars in Bitcoin, as Tesla will now accept payments in Bitcoin. It is important to note that a regressor is only useful if a good forecast of the regressor can be obtained. For example, we can assume the number of unique addresses to grow like predictions from a Gompertz curve, like in Peterson’s Metcalfe law-based model. So in practice, it would be important to find regressors that are stable and fairly easy to predict. Recall that Prophet’s model assumes that there is a long term trend, seasonality, and holidays effects. We now visualize these components. We can look at the decomposition of the forecast by a simple method call fig = extended_model.plot_components(forecast) which produces We can see that the price is only trending up in the long term according to the model. Interestingly, prices are lower on the weekends than on weekdays. Moreover, prices also rise higher towards the end of the year to the start of the following year than other periods. We can also see the seasonality in the extra regressors we have added. We can also apply Prophet to Ethereum, a blockchain network with smart contract functionality. Here, I use the number of active addresses in the network and Google’s search trend sentiment. More details can be found in the supplied code. The famous physicist, Niels Bohr, is purported to have said It is difficult to make predictions, especially about the future Forecasting Bitcoin prices is no different. Who would have thought that Bitcoin would have its roots in an obscure whitepaper written by a anonymous author, to almost a trillion USD worth in market capitalization today? As with all things though, there are a few lessons we can gather from this exercise. The first is that every forecasting model has a set of assumptions. These assumptions can be implicit or explicit, but they are there. Peterson’s model assumes that Bitcoin is a network that follows Metcalfe’s law. PlanB’s model assumes that scarcity will ultimately be the deciding factor of Bitcoin’s value. In Prophet, the underlying model has an explicit structure: it has trend, seasonal and spurious (holiday) components. Deep learning models have other assumptions but they can be implicit due to their non-parameteric nature. The strength of models with explicit structure is that it is easier to perform sensitivity analysis to test the robustness of the model under various scenarios. This is especially important in financial models, as this can spell disaster if an overoptimistic forecast is made. The second is that forecasting by itself is only half the task. Often forecasting goes hand-in-hand with a decision. In this case, it would be a decision to buy, hold or sell Bitcoin. It would be wise to have models that produce a range and uncertainty bounds. In this way, when uncertainty is very high, allocation is lower with more diversification, so as to reduce the overall risk of a portfolio. Some methods such as reinforcement learning learns both the forecast and decision together, but that is a topic for another day. Prophet is a very useful tool for time series forecasting, but like with every other model, the wielder of the tool has to check if her data matches the assumptions of the model. I hope that this article shows how additional information can be added to Prophet to make it more powerful. The thoughts and views expressed in this article are mine alone and do not reflect the view of Towards Data Science. This article is intended to be educational in nature and should not be construed as individual investment advice nor as a recommendation to buy, sell, or hold any security or to adopt any investment strategy. Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.
[ { "code": null, "e": 436, "s": 47, "text": "While the world was (and still is) in the grip of a pandemic in 2020, Bitcoin has had a stellar run. From its spectacular crash in 2018 and a relatively uneventful year in 2019, it started 2020 with a price of USD$8,000 to an all new record high of USD$50,000 as of the writing of this article. That’s roughly more than a 600% return! It is one of the most successful investments of 2020." }, { "code": null, "e": 485, "s": 436, "text": "Yet Bitcoin is, to say the least, controversial." }, { "code": null, "e": 709, "s": 485, "text": "For one, academics cannot decide if it is a currency that can be used for transactions, a store of value like gold or a mere collectible. Some have used it as an example to fundamentally question the nature of money itself." }, { "code": null, "e": 1364, "s": 709, "text": "Bitcoin’s supporters believe it and other cryptocurrencies are the future of money for good reason. We have seen the ease of the printing of currencies through stimulus programs demonstrated by world governments after the COVID-19 outbreak last year. With this in mind, Bitcoin supporters see the built-in scarcity of Bitcoin through the increasing difficulty in mining for new Bitcoins as a way to overcome its devaluation. Bitcoin’s deflationary nature makes it attractive as a store of value. It can be used for transactions in a completely decentralized manner, making it attractive for circumventing the middle man, often considered to be the banks." }, { "code": null, "e": 1667, "s": 1364, "text": "Companies are split about its potential. Square was one of the first major companies to buy $50 million USD worth of Bitcoins for transaction purposes, followed by Paypal. Tesla has recently announced that the company would be heavily invested in Bitcoin, buying about USD$1.5 billion worth of Bitcoin." }, { "code": null, "e": 1769, "s": 1667, "text": "Well-known investors have differing opinions if Bitcoin is an investment, or not. Warren Buffett said" }, { "code": null, "e": 2078, "s": 1769, "text": "Cryptocurrencies basically have no value and they don’t produce anything. They don’t reproduce, they can’t mail you a check, they can’t do anything, and what you hope is that somebody else comes along and pays you more money for them later on, but then that person’s got the problem. In terms of value: zero." }, { "code": null, "e": 2456, "s": 2078, "text": "Some in the public dismiss Bitcoin as a currency for pirates and criminals. Some are increasingly worried about its energy consumption, which is higher than all of Argentina’s electricity consumption. Many still do not understand what it is and how its underlying technology, the blockchain works. And some have bought cryptocurrency just through the sheer fear of missing out!" }, { "code": null, "e": 2657, "s": 2456, "text": "Whatever your stand is on the matter, Bitcoin has certainly produced no shortage of opinions. What does matter now is that we can improve our data science skills by learning some time series modeling." }, { "code": null, "e": 2931, "s": 2657, "text": "In this article, we learn about price forecasting and time series modelling using Facebook’s highly useful forecasting tool: Prophet. We will also learn how to factor in multiple data sources to improve our price estimates. All code shown in this article can be found here." }, { "code": null, "e": 3172, "s": 2931, "text": "Before we begin, a disclaimer. This article is by no means a way to accurately determine the price of Bitcoin, and is purely for educational purposes. Please understand the financial risks before buying Bitcoin or any other financial asset." }, { "code": null, "e": 3450, "s": 3172, "text": "Bitcoin has naturally attracted the attention of the public due to the potential of massive gains. It is then not surprising that there have been efforts to develop price forecasting models for Bitcoin and various cryptocurrencies. We’ll provide an overview of two models here." }, { "code": null, "e": 3503, "s": 3450, "text": "One model relies on Metcalfe’s law, simply stated as" }, { "code": null, "e": 3594, "s": 3503, "text": "The value of a network is proportional to the square of the number of users in the network" }, { "code": null, "e": 3966, "s": 3594, "text": "The proposed model by Timothy Peterson and the follow-up paper applied Metcalfe’s law to Bitcoin. Since the value of Bitcoin is driven by the number of users, we would have to model the growth of users of Bitcoin. The model uses a Gompertz function to model the growth instead of a logistic function. For reference, the growth of the number of users at time t is given by" }, { "code": null, "e": 4136, "s": 3966, "text": "This function is fitted on the number of active Bitcoin addresses, as shown in the figure below. The forecast then serves as the foundation for the valuation of Bitcoin." }, { "code": null, "e": 4424, "s": 4136, "text": "The stock-to-flow model for Bitcoin (S2F) by the pseudonymous PlanB. It is considered a controversial model for its assumption: that Bitcoin is scarce, and therefore, the value is determined by how many coins there are in circulation (stock) and how many coins have been produced (flow)." }, { "code": null, "e": 4694, "s": 4424, "text": "A follow-up article by PlanB proposed a new stock-to-flow model with cross asset pricing. The model is still fundamentally similar to the initial S2F model. However, this model formulates Bitcoin as going through distinct phases like water. The four distinct phases are" }, { "code": null, "e": 4721, "s": 4694, "text": "the proof-of-concept phase" }, { "code": null, "e": 4740, "s": 4721, "text": "the payments phase" }, { "code": null, "e": 4757, "s": 4740, "text": "the E-gold phase" }, { "code": null, "e": 4783, "s": 4757, "text": "the financial asset phase" }, { "code": null, "e": 4912, "s": 4783, "text": "These clusters were found using a genetic search algorithm, with the price predictions coming from the aforementioned S2F model." }, { "code": null, "e": 5187, "s": 4912, "text": "There have been arguments against the S2F model (see here). The model has been accused of being a “chameleon”, a model that has no basis in reality, but sounds plausible. Regardless, the model’s price predictions has been on point throughout the whole of 2020 to the present" }, { "code": null, "e": 5488, "s": 5187, "text": "As we have seen, like any new technology, Bitcoin and cryptocurrencies in general are hard to value because no one can know exactly what’s in store for the future. We expect a lot of uncertainty around pricing, and the large variance around pricing forecasts around Bitcoin reflects this uncertainty." }, { "code": null, "e": 5907, "s": 5488, "text": "Prophet is a tool developed by Sean J. Taylor and Benjamin Letham at Facebook for large scale time series forecasting. It was developed to account for time series data encountered in businesses. The underlying model accounts for a long term trend, seasonality (daily, monthly and yearly), and holidays. As we shall see, this allows us to visualize the decomposition of the modelled time series once a fit is performed." }, { "code": null, "e": 6181, "s": 5907, "text": "For simplicity, we use Bitcoin prices at the open of the market. We set our starting date to be the 1st of January 2016. The end date of the training dataset is set to the 31st of December 2020. The test set is set from the 1st of January 2021 to the 12th of February 2021." }, { "code": null, "e": 6289, "s": 6181, "text": "Our goal is to test how well Prophet fits on Bitcoin’s prices with and without additional side information." }, { "code": null, "e": 6577, "s": 6289, "text": "Our initial model only uses Bitcoin’s past price action to determine its future price. We will be using the Prophet’s Python API. Prophet is easy to use but it requires that your Pandas DataFrame is formatted with a Date and y column. In this case the y column is Bitcoin’s price in USD." }, { "code": null, "e": 6757, "s": 6577, "text": "We denote our model by init_model . I explicitly set the daily seasonality to False because our data is in days and we don’t have a finer timescale to model fluctuations in a day." }, { "code": null, "e": 6985, "s": 6757, "text": "Another important setting is to have seasonality_mode=\"multiplicative\" . The reason for this is that Bitcoin’s seasonality fluctuations are increasing year-on-year, which fits a multiplicative model rather than an additive one." }, { "code": null, "e": 7099, "s": 6985, "text": "init_model = Prophet( daily_seasonality=False, seasonality_mode=\"multiplicative\",)init_model.fit(input_df)" }, { "code": null, "e": 7481, "s": 7099, "text": "No optimization of Prophet’s parameters were attempted. This forecast is the not the same as the forecast made here, since the forecast made there used an additive seasonality mode. I have also placed a hard constraint that price is at least $0. Another option to explore is to fit on the logarithm of Bitcoin’s price instead, which would ensure the constraint on the price is met." }, { "code": null, "e": 7585, "s": 7481, "text": "Constraints on the forecasts are still work in progress in Prophet, so we will have to make do for now." }, { "code": null, "e": 7847, "s": 7585, "text": "The fit is quite good on the training set. The R2 score for this model on the training set is 0.96. The root mean squared error (RMSE) is 946. However, the model unfortunately was not able to predict the recent run up in prices, but the trend is still going up." }, { "code": null, "e": 8117, "s": 7847, "text": "Prophet provides a prediction yhat with lower and upper predictions (given by yhat_lower and yhat_upper respectively) . The predictions vastly underpredicts prices at the end of January compared to the current price of Bitcoin (which exceeded USD$50,000 as of writing)." }, { "code": null, "e": 8135, "s": 8117, "text": "We can do better." }, { "code": null, "e": 8433, "s": 8135, "text": "The Bitcoin network itself possesses a wealth of information. These include the number of unique addresses, transaction volumes, total Bitcoins currently in circulation, and the gradual difficulty in mining through the hash rate. These information is up-to-date and publicly available from Quandl." }, { "code": null, "e": 8796, "s": 8433, "text": "Moreover, macroeconomic factors do play a part in determining price. The overall market capitalization can be captured through the Standard and Poor’s (S&P) 500’s index. The US Treasury Bill rates captures the current interest rates, thereby providing an indicator of an appetite by investors for riskier assets. We can get these information from Yahoo! Finance." }, { "code": null, "e": 8891, "s": 8796, "text": "Finally, given the buzz about Bitcoin, we can add search trend information from Google Trends." }, { "code": null, "e": 9107, "s": 8891, "text": "We can see the correlation between the unique addresses with Bitcoin price over rolling 30-day windows. We can see that it is generally positive, so that would provide additional information to our price prediction." }, { "code": null, "e": 9188, "s": 9107, "text": "We can add regressors easily by calling the add_regressor method, as shown here:" }, { "code": null, "e": 9436, "s": 9188, "text": "extended_model = Prophet( daily_seasonality=False, seasonality_mode=\"multiplicative\",) for col in input_df.columns: if col not in [\"ds\", \"y\"]: extended_model.add_regressor(col, mode=\"additive\") extended_model.fit(input_df)" }, { "code": null, "e": 9553, "s": 9436, "text": "I have chosen the regressors to be additive. I have tested with multiplicative regressors, but the fit is far worse." }, { "code": null, "e": 9653, "s": 9553, "text": "The fit is marginally better than the previous model, with an R2 score of 0.97 with an RMSE of 822." }, { "code": null, "e": 9740, "s": 9653, "text": "The price prediction given by this model still vastly under predicts the actual price." }, { "code": null, "e": 10122, "s": 9740, "text": "The departure from the from actual price could mean that we lack additional information, which the model cannot account for. For instance, we have not added sentiment data from social media, or news outlets. A good example would be a jump in Bitcoin price when Elon Musk announced that Tesla has bought $1.5 billion dollars in Bitcoin, as Tesla will now accept payments in Bitcoin." }, { "code": null, "e": 10483, "s": 10122, "text": "It is important to note that a regressor is only useful if a good forecast of the regressor can be obtained. For example, we can assume the number of unique addresses to grow like predictions from a Gompertz curve, like in Peterson’s Metcalfe law-based model. So in practice, it would be important to find regressors that are stable and fairly easy to predict." }, { "code": null, "e": 10622, "s": 10483, "text": "Recall that Prophet’s model assumes that there is a long term trend, seasonality, and holidays effects. We now visualize these components." }, { "code": null, "e": 10695, "s": 10622, "text": "We can look at the decomposition of the forecast by a simple method call" }, { "code": null, "e": 10742, "s": 10695, "text": "fig = extended_model.plot_components(forecast)" }, { "code": null, "e": 10757, "s": 10742, "text": "which produces" }, { "code": null, "e": 11098, "s": 10757, "text": "We can see that the price is only trending up in the long term according to the model. Interestingly, prices are lower on the weekends than on weekdays. Moreover, prices also rise higher towards the end of the year to the start of the following year than other periods. We can also see the seasonality in the extra regressors we have added." }, { "code": null, "e": 11288, "s": 11098, "text": "We can also apply Prophet to Ethereum, a blockchain network with smart contract functionality. Here, I use the number of active addresses in the network and Google’s search trend sentiment." }, { "code": null, "e": 11336, "s": 11288, "text": "More details can be found in the supplied code." }, { "code": null, "e": 11396, "s": 11336, "text": "The famous physicist, Niels Bohr, is purported to have said" }, { "code": null, "e": 11461, "s": 11396, "text": "It is difficult to make predictions, especially about the future" }, { "code": null, "e": 11766, "s": 11461, "text": "Forecasting Bitcoin prices is no different. Who would have thought that Bitcoin would have its roots in an obscure whitepaper written by a anonymous author, to almost a trillion USD worth in market capitalization today? As with all things though, there are a few lessons we can gather from this exercise." }, { "code": null, "e": 11901, "s": 11766, "text": "The first is that every forecasting model has a set of assumptions. These assumptions can be implicit or explicit, but they are there." }, { "code": null, "e": 12300, "s": 11901, "text": "Peterson’s model assumes that Bitcoin is a network that follows Metcalfe’s law. PlanB’s model assumes that scarcity will ultimately be the deciding factor of Bitcoin’s value. In Prophet, the underlying model has an explicit structure: it has trend, seasonal and spurious (holiday) components. Deep learning models have other assumptions but they can be implicit due to their non-parameteric nature." }, { "code": null, "e": 12577, "s": 12300, "text": "The strength of models with explicit structure is that it is easier to perform sensitivity analysis to test the robustness of the model under various scenarios. This is especially important in financial models, as this can spell disaster if an overoptimistic forecast is made." }, { "code": null, "e": 13107, "s": 12577, "text": "The second is that forecasting by itself is only half the task. Often forecasting goes hand-in-hand with a decision. In this case, it would be a decision to buy, hold or sell Bitcoin. It would be wise to have models that produce a range and uncertainty bounds. In this way, when uncertainty is very high, allocation is lower with more diversification, so as to reduce the overall risk of a portfolio. Some methods such as reinforcement learning learns both the forecast and decision together, but that is a topic for another day." }, { "code": null, "e": 13394, "s": 13107, "text": "Prophet is a very useful tool for time series forecasting, but like with every other model, the wielder of the tool has to check if her data matches the assumptions of the model. I hope that this article shows how additional information can be added to Prophet to make it more powerful." }, { "code": null, "e": 13720, "s": 13394, "text": "The thoughts and views expressed in this article are mine alone and do not reflect the view of Towards Data Science. This article is intended to be educational in nature and should not be construed as individual investment advice nor as a recommendation to buy, sell, or hold any security or to adopt any investment strategy." } ]
degrees() and radians() in Python - GeeksforGeeks
09 Apr, 2018 degress() and radians() are methods specified in math module in Python 3 and Python 2. Often one is in need to handle mathematical computation of conversion of radians to degrees and vice-versa, especially in the field of geometry. Python offers inbuilt methods to handle this functionality. Both the functions are discussed in this article. This function accepts the “degrees” as input and converts it into its radians equivalent. Syntax : radians(deg) Parameters :deg : The degrees value that one needs to convert into radians Returns : This function returns the floating point radians equivalent of argument.Computational Equivalent : 1 Radians = 180/pi Degrees. Code #1 : Demonstrating radians() # Python code to demonstrate# working of radians() # for radiansimport math # Printing radians equivalents.print("180 / pi Degrees is equal to Radians : ", end ="")print (math.radians(180 / math.pi)) print("180 Degrees is equal to Radians : ", end ="")print (math.radians(180)) print("1 Degrees is equal to Radians : ", end ="")print (math.radians(1)) Output: 180/pi Degrees is equal to Radians : 1.0 180 Degrees is equal to Radians : 3.141592653589793 1 Degrees is equal to Radians : 0.017453292519943295 This function accepts the “radians” as input and converts it into its degrees equivalent. Syntax : degrees(rad) Parameters :rad : The radians value that one needs to convert into degrees. Returns : This function returns the floating point degrees equivalent of argument.Computational Equivalent : 1 Degrees = pi/180 Radians. Code #2 : Demonstrating degrees() # Python code to demonstrate# working of degrees() # for degrees()import math # Printing degrees equivalents.print("pi / 180 Radians is equal to Degrees : ", end ="")print (math.degrees(math.pi / 180)) print("180 Radians is equal to Degrees : ", end ="")print (math.degrees(180)) print("1 Radians is equal to Degrees : ", end ="")print (math.degrees(1)) Output: pi/180 Radians is equal to Degrees : 1.0 180 Radians is equal to Degrees : 10313.240312354817 1 Radians is equal to Degrees : 57.29577951308232 Application :There are many possible applications of these functions in mathematical computations related to geometry and has a certain applications in astronomical computations as well. Python-Built-in-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 23815, "s": 23787, "text": "\n09 Apr, 2018" }, { "code": null, "e": 23902, "s": 23815, "text": "degress() and radians() are methods specified in math module in Python 3 and Python 2." }, { "code": null, "e": 24157, "s": 23902, "text": "Often one is in need to handle mathematical computation of conversion of radians to degrees and vice-versa, especially in the field of geometry. Python offers inbuilt methods to handle this functionality. Both the functions are discussed in this article." }, { "code": null, "e": 24247, "s": 24157, "text": "This function accepts the “degrees” as input and converts it into its radians equivalent." }, { "code": null, "e": 24269, "s": 24247, "text": "Syntax : radians(deg)" }, { "code": null, "e": 24344, "s": 24269, "text": "Parameters :deg : The degrees value that one needs to convert into radians" }, { "code": null, "e": 24481, "s": 24344, "text": "Returns : This function returns the floating point radians equivalent of argument.Computational Equivalent : 1 Radians = 180/pi Degrees." }, { "code": null, "e": 24516, "s": 24481, "text": " Code #1 : Demonstrating radians()" }, { "code": "# Python code to demonstrate# working of radians() # for radiansimport math # Printing radians equivalents.print(\"180 / pi Degrees is equal to Radians : \", end =\"\")print (math.radians(180 / math.pi)) print(\"180 Degrees is equal to Radians : \", end =\"\")print (math.radians(180)) print(\"1 Degrees is equal to Radians : \", end =\"\")print (math.radians(1))", "e": 24872, "s": 24516, "text": null }, { "code": null, "e": 24880, "s": 24872, "text": "Output:" }, { "code": null, "e": 25027, "s": 24880, "text": "180/pi Degrees is equal to Radians : 1.0\n180 Degrees is equal to Radians : 3.141592653589793\n1 Degrees is equal to Radians : 0.017453292519943295\n" }, { "code": null, "e": 25117, "s": 25027, "text": "This function accepts the “radians” as input and converts it into its degrees equivalent." }, { "code": null, "e": 25139, "s": 25117, "text": "Syntax : degrees(rad)" }, { "code": null, "e": 25215, "s": 25139, "text": "Parameters :rad : The radians value that one needs to convert into degrees." }, { "code": null, "e": 25352, "s": 25215, "text": "Returns : This function returns the floating point degrees equivalent of argument.Computational Equivalent : 1 Degrees = pi/180 Radians." }, { "code": null, "e": 25387, "s": 25352, "text": " Code #2 : Demonstrating degrees()" }, { "code": "# Python code to demonstrate# working of degrees() # for degrees()import math # Printing degrees equivalents.print(\"pi / 180 Radians is equal to Degrees : \", end =\"\")print (math.degrees(math.pi / 180)) print(\"180 Radians is equal to Degrees : \", end =\"\")print (math.degrees(180)) print(\"1 Radians is equal to Degrees : \", end =\"\")print (math.degrees(1))", "e": 25745, "s": 25387, "text": null }, { "code": null, "e": 25753, "s": 25745, "text": "Output:" }, { "code": null, "e": 25898, "s": 25753, "text": "pi/180 Radians is equal to Degrees : 1.0\n180 Radians is equal to Degrees : 10313.240312354817\n1 Radians is equal to Degrees : 57.29577951308232\n" }, { "code": null, "e": 26085, "s": 25898, "text": "Application :There are many possible applications of these functions in mathematical computations related to geometry and has a certain applications in astronomical computations as well." }, { "code": null, "e": 26111, "s": 26085, "text": "Python-Built-in-functions" }, { "code": null, "e": 26118, "s": 26111, "text": "Python" }, { "code": null, "e": 26216, "s": 26118, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26225, "s": 26216, "text": "Comments" }, { "code": null, "e": 26238, "s": 26225, "text": "Old Comments" }, { "code": null, "e": 26256, "s": 26238, "text": "Python Dictionary" }, { "code": null, "e": 26291, "s": 26256, "text": "Read a file line by line in Python" }, { "code": null, "e": 26313, "s": 26291, "text": "Enumerate() in Python" }, { "code": null, "e": 26345, "s": 26313, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26375, "s": 26345, "text": "Iterate over a list in Python" }, { "code": null, "e": 26417, "s": 26375, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26443, "s": 26417, "text": "Python String | replace()" }, { "code": null, "e": 26486, "s": 26443, "text": "Python program to convert a list to string" }, { "code": null, "e": 26530, "s": 26486, "text": "Reading and Writing to text files in Python" } ]
Move all zeros to start and ones to end in an Array of random integers in C++
In this tutorial, we are going to write a program that moves all zeroes to front and ones to end of the array. Given an array with zeroes and ones along with random integers. We have to move all the zeroes to start and ones to the end of the array. Let's see an example. Input arr = [4, 5, 1, 1, 0, 0, 2, 0, 3, 1, 0, 1] Output 0 0 0 0 4 5 2 3 1 1 1 1 Initialise the array. Initialise the array. Initialise an index to 1. Initialise an index to 1. Iterate over the given array.If the current element is not zero, then update the value at the index with the current element.Increment the index. Iterate over the given array. If the current element is not zero, then update the value at the index with the current element. If the current element is not zero, then update the value at the index with the current element. Increment the index. Increment the index. Write a loop that iterates from the above index to nUpdate all the elements to 1. Write a loop that iterates from the above index to n Update all the elements to 1. Update all the elements to 1. Similarly, do for 0. Instead of increasing the index, decrease it to move all zeroes to front of the array. Similarly, do for 0. Instead of increasing the index, decrease it to move all zeroes to front of the array. Following is the implementation of the above algorithm in C++ #include <bits/stdc++.h> using namespace std; void update1And0Positions(int arr[], int n) { int index = 0; for (int i = 0; i < n; i++) { if (arr[i] != 1) { arr[index++] = arr[i]; } } while (index < n) { arr[index++] = 1; } index = 0; for (int i = n - 1; i >= 0; i--) { if (arr[i] == 1) { continue; } if (!index) { index = i; } if (arr[i] != 0) { arr[index--] = arr[i]; } } while (index >= 0) { arr[index--] = 0; } } int main() { int arr[] = { 4, 5, 1, 1, 0, 0, 2, 0, 3, 1, 0, 1 }; int n = 12; update1And0Positions(arr, n); for (int i = 0; i < n; i++) { cout << arr[i] << " "; } cout << endl; return 0; } If you run the above code, then you will get the following result. 0 0 0 0 4 5 2 3 1 1 1 1
[ { "code": null, "e": 1173, "s": 1062, "text": "In this tutorial, we are going to write a program that moves all zeroes to front and ones to end of the array." }, { "code": null, "e": 1333, "s": 1173, "text": "Given an array with zeroes and ones along with random integers. We have to move all the zeroes to start and ones to the end of the array. Let's see an example." }, { "code": null, "e": 1339, "s": 1333, "text": "Input" }, { "code": null, "e": 1382, "s": 1339, "text": "arr = [4, 5, 1, 1, 0, 0, 2, 0, 3, 1, 0, 1]" }, { "code": null, "e": 1389, "s": 1382, "text": "Output" }, { "code": null, "e": 1413, "s": 1389, "text": "0 0 0 0 4 5 2 3 1 1 1 1" }, { "code": null, "e": 1435, "s": 1413, "text": "Initialise the array." }, { "code": null, "e": 1457, "s": 1435, "text": "Initialise the array." }, { "code": null, "e": 1483, "s": 1457, "text": "Initialise an index to 1." }, { "code": null, "e": 1509, "s": 1483, "text": "Initialise an index to 1." }, { "code": null, "e": 1655, "s": 1509, "text": "Iterate over the given array.If the current element is not zero, then update the value at the index with the current element.Increment the index." }, { "code": null, "e": 1685, "s": 1655, "text": "Iterate over the given array." }, { "code": null, "e": 1782, "s": 1685, "text": "If the current element is not zero, then update the value at the index with the current element." }, { "code": null, "e": 1879, "s": 1782, "text": "If the current element is not zero, then update the value at the index with the current element." }, { "code": null, "e": 1900, "s": 1879, "text": "Increment the index." }, { "code": null, "e": 1921, "s": 1900, "text": "Increment the index." }, { "code": null, "e": 2003, "s": 1921, "text": "Write a loop that iterates from the above index to nUpdate all the elements to 1." }, { "code": null, "e": 2056, "s": 2003, "text": "Write a loop that iterates from the above index to n" }, { "code": null, "e": 2086, "s": 2056, "text": "Update all the elements to 1." }, { "code": null, "e": 2116, "s": 2086, "text": "Update all the elements to 1." }, { "code": null, "e": 2224, "s": 2116, "text": "Similarly, do for 0. Instead of increasing the index, decrease it to move all zeroes to front of the array." }, { "code": null, "e": 2332, "s": 2224, "text": "Similarly, do for 0. Instead of increasing the index, decrease it to move all zeroes to front of the array." }, { "code": null, "e": 2394, "s": 2332, "text": "Following is the implementation of the above algorithm in C++" }, { "code": null, "e": 3151, "s": 2394, "text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid update1And0Positions(int arr[], int n) {\n int index = 0;\n for (int i = 0; i < n; i++) {\n if (arr[i] != 1) {\n arr[index++] = arr[i];\n }\n }\n while (index < n) {\n arr[index++] = 1;\n }\n index = 0;\n for (int i = n - 1; i >= 0; i--) {\n if (arr[i] == 1) {\n continue;\n }\n if (!index) {\n index = i;\n }\n if (arr[i] != 0) {\n arr[index--] = arr[i];\n }\n }\n while (index >= 0) {\n arr[index--] = 0;\n }\n}\nint main() {\n int arr[] = { 4, 5, 1, 1, 0, 0, 2, 0, 3, 1, 0, 1 };\n int n = 12;\n update1And0Positions(arr, n);\n for (int i = 0; i < n; i++) {\n cout << arr[i] << \" \";\n }\n cout << endl;\n return 0;\n}" }, { "code": null, "e": 3218, "s": 3151, "text": "If you run the above code, then you will get the following result." }, { "code": null, "e": 3242, "s": 3218, "text": "0 0 0 0 4 5 2 3 1 1 1 1" } ]
How to get the fragment identifier from a URL ? - GeeksforGeeks
19 Dec, 2019 A fragment identifier is a string of characters that refers to a resource that is inferior to a primary resource. Approach 1: We are able to print the fragment identifier by defining a new variable as location.hash and then displaying it with the help of document.getElementbyId() method.Syntax:var x = location.hash; document.getElementById("demo").innerHTML = x;Example: In this example, we will use location.hash property.<!DOCTYPE html><html> <head> <title> How to get the fragment identifier from a URL? </title></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <button onclick="GFG()"> Try it </button> <p id="demo"></p> <script> function GFG() { location.hash = "#fragment_identifier"; var x = location.hash; document.getElementById( "demo").innerHTML = x; } </script></body> </html>Output:Before clicking the button:After clicking the button: Syntax: var x = location.hash; document.getElementById("demo").innerHTML = x; Example: In this example, we will use location.hash property. <!DOCTYPE html><html> <head> <title> How to get the fragment identifier from a URL? </title></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <button onclick="GFG()"> Try it </button> <p id="demo"></p> <script> function GFG() { location.hash = "#fragment_identifier"; var x = location.hash; document.getElementById( "demo").innerHTML = x; } </script></body> </html> Output: Before clicking the button: After clicking the button: Approach 2: We have defined a variable hash which stores whatever is after the # in the URL i.e. the fragment identifier and then we display it as an alert. It is done by storing the substring in the variable.Syntax:var hash = url.substring(url.indexOf('#') + 1); alert(hash);Example 2: This example uses substring() method to display the fragment identifier.<!DOCTYPE html><html> <head> <title> How to get the fragment identifier from a URL? </title></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id="demo"></p> <script> var url = "www.geeksforgeeks.com/article.php#hello"; var hash = url.substring(url.indexOf('#') + 1); alert(hash); </script></body> </html>Output: Syntax: var hash = url.substring(url.indexOf('#') + 1); alert(hash); Example 2: This example uses substring() method to display the fragment identifier. <!DOCTYPE html><html> <head> <title> How to get the fragment identifier from a URL? </title></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id="demo"></p> <script> var url = "www.geeksforgeeks.com/article.php#hello"; var hash = url.substring(url.indexOf('#') + 1); alert(hash); </script></body> </html> Output: JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Difference Between PUT and PATCH Request How to get character array from string in JavaScript? How to filter object array based on attributes? 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": 25300, "s": 25272, "text": "\n19 Dec, 2019" }, { "code": null, "e": 25414, "s": 25300, "text": "A fragment identifier is a string of characters that refers to a resource that is inferior to a primary resource." }, { "code": null, "e": 26364, "s": 25414, "text": "Approach 1: We are able to print the fragment identifier by defining a new variable as location.hash and then displaying it with the help of document.getElementbyId() method.Syntax:var x = location.hash;\ndocument.getElementById(\"demo\").innerHTML = x;Example: In this example, we will use location.hash property.<!DOCTYPE html><html> <head> <title> How to get the fragment identifier from a URL? </title></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <button onclick=\"GFG()\"> Try it </button> <p id=\"demo\"></p> <script> function GFG() { location.hash = \"#fragment_identifier\"; var x = location.hash; document.getElementById( \"demo\").innerHTML = x; } </script></body> </html>Output:Before clicking the button:After clicking the button:" }, { "code": null, "e": 26372, "s": 26364, "text": "Syntax:" }, { "code": null, "e": 26443, "s": 26372, "text": "var x = location.hash;\ndocument.getElementById(\"demo\").innerHTML = x;" }, { "code": null, "e": 26505, "s": 26443, "text": "Example: In this example, we will use location.hash property." }, { "code": "<!DOCTYPE html><html> <head> <title> How to get the fragment identifier from a URL? </title></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <button onclick=\"GFG()\"> Try it </button> <p id=\"demo\"></p> <script> function GFG() { location.hash = \"#fragment_identifier\"; var x = location.hash; document.getElementById( \"demo\").innerHTML = x; } </script></body> </html>", "e": 27083, "s": 26505, "text": null }, { "code": null, "e": 27091, "s": 27083, "text": "Output:" }, { "code": null, "e": 27119, "s": 27091, "text": "Before clicking the button:" }, { "code": null, "e": 27146, "s": 27119, "text": "After clicking the button:" }, { "code": null, "e": 27991, "s": 27146, "text": "Approach 2: We have defined a variable hash which stores whatever is after the # in the URL i.e. the fragment identifier and then we display it as an alert. It is done by storing the substring in the variable.Syntax:var hash = url.substring(url.indexOf('#') + 1);\nalert(hash);Example 2: This example uses substring() method to display the fragment identifier.<!DOCTYPE html><html> <head> <title> How to get the fragment identifier from a URL? </title></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id=\"demo\"></p> <script> var url = \"www.geeksforgeeks.com/article.php#hello\"; var hash = url.substring(url.indexOf('#') + 1); alert(hash); </script></body> </html>Output:" }, { "code": null, "e": 27999, "s": 27991, "text": "Syntax:" }, { "code": null, "e": 28060, "s": 27999, "text": "var hash = url.substring(url.indexOf('#') + 1);\nalert(hash);" }, { "code": null, "e": 28144, "s": 28060, "text": "Example 2: This example uses substring() method to display the fragment identifier." }, { "code": "<!DOCTYPE html><html> <head> <title> How to get the fragment identifier from a URL? </title></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id=\"demo\"></p> <script> var url = \"www.geeksforgeeks.com/article.php#hello\"; var hash = url.substring(url.indexOf('#') + 1); alert(hash); </script></body> </html>", "e": 28623, "s": 28144, "text": null }, { "code": null, "e": 28631, "s": 28623, "text": "Output:" }, { "code": null, "e": 28647, "s": 28631, "text": "JavaScript-Misc" }, { "code": null, "e": 28654, "s": 28647, "text": "Picked" }, { "code": null, "e": 28665, "s": 28654, "text": "JavaScript" }, { "code": null, "e": 28682, "s": 28665, "text": "Web Technologies" }, { "code": null, "e": 28709, "s": 28682, "text": "Web technologies Questions" }, { "code": null, "e": 28807, "s": 28709, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28868, "s": 28807, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28908, "s": 28868, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28949, "s": 28908, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29003, "s": 28949, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 29051, "s": 29003, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 29093, "s": 29051, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 29126, "s": 29093, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29188, "s": 29126, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29231, "s": 29188, "text": "How to fetch data from an API in ReactJS ?" } ]
How to use window.location to redirect to a different URL?
You might have encountered a situation where you clicked a URL to reach a page X but internally you were directed to another page Y. It happens due to page redirection. It is quite simple to do a page redirect using JavaScript on the client side. To redirect your site visitors to a new page, you just need to add a line in your head section as follows. You can try to run the following code to learn how to use window.location to redirect an HTML page. Here, we will redirect to the home page Live Demo <html> <head> <script> <!-- function Redirect() { window.location.assign("https://www.tutorialspoint.com"); } //--> </script> </head> <body> <p>Click the following button, you will be redirected to home page.</p> <input type="button" value="Redirect Me" onclick="Redirect();" /> </body> </html>
[ { "code": null, "e": 1231, "s": 1062, "text": "You might have encountered a situation where you clicked a URL to reach a page X but internally you were directed to another page Y. It happens due to page redirection." }, { "code": null, "e": 1416, "s": 1231, "text": "It is quite simple to do a page redirect using JavaScript on the client side. To redirect your site visitors to a new page, you just need to add a line in your head section as follows." }, { "code": null, "e": 1556, "s": 1416, "text": "You can try to run the following code to learn how to use window.location to redirect an HTML page. Here, we will redirect to the home page" }, { "code": null, "e": 1566, "s": 1556, "text": "Live Demo" }, { "code": null, "e": 1954, "s": 1566, "text": "<html>\n <head>\n <script>\n <!--\n function Redirect() {\n window.location.assign(\"https://www.tutorialspoint.com\");\n }\n //-->\n </script>\n </head>\n <body>\n <p>Click the following button, you will be redirected to home page.</p>\n <input type=\"button\" value=\"Redirect Me\" onclick=\"Redirect();\" />\n </body>\n</html>" } ]
What are the differences and similarities between tuples and lists in Python?
Both List and Tuple are called as sequence data types of Python. Objects of both types are comma separated collection of items not necessarily of same type. Concatenation, repetition, indexing and slicing can be done on objects of both types >>> #list operations >>> L1=[1,2,3] >>> L2=[4,5,6] >>> #concatenation >>> L3=L1+L2 >>> L3 [1, 2, 3, 4, 5, 6] >>> #repetition >>> L1*3 [1, 2, 3, 1, 2, 3, 1, 2, 3] >>> #indexing >>> L3[4] 5 >>> #slicing >>> L3[2:4] [3, 4] >>> #tuple operations >>> T1=(1,2,3) >>> T2=(4,5,6) >>> #concatenation >>> T3=T1+T2 >>> T3 (1, 2, 3, 4, 5, 6) >>> #repetition >>> T1*3 (1, 2, 3, 1, 2, 3, 1, 2, 3) >>> #indexing >>> T3[4] 5 >>> #slicing >>> T3[2:4] (3, 4) Following built-in functions are common to both types len() − return number of elements in sequence >>> L1=[45,32,16,72,24] >>> len(L1) 5 >>> T1=(45,32,16,72,24) >>> len(T3) max() − returns element with largest value. >>> max(L1) 72 >>> max(T1) 72 min() − returns element with smallest value. >>> max(T1) 72 >>> min(L1) 16 >>> min(T1) 16 List object is mutable. Hence, it is possible to append, update or delete an item from list. >>> L1=[45,32,16,72,24] >>> L1.append(56) >>> L1 [45, 32, 16, 72, 24, 56] >>> L1.insert(4,10) #insert 10 at 4th index >>> L1 [45, 32, 16, 72, 10, 24, 56] >>> L1.remove(16) >>> L1 [45, 32, 72, 10, 24, 56] >>> L1[2]=100 #update >>> L1 [45, 32, 100, 10, 24, 56] Tuple is immutable object. Any operation that try to modify it , results in AttributeError T1.append(56) AttributeError: 'tuple' object has no attribute 'append' >>> T1.remove(16) AttributeError: 'tuple' object has no attribute 'remove' >>> T1[2]=100 TypeError: 'tuple' object does not support item assignment
[ { "code": null, "e": 1219, "s": 1062, "text": "Both List and Tuple are called as sequence data types of Python. Objects of both types are comma separated collection of items not necessarily of same type." }, { "code": null, "e": 1304, "s": 1219, "text": "Concatenation, repetition, indexing and slicing can be done on objects of both types" }, { "code": null, "e": 1524, "s": 1304, "text": ">>> #list operations\n>>> L1=[1,2,3]\n>>> L2=[4,5,6]\n>>> #concatenation\n>>> L3=L1+L2\n>>> L3\n[1, 2, 3, 4, 5, 6]\n>>> #repetition\n>>> L1*3\n[1, 2, 3, 1, 2, 3, 1, 2, 3]\n>>> #indexing\n>>> L3[4]\n5\n>>> #slicing\n>>> L3[2:4]\n[3, 4]" }, { "code": null, "e": 1745, "s": 1524, "text": ">>> #tuple operations\n>>> T1=(1,2,3)\n>>> T2=(4,5,6)\n>>> #concatenation\n>>> T3=T1+T2\n>>> T3\n(1, 2, 3, 4, 5, 6)\n>>> #repetition\n>>> T1*3\n(1, 2, 3, 1, 2, 3, 1, 2, 3)\n>>> #indexing\n>>> T3[4]\n5\n>>> #slicing\n>>> T3[2:4]\n(3, 4)" }, { "code": null, "e": 1799, "s": 1745, "text": "Following built-in functions are common to both types" }, { "code": null, "e": 1845, "s": 1799, "text": "len() − return number of elements in sequence" }, { "code": null, "e": 1919, "s": 1845, "text": ">>> L1=[45,32,16,72,24]\n>>> len(L1)\n5\n>>> T1=(45,32,16,72,24)\n>>> len(T3)" }, { "code": null, "e": 1963, "s": 1919, "text": "max() − returns element with largest value." }, { "code": null, "e": 1993, "s": 1963, "text": ">>> max(L1)\n72\n>>> max(T1)\n72" }, { "code": null, "e": 2038, "s": 1993, "text": "min() − returns element with smallest value." }, { "code": null, "e": 2083, "s": 2038, "text": ">>> max(T1)\n72\n>>> min(L1)\n16\n>>> min(T1)\n16" }, { "code": null, "e": 2176, "s": 2083, "text": "List object is mutable. Hence, it is possible to append, update or delete an item from list." }, { "code": null, "e": 2435, "s": 2176, "text": ">>> L1=[45,32,16,72,24]\n>>> L1.append(56)\n>>> L1\n[45, 32, 16, 72, 24, 56]\n>>> L1.insert(4,10) #insert 10 at 4th index\n>>> L1\n[45, 32, 16, 72, 10, 24, 56]\n>>> L1.remove(16)\n>>> L1\n[45, 32, 72, 10, 24, 56]\n>>> L1[2]=100 #update\n>>> L1\n[45, 32, 100, 10, 24, 56]" }, { "code": null, "e": 2526, "s": 2435, "text": "Tuple is immutable object. Any operation that try to modify it , results in AttributeError" }, { "code": null, "e": 2745, "s": 2526, "text": "T1.append(56)\nAttributeError: 'tuple' object has no attribute 'append'\n>>> T1.remove(16)\nAttributeError: 'tuple' object has no attribute 'remove'\n>>> T1[2]=100\nTypeError: 'tuple' object does not support item assignment" } ]
Find maximum of minimum for every window size in a given array - GeeksforGeeks
22 Oct, 2021 Given an integer array of size n, find the maximum of the minimum’s of every window size in the array. Note that window size varies from 1 to n.Example: Input: arr[] = {10, 20, 30, 50, 10, 70, 30} Output: 70, 30, 20, 10, 10, 10, 10The first element in the output indicates the maximum of minimums of all windows of size 1. Minimums of windows of size 1 are {10}, {20}, {30}, {50}, {10}, {70} and {30}. Maximum of these minimums is 70The second element in the output indicates the maximum of minimums of all windows of size 2. Minimums of windows of size 2 are {10}, {20}, {30}, {10}, {10}, and {30}. Maximum of these minimums is 30The third element in the output indicates the maximum of minimums of all windows of size 3. Minimums of windows of size 3 are {10}, {20}, {10}, {10} and {10}. Maximum of these minimums is 20Similarly, other elements of output are computed. Naive Solution: Brute Force. Approach: A simple brute force approach to solve this problem can be to generate all the windows possible of a particular length say ‘L’ and find the minimum element in all such windows. Then find the maximum of all such elements and store it. Now the length of window is 1<=L<=N. So we have to generate all possible windows of size ‘1’ to ‘N’ and for generating each such window we have to mark the end-points of that window. So for that, we have to use a nested loop for fixing the starting and end point of the window respectively. Therefore there will be a use of triple-nested loop in brute-force approach mainly for fixing the length of the window, starting point and end point. C++ Java Python3 C# PHP Javascript // A naive method to find maximum of// minimum of all windows of different// sizes#include <bits/stdc++.h>using namespace std; void printMaxOfMin(int arr[], int n){ // Consider all windows of different // sizes starting from size 1 for (int k = 1; k <= n; k++) { // Initialize max of min for // current window size k int maxOfMin = INT_MIN; // Traverse through all windows // of current size k for (int i = 0; i <= n - k; i++) { // Find minimum of current window int min = arr[i]; for (int j = 1; j < k; j++) { if (arr[i + j] < min) min = arr[i + j]; } // Update maxOfMin if required if (min > maxOfMin) maxOfMin = min; } // Print max of min for current // window size cout << maxOfMin << " "; }} // Driver programint main(){ int arr[] = { 10, 20, 30, 50, 10, 70, 30 }; int n = sizeof(arr) / sizeof(arr[0]); printMaxOfMin(arr, n); return 0;} // A naive method to find maximum of// minimum of all windows of different sizes class Test { static int arr[] = { 10, 20, 30, 50, 10, 70, 30 }; static void printMaxOfMin(int n) { // Consider all windows of different // sizes starting from size 1 for (int k = 1; k <= n; k++) { // Initialize max of min for current // window size k int maxOfMin = Integer.MIN_VALUE; // Traverse through all windows of // current size k for (int i = 0; i <= n - k; i++) { // Find minimum of current window int min = arr[i]; for (int j = 1; j < k; j++) { if (arr[i + j] < min) min = arr[i + j]; } // Update maxOfMin if required if (min > maxOfMin) maxOfMin = min; } // Print max of min for current // window size System.out.print(maxOfMin + " "); } } // Driver method public static void main(String[] args) { printMaxOfMin(arr.length); }} # A naive method to find maximum of# minimum of all windows of different sizesINT_MIN = -1000000def printMaxOfMin(arr, n): # Consider all windows of different # sizes starting from size 1 for k in range(1, n + 1): # Initialize max of min for # current window size k maxOfMin = INT_MIN; # Traverse through all windows # of current size k for i in range(n - k + 1): # Find minimum of current window min = arr[i] for j in range(k): if (arr[i + j] < min): min = arr[i + j] # Update maxOfMin if required if (min > maxOfMin): maxOfMin = min # Print max of min for current window size print(maxOfMin, end = " ") # Driver Codearr = [10, 20, 30, 50, 10, 70, 30]n = len(arr)printMaxOfMin(arr, n) # This code is contributed by sahilshelangia // C# program using Naive approach to find// maximum of minimum of all windows of// different sizesusing System; class GFG{ static int []arr = {10, 20, 30, 50, 10, 70, 30}; // Function to print maximum of minimum static void printMaxOfMin(int n) { // Consider all windows of different // sizes starting from size 1 for (int k = 1; k <= n; k++) { // Initialize max of min for // current window size k int maxOfMin = int.MinValue; // Traverse through all windows // of current size k for (int i = 0; i <= n - k; i++) { // Find minimum of current window int min = arr[i]; for (int j = 1; j < k; j++) { if (arr[i + j] < min) min = arr[i + j]; } // Update maxOfMin if required if (min > maxOfMin) maxOfMin = min; } // Print max of min for current window size Console.Write(maxOfMin + " "); } } // Driver Code public static void Main() { printMaxOfMin(arr.Length); }} // This code is contributed by Sam007. <?php// PHP program to find maximum of// minimum of all windows of// different sizes // Method to find maximum of// minimum of all windows of// different sizesfunction printMaxOfMin($arr, $n){ // Consider all windows of // different sizes starting // from size 1 for($k = 1; $k <= $n; $k++) { // Initialize max of min for // current window size k $maxOfMin = PHP_INT_MIN; // Traverse through all windows // of current size k for ($i = 0; $i <= $n-$k; $i++) { // Find minimum of current window $min = $arr[$i]; for ($j = 1; $j < $k; $j++) { if ($arr[$i + $j] < $min) $min = $arr[$i + $j]; } // Update maxOfMin // if required if ($min > $maxOfMin) $maxOfMin = $min; } // Print max of min for // current window size echo $maxOfMin , " "; }} // Driver Code $arr= array(10, 20, 30, 50, 10, 70, 30); $n = sizeof($arr); printMaxOfMin($arr, $n); // This code is contributed by nitin mittal.?> <script> // A naive method to find maximum of// minimum of all windows of different sizes var arr = [ 10, 20, 30, 50, 10, 70, 30 ]; function printMaxOfMin(n) { // Consider all windows of different // sizes starting from size 1 for (k = 1; k <= n; k++) { // Initialize max of min for current // window size k var maxOfMin = Number.MIN_VALUE; // Traverse through all windows of // current size k for (i = 0; i <= n - k; i++) { // Find minimum of current window var min = arr[i]; for (j = 1; j < k; j++) { if (arr[i + j] < min) min = arr[i + j]; } // Update maxOfMin if required if (min > maxOfMin) maxOfMin = min; } // Print max of min for current // window size document.write(maxOfMin + " "); } } // Driver method printMaxOfMin(arr.length); // This code contributed by aashish1995</script> Output: 70 30 20 10 10 10 10 Complexity Analysis: Time Complexity: O(n3). As there is a use of triple nested loop in this approach. Auxiliary Space: O(1) As no extra data structure has been used to store the values. Efficient Solution: We can solve this problem in O(n) time. The idea is to use extra space. Below are detailed steps.Step 1: Find indexes of next smaller and previous smaller for every element. Next smaller is the nearest smallest element on right side of arr[i]. Similarly, a previous smaller element is the nearest smallest element on the left side of arr[i]. If there is no smaller element on the right side, then the next smaller is n. If there is no smaller on the left side, then the previous smaller is -1.For input {10, 20, 30, 50, 10, 70, 30}, array of indexes of next smaller is {7, 4, 4, 4, 7, 6, 7}. For input {10, 20, 30, 50, 10, 70, 30}, array of indexes of previous smaller is {-1, 0, 1, 2, -1, 4, 4}This step can be done in O(n) time using the approach discussed in next greater element.Step 2: Once we have indexes of next and previous smaller, we know that arr[i] is a minimum of a window of length “right[i] – left[i] – 1”. Lengths of windows for which the elements are minimum are {7, 3, 2, 1, 7, 1, 2}. This array indicates, the first element is minimum in the window of size 7, the second element is minimum in the window of size 3, and so on.Create an auxiliary array ans[n+1] to store the result. Values in ans[] can be filled by iterating through right[] and left[] for (int i=0; i < n; i++) { // length of the interval int len = right[i] - left[i] - 1; // arr[i] is a possible answer for // this length len interval ans[len] = max(ans[len], arr[i]); } We get the ans[] array as {0, 70, 30, 20, 0, 0, 0, 10}. Note that ans[0] or answer for length 0 is useless.Step 3: Some entries in ans[] are 0 and yet to be filled. For example, we know maximum of minimum for lengths 1, 2, 3 and 7 are 70, 30, 20 and 10 respectively, but we don’t know the same for lengths 4, 5 and 6. Below are few important observations to fill remaining entries a) Result for length i, i.e. ans[i] would always be greater or same as result for length i+1, i.e., ans[i+1]. b) If ans[i] is not filled it means there is no direct element which is minimum of length i and therefore either the element of length ans[i+1], or ans[i+2], and so on is same as ans[i] So we fill rest of the entries using below loop. for (int i=n-1; i>=1; i--) ans[i] = max(ans[i], ans[i+1]); Below is implementation of above algorithm. C++ Java Python3 C# Javascript // An efficient C++ program to find// maximum of all minimums of// windows of different sizes#include <iostream>#include<stack>using namespace std; void printMaxOfMin(int arr[], int n){// Used to find previous and next smaller stack<int> s; // Arrays to store previous and next smaller int left[n+1]; int right[n+1]; // Initialize elements of left[] and right[] for (int i=0; i<n; i++) { left[i] = -1; right[i] = n; } // Fill elements of left[] using logic discussed on // https://www.geeksforgeeks.org/next-greater-element/ for (int i=0; i<n; i++) { while (!s.empty() && arr[s.top()] >= arr[i]) s.pop(); if (!s.empty()) left[i] = s.top(); s.push(i); } // Empty the stack as stack is// going to be used for right[] while (!s.empty()) s.pop(); // Fill elements of right[] using same logic for (int i = n-1 ; i>=0 ; i-- ) { while (!s.empty() && arr[s.top()] >= arr[i]) s.pop(); if(!s.empty()) right[i] = s.top(); s.push(i); } // Create and initialize answer array int ans[n+1]; for (int i=0; i<=n; i++) ans[i] = 0; // Fill answer array by comparing minimums of all // lengths computed using left[] and right[] for (int i=0; i<n; i++) { // length of the interval int len = right[i] - left[i] - 1; // arr[i] is a possible answer for this length // 'len' interval, check if arr[i] is more than // max for 'len' ans[len] = max(ans[len], arr[i]); } // Some entries in ans[] may not be filled yet. Fill // them by taking values from right side of ans[] for (int i=n-1; i>=1; i--) ans[i] = max(ans[i], ans[i+1]); // Print the result for (int i=1; i<=n; i++) cout << ans[i] << " ";} // Driver programint main(){ int arr[] = {10, 20, 30, 50, 10, 70, 30}; int n = sizeof(arr)/sizeof(arr[0]); printMaxOfMin(arr, n); return 0;} // An efficient Java program to find// maximum of all minimums of// windows of different size import java.util.Stack; class Test{ static int arr[] = {10, 20, 30, 50, 10, 70, 30}; static void printMaxOfMin(int n) { // Used to find previous and next smaller Stack<Integer> s = new Stack<>(); // Arrays to store previous and next smaller int left[] = new int[n+1]; int right[] = new int[n+1]; // Initialize elements of left[] and right[] for (int i=0; i<n; i++) { left[i] = -1; right[i] = n; } // Fill elements of left[] using logic discussed on // https://www.geeksforgeeks.org/next-greater-element/ for (int i=0; i<n; i++) { while (!s.empty() && arr[s.peek()] >= arr[i]) s.pop(); if (!s.empty()) left[i] = s.peek(); s.push(i); } // Empty the stack as stack is// going to be used for right[] while (!s.empty()) s.pop(); // Fill elements of right[] using same logic for (int i = n-1 ; i>=0 ; i-- ) { while (!s.empty() && arr[s.peek()] >= arr[i]) s.pop(); if(!s.empty()) right[i] = s.peek(); s.push(i); } // Create and initialize answer array int ans[] = new int[n+1]; for (int i=0; i<=n; i++) ans[i] = 0; // Fill answer array by comparing minimums of all // lengths computed using left[] and right[] for (int i=0; i<n; i++) { // length of the interval int len = right[i] - left[i] - 1; // arr[i] is a possible answer for this length // 'len' interval, check if arr[i] is more than // max for 'len' ans[len] = Math.max(ans[len], arr[i]); } // Some entries in ans[] may not be filled yet. Fill // them by taking values from right side of ans[] for (int i=n-1; i>=1; i--) ans[i] = Math.max(ans[i], ans[i+1]); // Print the result for (int i=1; i<=n; i++) System.out.print(ans[i] + " "); } // Driver method public static void main(String[] args) { printMaxOfMin(arr.length); }} # An efficient Python3 program to find# maximum of all minimums of windows of# different sizes def printMaxOfMin(arr, n): s = [] # Used to find previous # and next smaller # Arrays to store previous and next # smaller. Initialize elements of # left[] and right[] left = [-1] * (n + 1) right = [n] * (n + 1) # Fill elements of left[] using logic discussed on # https:#www.geeksforgeeks.org/next-greater-element for i in range(n): while (len(s) != 0 and arr[s[-1]] >= arr[i]): s.pop() if (len(s) != 0): left[i] = s[-1] s.append(i) # Empty the stack as stack is going # to be used for right[] while (len(s) != 0): s.pop() # Fill elements of right[] using same logic for i in range(n - 1, -1, -1): while (len(s) != 0 and arr[s[-1]] >= arr[i]): s.pop() if(len(s) != 0): right[i] = s[-1] s.append(i) # Create and initialize answer array ans = [0] * (n + 1) for i in range(n + 1): ans[i] = 0 # Fill answer array by comparing minimums # of all. Lengths computed using left[] # and right[] for i in range(n): # Length of the interval Len = right[i] - left[i] - 1 # arr[i] is a possible answer for this # Length 'Len' interval, check if arr[i] # is more than max for 'Len' ans[Len] = max(ans[Len], arr[i]) # Some entries in ans[] may not be filled # yet. Fill them by taking values from # right side of ans[] for i in range(n - 1, 0, -1): ans[i] = max(ans[i], ans[i + 1]) # Print the result for i in range(1, n + 1): print(ans[i], end = " ") # Driver Codeif __name__ == '__main__': arr = [10, 20, 30, 50, 10, 70, 30] n = len(arr) printMaxOfMin(arr, n) # This code is contributed by PranchalK // An efficient C# program to find maximum// of all minimums of windows of different sizeusing System;using System.Collections.Generic; class GFG{public static int[] arr = new int[] {10, 20, 30, 50, 10, 70, 30}; public static void printMaxOfMin(int n){ // Used to find previous and next smaller Stack<int> s = new Stack<int>(); // Arrays to store previous // and next smaller int[] left = new int[n + 1]; int[] right = new int[n + 1]; // Initialize elements of left[] // and right[] for (int i = 0; i < n; i++) { left[i] = -1; right[i] = n; } // Fill elements of left[] using logic discussed on // https://www.geeksforgeeks.org/next-greater-element/ for (int i = 0; i < n; i++) { while (s.Count > 0 && arr[s.Peek()] >= arr[i]) { s.Pop(); } if (s.Count > 0) { left[i] = s.Peek(); } s.Push(i); } // Empty the stack as stack is going // to be used for right[] while (s.Count > 0) { s.Pop(); } // Fill elements of right[] using // same logic for (int i = n - 1 ; i >= 0 ; i--) { while (s.Count > 0 && arr[s.Peek()] >= arr[i]) { s.Pop(); } if (s.Count > 0) { right[i] = s.Peek(); } s.Push(i); } // Create and initialize answer array int[] ans = new int[n + 1]; for (int i = 0; i <= n; i++) { ans[i] = 0; } // Fill answer array by comparing // minimums of all lengths computed // using left[] and right[] for (int i = 0; i < n; i++) { // length of the interval int len = right[i] - left[i] - 1; // arr[i] is a possible answer for // this length 'len' interval, check x // if arr[i] is more than max for 'len' ans[len] = Math.Max(ans[len], arr[i]); } // Some entries in ans[] may not be // filled yet. Fill them by taking // values from right side of ans[] for (int i = n - 1; i >= 1; i--) { ans[i] = Math.Max(ans[i], ans[i + 1]); } // Print the result for (int i = 1; i <= n; i++) { Console.Write(ans[i] + " "); }} // Driver Codepublic static void Main(string[] args){ printMaxOfMin(arr.Length);}} // This code is contributed by Shrikant13 <script> // An efficient Javascript program to find maximum // of all minimums of windows of different size let arr = [10, 20, 30, 50, 10, 70, 30]; function printMaxOfMin(n) { // Used to find previous and next smaller let s = []; // Arrays to store previous // and next smaller let left = new Array(n + 1); left.fill(0); let right = new Array(n + 1); right.fill(0); // Initialize elements of left[] // and right[] for (let i = 0; i < n; i++) { left[i] = -1; right[i] = n; } // Fill elements of left[] using logic discussed on // https://www.geeksforgeeks.org/next-greater-element/ for (let i = 0; i < n; i++) { while (s.length > 0 && arr[s[s.length - 1]] >= arr[i]) { s.pop(); } if (s.length > 0) { left[i] = s[s.length - 1]; } s.push(i); } // Empty the stack as stack is going // to be used for right[] while (s.length > 0) { s.pop(); } // Fill elements of right[] using // same logic for (let i = n - 1 ; i >= 0 ; i--) { while (s.length > 0 && arr[s[s.length - 1]] >= arr[i]) { s.pop(); } if (s.length > 0) { right[i] = s[s.length - 1]; } s.push(i); } // Create and initialize answer array let ans = new Array(n + 1); ans.fill(0); for (let i = 0; i <= n; i++) { ans[i] = 0; } // Fill answer array by comparing // minimums of all lengths computed // using left[] and right[] for (let i = 0; i < n; i++) { // length of the interval let len = right[i] - left[i] - 1; // arr[i] is a possible answer for // this length 'len' interval, check x // if arr[i] is more than max for 'len' ans[len] = Math.max(ans[len], arr[i]); } // Some entries in ans[] may not be // filled yet. Fill them by taking // values from right side of ans[] for (let i = n - 1; i >= 1; i--) { ans[i] = Math.max(ans[i], ans[i + 1]); } // Print the result for (let i = 1; i <= n; i++) { document.write(ans[i] + " "); } } printMaxOfMin(arr.length); // This code is contributed by decode2207.</script> Output: 70 30 20 10 10 10 10 Complexity Analysis: Time Complexity: O(n). Every sub-task in this approach takes Linear time. Auxiliary Space : O(n). Use of stack for calculating next minimum and arrays to store the intermediate results. This article is contributed by Ekta Goel and Ayush Govil. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Sam007 nitin mittal shrikanth13 sahilshelangia sanskar27jain PranchalKatiyar nidhi_biet bidibaaz123 brashcaran aashish1995 decode2207 simranarora5sos Amazon sliding-window Stack Amazon sliding-window Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Implement Stack using Queues Iterative Depth First Traversal of Graph Merge Overlapping Intervals Reverse a stack using recursion Largest Rectangular Area in a Histogram | Set 2 Difference between Stack and Queue Data Structures The Stock Span Problem Design and Implement Special Stack Data Structure | Added Space Optimized Version Sort a stack using recursion Iterative Postorder Traversal | Set 2 (Using One Stack)
[ { "code": null, "e": 25046, "s": 25018, "text": "\n22 Oct, 2021" }, { "code": null, "e": 25199, "s": 25046, "text": "Given an integer array of size n, find the maximum of the minimum’s of every window size in the array. Note that window size varies from 1 to n.Example:" }, { "code": null, "e": 25919, "s": 25199, "text": " Input: arr[] = {10, 20, 30, 50, 10, 70, 30} Output: 70, 30, 20, 10, 10, 10, 10The first element in the output indicates the maximum of minimums of all windows of size 1. Minimums of windows of size 1 are {10}, {20}, {30}, {50}, {10}, {70} and {30}. Maximum of these minimums is 70The second element in the output indicates the maximum of minimums of all windows of size 2. Minimums of windows of size 2 are {10}, {20}, {30}, {10}, {10}, and {30}. Maximum of these minimums is 30The third element in the output indicates the maximum of minimums of all windows of size 3. Minimums of windows of size 3 are {10}, {20}, {10}, {10} and {10}. Maximum of these minimums is 20Similarly, other elements of output are computed. " }, { "code": null, "e": 26633, "s": 25919, "text": "Naive Solution: Brute Force. Approach: A simple brute force approach to solve this problem can be to generate all the windows possible of a particular length say ‘L’ and find the minimum element in all such windows. Then find the maximum of all such elements and store it. Now the length of window is 1<=L<=N. So we have to generate all possible windows of size ‘1’ to ‘N’ and for generating each such window we have to mark the end-points of that window. So for that, we have to use a nested loop for fixing the starting and end point of the window respectively. Therefore there will be a use of triple-nested loop in brute-force approach mainly for fixing the length of the window, starting point and end point." }, { "code": null, "e": 26637, "s": 26633, "text": "C++" }, { "code": null, "e": 26642, "s": 26637, "text": "Java" }, { "code": null, "e": 26650, "s": 26642, "text": "Python3" }, { "code": null, "e": 26653, "s": 26650, "text": "C#" }, { "code": null, "e": 26657, "s": 26653, "text": "PHP" }, { "code": null, "e": 26668, "s": 26657, "text": "Javascript" }, { "code": "// A naive method to find maximum of// minimum of all windows of different// sizes#include <bits/stdc++.h>using namespace std; void printMaxOfMin(int arr[], int n){ // Consider all windows of different // sizes starting from size 1 for (int k = 1; k <= n; k++) { // Initialize max of min for // current window size k int maxOfMin = INT_MIN; // Traverse through all windows // of current size k for (int i = 0; i <= n - k; i++) { // Find minimum of current window int min = arr[i]; for (int j = 1; j < k; j++) { if (arr[i + j] < min) min = arr[i + j]; } // Update maxOfMin if required if (min > maxOfMin) maxOfMin = min; } // Print max of min for current // window size cout << maxOfMin << \" \"; }} // Driver programint main(){ int arr[] = { 10, 20, 30, 50, 10, 70, 30 }; int n = sizeof(arr) / sizeof(arr[0]); printMaxOfMin(arr, n); return 0;}", "e": 27722, "s": 26668, "text": null }, { "code": "// A naive method to find maximum of// minimum of all windows of different sizes class Test { static int arr[] = { 10, 20, 30, 50, 10, 70, 30 }; static void printMaxOfMin(int n) { // Consider all windows of different // sizes starting from size 1 for (int k = 1; k <= n; k++) { // Initialize max of min for current // window size k int maxOfMin = Integer.MIN_VALUE; // Traverse through all windows of // current size k for (int i = 0; i <= n - k; i++) { // Find minimum of current window int min = arr[i]; for (int j = 1; j < k; j++) { if (arr[i + j] < min) min = arr[i + j]; } // Update maxOfMin if required if (min > maxOfMin) maxOfMin = min; } // Print max of min for current // window size System.out.print(maxOfMin + \" \"); } } // Driver method public static void main(String[] args) { printMaxOfMin(arr.length); }}", "e": 28867, "s": 27722, "text": null }, { "code": "# A naive method to find maximum of# minimum of all windows of different sizesINT_MIN = -1000000def printMaxOfMin(arr, n): # Consider all windows of different # sizes starting from size 1 for k in range(1, n + 1): # Initialize max of min for # current window size k maxOfMin = INT_MIN; # Traverse through all windows # of current size k for i in range(n - k + 1): # Find minimum of current window min = arr[i] for j in range(k): if (arr[i + j] < min): min = arr[i + j] # Update maxOfMin if required if (min > maxOfMin): maxOfMin = min # Print max of min for current window size print(maxOfMin, end = \" \") # Driver Codearr = [10, 20, 30, 50, 10, 70, 30]n = len(arr)printMaxOfMin(arr, n) # This code is contributed by sahilshelangia", "e": 29813, "s": 28867, "text": null }, { "code": "// C# program using Naive approach to find// maximum of minimum of all windows of// different sizesusing System; class GFG{ static int []arr = {10, 20, 30, 50, 10, 70, 30}; // Function to print maximum of minimum static void printMaxOfMin(int n) { // Consider all windows of different // sizes starting from size 1 for (int k = 1; k <= n; k++) { // Initialize max of min for // current window size k int maxOfMin = int.MinValue; // Traverse through all windows // of current size k for (int i = 0; i <= n - k; i++) { // Find minimum of current window int min = arr[i]; for (int j = 1; j < k; j++) { if (arr[i + j] < min) min = arr[i + j]; } // Update maxOfMin if required if (min > maxOfMin) maxOfMin = min; } // Print max of min for current window size Console.Write(maxOfMin + \" \"); } } // Driver Code public static void Main() { printMaxOfMin(arr.Length); }} // This code is contributed by Sam007.", "e": 31128, "s": 29813, "text": null }, { "code": "<?php// PHP program to find maximum of// minimum of all windows of// different sizes // Method to find maximum of// minimum of all windows of// different sizesfunction printMaxOfMin($arr, $n){ // Consider all windows of // different sizes starting // from size 1 for($k = 1; $k <= $n; $k++) { // Initialize max of min for // current window size k $maxOfMin = PHP_INT_MIN; // Traverse through all windows // of current size k for ($i = 0; $i <= $n-$k; $i++) { // Find minimum of current window $min = $arr[$i]; for ($j = 1; $j < $k; $j++) { if ($arr[$i + $j] < $min) $min = $arr[$i + $j]; } // Update maxOfMin // if required if ($min > $maxOfMin) $maxOfMin = $min; } // Print max of min for // current window size echo $maxOfMin , \" \"; }} // Driver Code $arr= array(10, 20, 30, 50, 10, 70, 30); $n = sizeof($arr); printMaxOfMin($arr, $n); // This code is contributed by nitin mittal.?>", "e": 32284, "s": 31128, "text": null }, { "code": "<script> // A naive method to find maximum of// minimum of all windows of different sizes var arr = [ 10, 20, 30, 50, 10, 70, 30 ]; function printMaxOfMin(n) { // Consider all windows of different // sizes starting from size 1 for (k = 1; k <= n; k++) { // Initialize max of min for current // window size k var maxOfMin = Number.MIN_VALUE; // Traverse through all windows of // current size k for (i = 0; i <= n - k; i++) { // Find minimum of current window var min = arr[i]; for (j = 1; j < k; j++) { if (arr[i + j] < min) min = arr[i + j]; } // Update maxOfMin if required if (min > maxOfMin) maxOfMin = min; } // Print max of min for current // window size document.write(maxOfMin + \" \"); } } // Driver method printMaxOfMin(arr.length); // This code contributed by aashish1995</script>", "e": 33394, "s": 32284, "text": null }, { "code": null, "e": 33403, "s": 33394, "text": "Output: " }, { "code": null, "e": 33424, "s": 33403, "text": "70 30 20 10 10 10 10" }, { "code": null, "e": 33447, "s": 33424, "text": "Complexity Analysis: " }, { "code": null, "e": 33529, "s": 33447, "text": "Time Complexity: O(n3). As there is a use of triple nested loop in this approach." }, { "code": null, "e": 33613, "s": 33529, "text": "Auxiliary Space: O(1) As no extra data structure has been used to store the values." }, { "code": null, "e": 34905, "s": 33613, "text": "Efficient Solution: We can solve this problem in O(n) time. The idea is to use extra space. Below are detailed steps.Step 1: Find indexes of next smaller and previous smaller for every element. Next smaller is the nearest smallest element on right side of arr[i]. Similarly, a previous smaller element is the nearest smallest element on the left side of arr[i]. If there is no smaller element on the right side, then the next smaller is n. If there is no smaller on the left side, then the previous smaller is -1.For input {10, 20, 30, 50, 10, 70, 30}, array of indexes of next smaller is {7, 4, 4, 4, 7, 6, 7}. For input {10, 20, 30, 50, 10, 70, 30}, array of indexes of previous smaller is {-1, 0, 1, 2, -1, 4, 4}This step can be done in O(n) time using the approach discussed in next greater element.Step 2: Once we have indexes of next and previous smaller, we know that arr[i] is a minimum of a window of length “right[i] – left[i] – 1”. Lengths of windows for which the elements are minimum are {7, 3, 2, 1, 7, 1, 2}. This array indicates, the first element is minimum in the window of size 7, the second element is minimum in the window of size 3, and so on.Create an auxiliary array ans[n+1] to store the result. Values in ans[] can be filled by iterating through right[] and left[] " }, { "code": null, "e": 35145, "s": 34905, "text": " for (int i=0; i < n; i++)\n {\n // length of the interval\n int len = right[i] - left[i] - 1;\n\n // arr[i] is a possible answer for\n // this length len interval\n ans[len] = max(ans[len], arr[i]);\n }" }, { "code": null, "e": 35872, "s": 35145, "text": "We get the ans[] array as {0, 70, 30, 20, 0, 0, 0, 10}. Note that ans[0] or answer for length 0 is useless.Step 3: Some entries in ans[] are 0 and yet to be filled. For example, we know maximum of minimum for lengths 1, 2, 3 and 7 are 70, 30, 20 and 10 respectively, but we don’t know the same for lengths 4, 5 and 6. Below are few important observations to fill remaining entries a) Result for length i, i.e. ans[i] would always be greater or same as result for length i+1, i.e., ans[i+1]. b) If ans[i] is not filled it means there is no direct element which is minimum of length i and therefore either the element of length ans[i+1], or ans[i+2], and so on is same as ans[i] So we fill rest of the entries using below loop. " }, { "code": null, "e": 35943, "s": 35872, "text": " for (int i=n-1; i>=1; i--)\n ans[i] = max(ans[i], ans[i+1]);" }, { "code": null, "e": 35989, "s": 35943, "text": "Below is implementation of above algorithm. " }, { "code": null, "e": 35993, "s": 35989, "text": "C++" }, { "code": null, "e": 35998, "s": 35993, "text": "Java" }, { "code": null, "e": 36006, "s": 35998, "text": "Python3" }, { "code": null, "e": 36009, "s": 36006, "text": "C#" }, { "code": null, "e": 36020, "s": 36009, "text": "Javascript" }, { "code": "// An efficient C++ program to find// maximum of all minimums of// windows of different sizes#include <iostream>#include<stack>using namespace std; void printMaxOfMin(int arr[], int n){// Used to find previous and next smaller stack<int> s; // Arrays to store previous and next smaller int left[n+1]; int right[n+1]; // Initialize elements of left[] and right[] for (int i=0; i<n; i++) { left[i] = -1; right[i] = n; } // Fill elements of left[] using logic discussed on // https://www.geeksforgeeks.org/next-greater-element/ for (int i=0; i<n; i++) { while (!s.empty() && arr[s.top()] >= arr[i]) s.pop(); if (!s.empty()) left[i] = s.top(); s.push(i); } // Empty the stack as stack is// going to be used for right[] while (!s.empty()) s.pop(); // Fill elements of right[] using same logic for (int i = n-1 ; i>=0 ; i-- ) { while (!s.empty() && arr[s.top()] >= arr[i]) s.pop(); if(!s.empty()) right[i] = s.top(); s.push(i); } // Create and initialize answer array int ans[n+1]; for (int i=0; i<=n; i++) ans[i] = 0; // Fill answer array by comparing minimums of all // lengths computed using left[] and right[] for (int i=0; i<n; i++) { // length of the interval int len = right[i] - left[i] - 1; // arr[i] is a possible answer for this length // 'len' interval, check if arr[i] is more than // max for 'len' ans[len] = max(ans[len], arr[i]); } // Some entries in ans[] may not be filled yet. Fill // them by taking values from right side of ans[] for (int i=n-1; i>=1; i--) ans[i] = max(ans[i], ans[i+1]); // Print the result for (int i=1; i<=n; i++) cout << ans[i] << \" \";} // Driver programint main(){ int arr[] = {10, 20, 30, 50, 10, 70, 30}; int n = sizeof(arr)/sizeof(arr[0]); printMaxOfMin(arr, n); return 0;}", "e": 38027, "s": 36020, "text": null }, { "code": "// An efficient Java program to find// maximum of all minimums of// windows of different size import java.util.Stack; class Test{ static int arr[] = {10, 20, 30, 50, 10, 70, 30}; static void printMaxOfMin(int n) { // Used to find previous and next smaller Stack<Integer> s = new Stack<>(); // Arrays to store previous and next smaller int left[] = new int[n+1]; int right[] = new int[n+1]; // Initialize elements of left[] and right[] for (int i=0; i<n; i++) { left[i] = -1; right[i] = n; } // Fill elements of left[] using logic discussed on // https://www.geeksforgeeks.org/next-greater-element/ for (int i=0; i<n; i++) { while (!s.empty() && arr[s.peek()] >= arr[i]) s.pop(); if (!s.empty()) left[i] = s.peek(); s.push(i); } // Empty the stack as stack is// going to be used for right[] while (!s.empty()) s.pop(); // Fill elements of right[] using same logic for (int i = n-1 ; i>=0 ; i-- ) { while (!s.empty() && arr[s.peek()] >= arr[i]) s.pop(); if(!s.empty()) right[i] = s.peek(); s.push(i); } // Create and initialize answer array int ans[] = new int[n+1]; for (int i=0; i<=n; i++) ans[i] = 0; // Fill answer array by comparing minimums of all // lengths computed using left[] and right[] for (int i=0; i<n; i++) { // length of the interval int len = right[i] - left[i] - 1; // arr[i] is a possible answer for this length // 'len' interval, check if arr[i] is more than // max for 'len' ans[len] = Math.max(ans[len], arr[i]); } // Some entries in ans[] may not be filled yet. Fill // them by taking values from right side of ans[] for (int i=n-1; i>=1; i--) ans[i] = Math.max(ans[i], ans[i+1]); // Print the result for (int i=1; i<=n; i++) System.out.print(ans[i] + \" \"); } // Driver method public static void main(String[] args) { printMaxOfMin(arr.length); }}", "e": 40413, "s": 38027, "text": null }, { "code": "# An efficient Python3 program to find# maximum of all minimums of windows of# different sizes def printMaxOfMin(arr, n): s = [] # Used to find previous # and next smaller # Arrays to store previous and next # smaller. Initialize elements of # left[] and right[] left = [-1] * (n + 1) right = [n] * (n + 1) # Fill elements of left[] using logic discussed on # https:#www.geeksforgeeks.org/next-greater-element for i in range(n): while (len(s) != 0 and arr[s[-1]] >= arr[i]): s.pop() if (len(s) != 0): left[i] = s[-1] s.append(i) # Empty the stack as stack is going # to be used for right[] while (len(s) != 0): s.pop() # Fill elements of right[] using same logic for i in range(n - 1, -1, -1): while (len(s) != 0 and arr[s[-1]] >= arr[i]): s.pop() if(len(s) != 0): right[i] = s[-1] s.append(i) # Create and initialize answer array ans = [0] * (n + 1) for i in range(n + 1): ans[i] = 0 # Fill answer array by comparing minimums # of all. Lengths computed using left[] # and right[] for i in range(n): # Length of the interval Len = right[i] - left[i] - 1 # arr[i] is a possible answer for this # Length 'Len' interval, check if arr[i] # is more than max for 'Len' ans[Len] = max(ans[Len], arr[i]) # Some entries in ans[] may not be filled # yet. Fill them by taking values from # right side of ans[] for i in range(n - 1, 0, -1): ans[i] = max(ans[i], ans[i + 1]) # Print the result for i in range(1, n + 1): print(ans[i], end = \" \") # Driver Codeif __name__ == '__main__': arr = [10, 20, 30, 50, 10, 70, 30] n = len(arr) printMaxOfMin(arr, n) # This code is contributed by PranchalK", "e": 42294, "s": 40413, "text": null }, { "code": "// An efficient C# program to find maximum// of all minimums of windows of different sizeusing System;using System.Collections.Generic; class GFG{public static int[] arr = new int[] {10, 20, 30, 50, 10, 70, 30}; public static void printMaxOfMin(int n){ // Used to find previous and next smaller Stack<int> s = new Stack<int>(); // Arrays to store previous // and next smaller int[] left = new int[n + 1]; int[] right = new int[n + 1]; // Initialize elements of left[] // and right[] for (int i = 0; i < n; i++) { left[i] = -1; right[i] = n; } // Fill elements of left[] using logic discussed on // https://www.geeksforgeeks.org/next-greater-element/ for (int i = 0; i < n; i++) { while (s.Count > 0 && arr[s.Peek()] >= arr[i]) { s.Pop(); } if (s.Count > 0) { left[i] = s.Peek(); } s.Push(i); } // Empty the stack as stack is going // to be used for right[] while (s.Count > 0) { s.Pop(); } // Fill elements of right[] using // same logic for (int i = n - 1 ; i >= 0 ; i--) { while (s.Count > 0 && arr[s.Peek()] >= arr[i]) { s.Pop(); } if (s.Count > 0) { right[i] = s.Peek(); } s.Push(i); } // Create and initialize answer array int[] ans = new int[n + 1]; for (int i = 0; i <= n; i++) { ans[i] = 0; } // Fill answer array by comparing // minimums of all lengths computed // using left[] and right[] for (int i = 0; i < n; i++) { // length of the interval int len = right[i] - left[i] - 1; // arr[i] is a possible answer for // this length 'len' interval, check x // if arr[i] is more than max for 'len' ans[len] = Math.Max(ans[len], arr[i]); } // Some entries in ans[] may not be // filled yet. Fill them by taking // values from right side of ans[] for (int i = n - 1; i >= 1; i--) { ans[i] = Math.Max(ans[i], ans[i + 1]); } // Print the result for (int i = 1; i <= n; i++) { Console.Write(ans[i] + \" \"); }} // Driver Codepublic static void Main(string[] args){ printMaxOfMin(arr.Length);}} // This code is contributed by Shrikant13", "e": 44676, "s": 42294, "text": null }, { "code": "<script> // An efficient Javascript program to find maximum // of all minimums of windows of different size let arr = [10, 20, 30, 50, 10, 70, 30]; function printMaxOfMin(n) { // Used to find previous and next smaller let s = []; // Arrays to store previous // and next smaller let left = new Array(n + 1); left.fill(0); let right = new Array(n + 1); right.fill(0); // Initialize elements of left[] // and right[] for (let i = 0; i < n; i++) { left[i] = -1; right[i] = n; } // Fill elements of left[] using logic discussed on // https://www.geeksforgeeks.org/next-greater-element/ for (let i = 0; i < n; i++) { while (s.length > 0 && arr[s[s.length - 1]] >= arr[i]) { s.pop(); } if (s.length > 0) { left[i] = s[s.length - 1]; } s.push(i); } // Empty the stack as stack is going // to be used for right[] while (s.length > 0) { s.pop(); } // Fill elements of right[] using // same logic for (let i = n - 1 ; i >= 0 ; i--) { while (s.length > 0 && arr[s[s.length - 1]] >= arr[i]) { s.pop(); } if (s.length > 0) { right[i] = s[s.length - 1]; } s.push(i); } // Create and initialize answer array let ans = new Array(n + 1); ans.fill(0); for (let i = 0; i <= n; i++) { ans[i] = 0; } // Fill answer array by comparing // minimums of all lengths computed // using left[] and right[] for (let i = 0; i < n; i++) { // length of the interval let len = right[i] - left[i] - 1; // arr[i] is a possible answer for // this length 'len' interval, check x // if arr[i] is more than max for 'len' ans[len] = Math.max(ans[len], arr[i]); } // Some entries in ans[] may not be // filled yet. Fill them by taking // values from right side of ans[] for (let i = n - 1; i >= 1; i--) { ans[i] = Math.max(ans[i], ans[i + 1]); } // Print the result for (let i = 1; i <= n; i++) { document.write(ans[i] + \" \"); } } printMaxOfMin(arr.length); // This code is contributed by decode2207.</script>", "e": 47299, "s": 44676, "text": null }, { "code": null, "e": 47308, "s": 47299, "text": "Output: " }, { "code": null, "e": 47329, "s": 47308, "text": "70 30 20 10 10 10 10" }, { "code": null, "e": 47352, "s": 47329, "text": "Complexity Analysis: " }, { "code": null, "e": 47426, "s": 47352, "text": "Time Complexity: O(n). Every sub-task in this approach takes Linear time." }, { "code": null, "e": 47538, "s": 47426, "text": "Auxiliary Space : O(n). Use of stack for calculating next minimum and arrays to store the intermediate results." }, { "code": null, "e": 47720, "s": 47538, "text": "This article is contributed by Ekta Goel and Ayush Govil. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 47727, "s": 47720, "text": "Sam007" }, { "code": null, "e": 47740, "s": 47727, "text": "nitin mittal" }, { "code": null, "e": 47752, "s": 47740, "text": "shrikanth13" }, { "code": null, "e": 47767, "s": 47752, "text": "sahilshelangia" }, { "code": null, "e": 47781, "s": 47767, "text": "sanskar27jain" }, { "code": null, "e": 47797, "s": 47781, "text": "PranchalKatiyar" }, { "code": null, "e": 47808, "s": 47797, "text": "nidhi_biet" }, { "code": null, "e": 47820, "s": 47808, "text": "bidibaaz123" }, { "code": null, "e": 47831, "s": 47820, "text": "brashcaran" }, { "code": null, "e": 47843, "s": 47831, "text": "aashish1995" }, { "code": null, "e": 47854, "s": 47843, "text": "decode2207" }, { "code": null, "e": 47870, "s": 47854, "text": "simranarora5sos" }, { "code": null, "e": 47877, "s": 47870, "text": "Amazon" }, { "code": null, "e": 47892, "s": 47877, "text": "sliding-window" }, { "code": null, "e": 47898, "s": 47892, "text": "Stack" }, { "code": null, "e": 47905, "s": 47898, "text": "Amazon" }, { "code": null, "e": 47920, "s": 47905, "text": "sliding-window" }, { "code": null, "e": 47926, "s": 47920, "text": "Stack" }, { "code": null, "e": 48024, "s": 47926, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 48033, "s": 48024, "text": "Comments" }, { "code": null, "e": 48046, "s": 48033, "text": "Old Comments" }, { "code": null, "e": 48075, "s": 48046, "text": "Implement Stack using Queues" }, { "code": null, "e": 48116, "s": 48075, "text": "Iterative Depth First Traversal of Graph" }, { "code": null, "e": 48144, "s": 48116, "text": "Merge Overlapping Intervals" }, { "code": null, "e": 48176, "s": 48144, "text": "Reverse a stack using recursion" }, { "code": null, "e": 48224, "s": 48176, "text": "Largest Rectangular Area in a Histogram | Set 2" }, { "code": null, "e": 48275, "s": 48224, "text": "Difference between Stack and Queue Data Structures" }, { "code": null, "e": 48298, "s": 48275, "text": "The Stock Span Problem" }, { "code": null, "e": 48380, "s": 48298, "text": "Design and Implement Special Stack Data Structure | Added Space Optimized Version" }, { "code": null, "e": 48409, "s": 48380, "text": "Sort a stack using recursion" } ]
Python - Synonyms and Antonyms
Synonyms and Antonyms are available as part of the wordnet which a lexical database for the English language. It is available as part of nltk corpora access. In wordnet Synonyms are the words that denote the same concept and are interchangeable in many contexts so that they are grouped into unordered sets (synsets). We use these synsets to derive the synonyms and antonyms as shown in the below programs. from nltk.corpus import wordnet synonyms = [] for syn in wordnet.synsets("Soil"): for lm in syn.lemmas(): synonyms.append(lm.name()) print (set(synonyms)) When we run the above program we get the following output − set([grease', filth', dirt', begrime', soil', grime', land', bemire', dirty', grunge', stain', territory', colly', ground']) To get the antonyms we simply uses the antonym function. from nltk.corpus import wordnet antonyms = [] for syn in wordnet.synsets("ahead"): for lm in syn.lemmas(): if lm.antonyms(): antonyms.append(lm.antonyms()[0].name()) print(set(antonyms)) When we run the above program, we get the following output − set([backward', back']) 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": 2995, "s": 2587, "text": " Synonyms and Antonyms are available as part of the wordnet which a lexical database for the English language. It is available as part of nltk corpora access. In wordnet Synonyms are the words that denote the same concept and are interchangeable in many contexts so that they are grouped into unordered sets (synsets). We use these synsets to derive the synonyms and antonyms as shown in the below programs." }, { "code": null, "e": 3169, "s": 2995, "text": "from nltk.corpus import wordnet\n\nsynonyms = []\n\nfor syn in wordnet.synsets(\"Soil\"):\n for lm in syn.lemmas():\n synonyms.append(lm.name())\nprint (set(synonyms))" }, { "code": null, "e": 3229, "s": 3169, "text": "When we run the above program we get the following output −" }, { "code": null, "e": 3357, "s": 3229, "text": "set([grease', filth', dirt', begrime', soil', \ngrime', land', bemire', dirty', grunge', \nstain', territory', colly', ground'])\n" }, { "code": null, "e": 3414, "s": 3357, "text": "To get the antonyms we simply uses the antonym function." }, { "code": null, "e": 3627, "s": 3414, "text": "from nltk.corpus import wordnet\nantonyms = []\n\nfor syn in wordnet.synsets(\"ahead\"):\n for lm in syn.lemmas():\n if lm.antonyms():\n antonyms.append(lm.antonyms()[0].name())\n\nprint(set(antonyms))" }, { "code": null, "e": 3688, "s": 3627, "text": "When we run the above program, we get the following output −" }, { "code": null, "e": 3713, "s": 3688, "text": "set([backward', back'])\n" }, { "code": null, "e": 3750, "s": 3713, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3766, "s": 3750, "text": " Malhar Lathkar" }, { "code": null, "e": 3799, "s": 3766, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3818, "s": 3799, "text": " Arnab Chakraborty" }, { "code": null, "e": 3853, "s": 3818, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3875, "s": 3853, "text": " In28Minutes Official" }, { "code": null, "e": 3909, "s": 3875, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3937, "s": 3909, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3972, "s": 3937, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3986, "s": 3972, "text": " Lets Kode It" }, { "code": null, "e": 4019, "s": 3986, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 4036, "s": 4019, "text": " Abhilash Nelson" }, { "code": null, "e": 4043, "s": 4036, "text": " Print" }, { "code": null, "e": 4054, "s": 4043, "text": " Add Notes" } ]
Python Grayscaling of Images using OpenCV
In this tutorial, we are going to learn how to change the grayscaling of an image using Grayscaling is the process of changing the images from different colour spaces like RGB,CMYK, etc.., to shades of gray. Install the OpenCV module if you didn't install it before. pip install opencv-python After installing the OpenCV module. Follow the below steps to write the code. Import the cv2 module. Read the image with cv2.imread(image_path) and store it in a variable. Convert the image colour scale using cv2.cvtColor(image, cv2.COLOR_BGR1GRAY) and store it in a variable. Show the image using cv2.imshow(image). Wait until any key press to exit using the cv2.waitKey(). Destroy all the opened windows using cv2.destroyAllWindows() method. # importing the opencv(cv2) module import cv2 # reading the image image = cv2.imread('lion.png') # changing the color space gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # showing the resultant image cv2.imshow('Grayscale Lion', gray_image) # waiting until key press cv2.waitKey() # destroy all the windows cv2.destroyAllWindows() If you run the above code, then you will see the image in grayscale as shown below. If you have any doubts in the tutorial, mention them in the comment section.
[ { "code": null, "e": 1329, "s": 1062, "text": "In this tutorial, we are going to learn how to change the grayscaling of an image using Grayscaling is the process of changing the images from different colour spaces like RGB,CMYK, etc.., to shades of gray. Install the OpenCV module if you didn't install it before." }, { "code": null, "e": 1355, "s": 1329, "text": "pip install opencv-python" }, { "code": null, "e": 1433, "s": 1355, "text": "After installing the OpenCV module. Follow the below steps to write the code." }, { "code": null, "e": 1456, "s": 1433, "text": "Import the cv2 module." }, { "code": null, "e": 1527, "s": 1456, "text": "Read the image with cv2.imread(image_path) and store it in a variable." }, { "code": null, "e": 1632, "s": 1527, "text": "Convert the image colour scale using cv2.cvtColor(image, cv2.COLOR_BGR1GRAY) and store it in a variable." }, { "code": null, "e": 1672, "s": 1632, "text": "Show the image using cv2.imshow(image)." }, { "code": null, "e": 1730, "s": 1672, "text": "Wait until any key press to exit using the cv2.waitKey()." }, { "code": null, "e": 1799, "s": 1730, "text": "Destroy all the opened windows using cv2.destroyAllWindows() method." }, { "code": null, "e": 2137, "s": 1799, "text": "# importing the opencv(cv2) module\nimport cv2\n# reading the image\nimage = cv2.imread('lion.png')\n# changing the color space\ngray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n# showing the resultant image\ncv2.imshow('Grayscale Lion', gray_image)\n# waiting until key press\ncv2.waitKey()\n# destroy all the windows\ncv2.destroyAllWindows()" }, { "code": null, "e": 2221, "s": 2137, "text": "If you run the above code, then you will see the image in grayscale as shown below." }, { "code": null, "e": 2298, "s": 2221, "text": "If you have any doubts in the tutorial, mention them in the comment section." } ]
C library function - exp()
The C library function double exp(double x) returns the value of e raised to the xth power. Following is the declaration for exp() function. double exp(double x) x − This is the floating point value. x − This is the floating point value. This function returns the exponential value of x. The following example shows the usage of exp() function. #include <stdio.h> #include <math.h> int main () { double x = 0; printf("The exponential value of %lf is %lf\n", x, exp(x)); printf("The exponential value of %lf is %lf\n", x+1, exp(x+1)); printf("The exponential value of %lf is %lf\n", x+2, exp(x+2)); return(0); } Let us compile and run the above program that will produce the following result − The exponential value of 0.000000 is 1.000000 The exponential value of 1.000000 is 2.718282 The exponential value of 2.000000 is 7.389056 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2099, "s": 2007, "text": "The C library function double exp(double x) returns the value of e raised to the xth power." }, { "code": null, "e": 2148, "s": 2099, "text": "Following is the declaration for exp() function." }, { "code": null, "e": 2169, "s": 2148, "text": "double exp(double x)" }, { "code": null, "e": 2207, "s": 2169, "text": "x − This is the floating point value." }, { "code": null, "e": 2245, "s": 2207, "text": "x − This is the floating point value." }, { "code": null, "e": 2295, "s": 2245, "text": "This function returns the exponential value of x." }, { "code": null, "e": 2352, "s": 2295, "text": "The following example shows the usage of exp() function." }, { "code": null, "e": 2641, "s": 2352, "text": "#include <stdio.h>\n#include <math.h>\n\nint main () {\n double x = 0;\n \n printf(\"The exponential value of %lf is %lf\\n\", x, exp(x));\n printf(\"The exponential value of %lf is %lf\\n\", x+1, exp(x+1));\n printf(\"The exponential value of %lf is %lf\\n\", x+2, exp(x+2));\n \n return(0);\n}" }, { "code": null, "e": 2723, "s": 2641, "text": "Let us compile and run the above program that will produce the following result −" }, { "code": null, "e": 2862, "s": 2723, "text": "The exponential value of 0.000000 is 1.000000\nThe exponential value of 1.000000 is 2.718282\nThe exponential value of 2.000000 is 7.389056\n" }, { "code": null, "e": 2895, "s": 2862, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 2910, "s": 2895, "text": " Nishant Malik" }, { "code": null, "e": 2945, "s": 2910, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2960, "s": 2945, "text": " Nishant Malik" }, { "code": null, "e": 2995, "s": 2960, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3009, "s": 2995, "text": " Asif Hussain" }, { "code": null, "e": 3042, "s": 3009, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3060, "s": 3042, "text": " Richa Maheshwari" }, { "code": null, "e": 3095, "s": 3060, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3114, "s": 3095, "text": " Vandana Annavaram" }, { "code": null, "e": 3147, "s": 3114, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 3159, "s": 3147, "text": " Amit Diwan" }, { "code": null, "e": 3166, "s": 3159, "text": " Print" }, { "code": null, "e": 3177, "s": 3166, "text": " Add Notes" } ]
3D Maths - DirectX Math
The initialization process of Direct3D requires some specific Direct3D types and basic graphics concepts. This chapter addresses these requirements. Direct3D includes a design of low-level graphics API (Application Programming Interface) that enables us to render 3D worlds using 3D hardware acceleration. The most important thing is that Direct3D provides the software interfaces through which a user can use the graphics hardware. The best illustration is to instruct the graphics hardware to clear the render target. Now, let us focus on DirectXMath which is the primary focus of this chapter. DirectXMath is written with the help of standard Intel-style intrinsics, which is usually portable to all compilers. The ARM code paths use ARM-style intrinsics which is considered to be portable. The DirectXMath library makes use of two commonly implemented extensions to Standard C++ which are mentioned below − Anonymous structs, which are widely supported and are part of the C11 standard. Anonymous structs, which are widely supported and are part of the C11 standard. Anonymous unions, but these are part of the C++ and C99 standard. Anonymous unions, but these are part of the C++ and C99 standard. DirectXMath is an inline SIMD which includes all the linear algebra library features for use in games and graphics apps. The DirectXMath library includes inline features and uses only the concerned Visual C++ intrinsics. Hence, it is considered to be more compatible with all versions of Windows supported by Visual C++. There's no standard configuration which will put DirectXMath in the include path but a user can add it manually or make use of the NuGet package which is designed for that unique purpose. Keep in mind there are many differences which are completed with DirectX development for Windows XP support. The details on moving from XNAMath to DirectXMath are covered in Code Migration from the XNA Math Library. Make sure as a user you read all the details on the calling convention types which are designed to deal with the various architectures and vector calling conventions. If a user is writing client code that is intended to build with both DirectXMath 3.06+ (Windows 8.1 SDK / VS 2013) and DirectXMath 3.03 (Windows 8 XDK / VS 2012), the following adapter code can be used − #include <DirectXMath.h> namespace DirectX { #if (DIRECTX_MATH_VERSION < 305) && !defined(XM_CALLCONV) #define XM_CALLCONV __fastcall typedef const XMVECTOR& HXMVECTOR; typedef const XMMATRIX& FXMMATRIX; #endif } DirectXMath includes all the written intrinsic standards, which should be portable to other compilers. The ARM codepaths also include ARM-style intrinsics which should be considered portable. Print Add Notes Bookmark this page
[ { "code": null, "e": 2447, "s": 2298, "text": "The initialization process of Direct3D requires some specific Direct3D types and basic graphics concepts. This chapter addresses these requirements." }, { "code": null, "e": 2818, "s": 2447, "text": "Direct3D includes a design of low-level graphics API (Application Programming Interface) that enables us to render 3D worlds using 3D hardware acceleration. The most important thing is that Direct3D provides the software interfaces through which a user can use the graphics hardware. The best illustration is to instruct the graphics hardware to clear the render target." }, { "code": null, "e": 3092, "s": 2818, "text": "Now, let us focus on DirectXMath which is the primary focus of this chapter. DirectXMath is written with the help of standard Intel-style intrinsics, which is usually portable to all compilers. The ARM code paths use ARM-style intrinsics which is considered to be portable." }, { "code": null, "e": 3209, "s": 3092, "text": "The DirectXMath library makes use of two commonly implemented extensions to Standard C++ which are mentioned below −" }, { "code": null, "e": 3289, "s": 3209, "text": "Anonymous structs, which are widely supported and are part of the C11 standard." }, { "code": null, "e": 3369, "s": 3289, "text": "Anonymous structs, which are widely supported and are part of the C11 standard." }, { "code": null, "e": 3435, "s": 3369, "text": "Anonymous unions, but these are part of the C++ and C99 standard." }, { "code": null, "e": 3501, "s": 3435, "text": "Anonymous unions, but these are part of the C++ and C99 standard." }, { "code": null, "e": 3622, "s": 3501, "text": "DirectXMath is an inline SIMD which includes all the linear algebra library features for use in games and graphics apps." }, { "code": null, "e": 4119, "s": 3622, "text": "The DirectXMath library includes inline features and uses only the concerned Visual C++ intrinsics. Hence, it is considered to be more compatible with all versions of Windows supported by Visual C++. There's no standard configuration which will put DirectXMath in the include path but a user can add it manually or make use of the NuGet package which is designed for that unique purpose. Keep in mind there are many differences which are completed with DirectX development for Windows XP support." }, { "code": null, "e": 4226, "s": 4119, "text": "The details on moving from XNAMath to DirectXMath are covered in Code Migration from the XNA Math Library." }, { "code": null, "e": 4393, "s": 4226, "text": "Make sure as a user you read all the details on the calling convention types which are designed to deal with the various architectures and vector calling conventions." }, { "code": null, "e": 4597, "s": 4393, "text": "If a user is writing client code that is intended to build with both DirectXMath 3.06+ (Windows 8.1 SDK / VS 2013) and DirectXMath 3.03 (Windows 8 XDK / VS 2012), the following adapter code can be used −" }, { "code": null, "e": 4826, "s": 4597, "text": "#include <DirectXMath.h>\nnamespace DirectX {\n #if (DIRECTX_MATH_VERSION < 305) && !defined(XM_CALLCONV)\n #define XM_CALLCONV __fastcall\n typedef const XMVECTOR& HXMVECTOR;\n typedef const XMMATRIX& FXMMATRIX;\n #endif\n}\n" }, { "code": null, "e": 5018, "s": 4826, "text": "DirectXMath includes all the written intrinsic standards, which should be portable to other compilers. The ARM codepaths also include ARM-style intrinsics which should be considered portable." }, { "code": null, "e": 5025, "s": 5018, "text": " Print" }, { "code": null, "e": 5036, "s": 5025, "text": " Add Notes" } ]
How to add “graphics.h” C/C++ library to gcc compiler in Linux
In this tutorial, we will be discussing a program to understand how to add “graphics.h” C/C++ library to gcc compiler in Linux. To do this we are required to compile and install the libgraph package. This includes install build-essential and some external packages >>sudo apt-get install build-essential >>sudo apt-get install libsdl-image1.2 libsdl-image1.2-dev guile-2.0 guile-2.0-dev libsdl1.2debian libart-2.0-dev libaudiofile-dev libesd0-dev libdirectfb-dev libdirectfb-extra libfreetype6-dev libxext-dev x11proto-xext-dev libfreetype6 libaa1 libaa1-dev libslang2-dev libasound2 libasound2-dev Then setting the path in the extracted files >>sudo make install >>sudo cp /usr/local/lib/libgraph.* /usr/lib #include<stdio.h> #include<stdlib.h> #include<graphics.h> int main(){ int gd = DETECT, gm; initgraph(&gd, &gm, NULL); circle(40, 40, 30); delay(40000); closegraph(); return 0; }
[ { "code": null, "e": 1190, "s": 1062, "text": "In this tutorial, we will be discussing a program to understand how to add “graphics.h” C/C++ library to gcc compiler in Linux." }, { "code": null, "e": 1262, "s": 1190, "text": "To do this we are required to compile and install the libgraph package." }, { "code": null, "e": 1327, "s": 1262, "text": "This includes install build-essential and some external packages" }, { "code": null, "e": 1662, "s": 1327, "text": ">>sudo apt-get install build-essential\n\n>>sudo apt-get install libsdl-image1.2 libsdl-image1.2-dev guile-2.0 guile-2.0-dev\nlibsdl1.2debian libart-2.0-dev libaudiofile-dev libesd0-dev\nlibdirectfb-dev libdirectfb-extra libfreetype6-dev\nlibxext-dev x11proto-xext-dev libfreetype6 libaa1\nlibaa1-dev libslang2-dev libasound2 libasound2-dev" }, { "code": null, "e": 1707, "s": 1662, "text": "Then setting the path in the extracted files" }, { "code": null, "e": 1772, "s": 1707, "text": ">>sudo make install\n>>sudo cp /usr/local/lib/libgraph.* /usr/lib" }, { "code": null, "e": 1968, "s": 1772, "text": "#include<stdio.h>\n#include<stdlib.h>\n#include<graphics.h>\nint main(){\n int gd = DETECT, gm;\n initgraph(&gd, &gm, NULL);\n circle(40, 40, 30);\n delay(40000);\n closegraph();\n return 0;\n}" } ]
Python 3 - os.readlink() Method
The method readlink() returns a string representing the path to which the symbolic link points. It may return an absolute or relative pathname. Following is the syntax for readlink() method − os.readlink(path) path − This is the path or symblic link for which we are going to find source of the link. This method return a string representing the path to which the symbolic link points. The following example shows the usage of readlink() method. # !/usr/bin/python3 import os src = 'd://tmp//python3' dst = 'd://tmp//python2' # This creates a symbolic link on python in tmp directory os.symlink(src, dst) # Now let us use readlink to display the source of the link. path = os.readlink( dst ) print (path) Let us compile and run the above program, this will create a symblic link to d:\tmp\python3 and later it will read the source of the symbolic link using readlink() call. This is an example on Windows platform and needs administrator privilege to run. Before running this program make sure you do not have d:\tmp\python2 already available. d:\tmp\python2 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": 2484, "s": 2340, "text": "The method readlink() returns a string representing the path to which the symbolic link points. It may return an absolute or relative pathname." }, { "code": null, "e": 2532, "s": 2484, "text": "Following is the syntax for readlink() method −" }, { "code": null, "e": 2550, "s": 2532, "text": "os.readlink(path)" }, { "code": null, "e": 2641, "s": 2550, "text": "path − This is the path or symblic link for which we are going to find source of the link." }, { "code": null, "e": 2726, "s": 2641, "text": "This method return a string representing the path to which the symbolic link points." }, { "code": null, "e": 2786, "s": 2726, "text": "The following example shows the usage of readlink() method." }, { "code": null, "e": 3048, "s": 2786, "text": "# !/usr/bin/python3\nimport os\n\nsrc = 'd://tmp//python3'\ndst = 'd://tmp//python2'\n\n# This creates a symbolic link on python in tmp directory\nos.symlink(src, dst)\n\n# Now let us use readlink to display the source of the link.\npath = os.readlink( dst )\nprint (path)" }, { "code": null, "e": 3387, "s": 3048, "text": "Let us compile and run the above program, this will create a symblic link to d:\\tmp\\python3 and later it will read the source of the symbolic link using readlink() call. This is an example on Windows platform and needs administrator privilege to run. Before running this program make sure you do not have d:\\tmp\\python2 already available." }, { "code": null, "e": 3403, "s": 3387, "text": "d:\\tmp\\python2\n" }, { "code": null, "e": 3440, "s": 3403, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3456, "s": 3440, "text": " Malhar Lathkar" }, { "code": null, "e": 3489, "s": 3456, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3508, "s": 3489, "text": " Arnab Chakraborty" }, { "code": null, "e": 3543, "s": 3508, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3565, "s": 3543, "text": " In28Minutes Official" }, { "code": null, "e": 3599, "s": 3565, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3627, "s": 3599, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3662, "s": 3627, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3676, "s": 3662, "text": " Lets Kode It" }, { "code": null, "e": 3709, "s": 3676, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3726, "s": 3709, "text": " Abhilash Nelson" }, { "code": null, "e": 3733, "s": 3726, "text": " Print" }, { "code": null, "e": 3744, "s": 3733, "text": " Add Notes" } ]
How to decrement a value in MySQL keeping it above zero?
You can decrement value in MySQL with update command. With this, you can also restrict the value to not reach below 0. The syntax is as follows − update yourTableName set yourColumnName = yourColumnName - 1 where yourColumnName > 0; To avoid the value to go below zero, you can use yourColumnName > 0. To understand the above syntax, let us create a table. The query to create a table. mysql> create table DecrementDemo −> ( −> DecrementValue int −> ); Query OK, 0 rows affected (0.62 sec) Insert some records in the table with insert statement. The query is as follows − mysql> insert into DecrementDemo values(15),(14),(13),(12),(11),(10); Query OK, 6 rows affected (0.18 sec) Records: 6 Duplicates: 0 Warnings: 0 Now you can display all records from table with the help of select statement. The query is as follows − mysql> select *from DecrementDemo; The following is the output − +----------------+ | DecrementValue | +----------------+ | 15 | | 14 | | 13 | | 12 | | 11 | | 10 | +----------------+ 6 rows in set (0.00 sec) Here is the query to decrement value from a table − mysql> update DecrementDemo −> set DecrementValue = DecrementValue - 1 where DecrementValue > 0; Query OK, 6 rows affected (0.16 sec) Rows matched: 6 Changed: 6 Warnings: 0 Check whether the value decremented or not using the following query − mysql> select *from DecrementDemo; The following is the output − +----------------+ | DecrementValue | +----------------+ | 14 | | 13 | | 12 | | 11 | | 10 | | 9 | +----------------+ 6 rows in set (0.00 sec)
[ { "code": null, "e": 1181, "s": 1062, "text": "You can decrement value in MySQL with update command. With this, you can also restrict the value to not reach below 0." }, { "code": null, "e": 1208, "s": 1181, "text": "The syntax is as follows −" }, { "code": null, "e": 1295, "s": 1208, "text": "update yourTableName set yourColumnName = yourColumnName - 1 where yourColumnName > 0;" }, { "code": null, "e": 1364, "s": 1295, "text": "To avoid the value to go below zero, you can use yourColumnName > 0." }, { "code": null, "e": 1448, "s": 1364, "text": "To understand the above syntax, let us create a table. The query to create a table." }, { "code": null, "e": 1561, "s": 1448, "text": "mysql> create table DecrementDemo\n −> (\n −> DecrementValue int\n −> );\nQuery OK, 0 rows affected (0.62 sec)" }, { "code": null, "e": 1643, "s": 1561, "text": "Insert some records in the table with insert statement. The query is as follows −" }, { "code": null, "e": 1787, "s": 1643, "text": "mysql> insert into DecrementDemo values(15),(14),(13),(12),(11),(10);\nQuery OK, 6 rows affected (0.18 sec)\nRecords: 6 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 1891, "s": 1787, "text": "Now you can display all records from table with the help of select statement. The query is as follows −" }, { "code": null, "e": 1926, "s": 1891, "text": "mysql> select *from DecrementDemo;" }, { "code": null, "e": 1956, "s": 1926, "text": "The following is the output −" }, { "code": null, "e": 2171, "s": 1956, "text": "+----------------+\n| DecrementValue |\n+----------------+\n| 15 |\n| 14 |\n| 13 |\n| 12 |\n| 11 |\n| 10 |\n+----------------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 2223, "s": 2171, "text": "Here is the query to decrement value from a table −" }, { "code": null, "e": 2399, "s": 2223, "text": "mysql> update DecrementDemo\n −> set DecrementValue = DecrementValue - 1 where DecrementValue > 0;\nQuery OK, 6 rows affected (0.16 sec)\nRows matched: 6 Changed: 6 Warnings: 0" }, { "code": null, "e": 2470, "s": 2399, "text": "Check whether the value decremented or not using the following query −" }, { "code": null, "e": 2505, "s": 2470, "text": "mysql> select *from DecrementDemo;" }, { "code": null, "e": 2535, "s": 2505, "text": "The following is the output −" }, { "code": null, "e": 2750, "s": 2535, "text": "+----------------+\n| DecrementValue |\n+----------------+\n| 14 |\n| 13 |\n| 12 |\n| 11 |\n| 10 |\n| 9 |\n+----------------+\n6 rows in set (0.00 sec)" } ]
How to get specific nodes in xml file in Python?
Using the xml library you can get any node you want from the xml file. But for extracting a given node, you'd need to know how to use xpath to get it. You can learn more about XPath here:https://www.w3schools.com/xml/xml_xpath.asp. For example, assume you have a xml file with following structure, <bookstore> <book category="cooking"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> <book category="children"> <title lang="en">Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> </bookstore> And you want to extract all title nodes with lang attribute en, then you'd have the code − from xml.etree.ElementTree import ElementTree tree = ElementTree() root = tree.parse("my_file.xml") for node in root.findall("//title[@lang='en']"): for type in node.getchildren(): print(type.text)
[ { "code": null, "e": 1295, "s": 1062, "text": "Using the xml library you can get any node you want from the xml file. But for extracting a given node, you'd need to know how to use xpath to get it. You can learn more about XPath here:https://www.w3schools.com/xml/xml_xpath.asp. " }, { "code": null, "e": 1361, "s": 1295, "text": "For example, assume you have a xml file with following structure," }, { "code": null, "e": 1728, "s": 1361, "text": "<bookstore>\n <book category=\"cooking\">\n <title lang=\"en\">Everyday Italian</title>\n <author>Giada De Laurentiis</author>\n <year>2005</year>\n <price>30.00</price>\n </book>\n <book category=\"children\">\n <title lang=\"en\">Harry Potter</title>\n <author>J K. Rowling</author>\n <year>2005</year>\n <price>29.99</price>\n </book>\n</bookstore>" }, { "code": null, "e": 1819, "s": 1728, "text": "And you want to extract all title nodes with lang attribute en, then you'd have the code −" }, { "code": null, "e": 2029, "s": 1819, "text": "from xml.etree.ElementTree import ElementTree\ntree = ElementTree()\nroot = tree.parse(\"my_file.xml\")\nfor node in root.findall(\"//title[@lang='en']\"):\n for type in node.getchildren():\n print(type.text)" } ]
Java & MySQL - Streaming Data
A PreparedStatement object has the ability to use input and output streams to supply parameter data. This enables you to place entire files into database columns that can hold large values, such as CLOB and BLOB data types. There are following methods, which can be used to stream data − setAsciiStream() − This method is used to supply large ASCII values. setAsciiStream() − This method is used to supply large ASCII values. setCharacterStream() − This method is used to supply large UNICODE values. setCharacterStream() − This method is used to supply large UNICODE values. setBinaryStream() − This method is used to supply large binary values. setBinaryStream() − This method is used to supply large binary values. The setXXXStream() method requires an extra parameter, the file size, besides the parameter placeholder. This parameter informs the driver how much data should be sent to the database using the stream. This example would create a database table XML_Data and then XML content would be written into this table. Copy and paste the following example in TestApplication.java, compile and run as follows − import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class TestApplication { static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT"; static final String USER = "guest"; static final String PASS = "guest123"; static final String QUERY = "SELECT Data FROM XML_Data WHERE id=100"; static final String INSERT_QUERY="INSERT INTO XML_Data VALUES (?,?)"; static final String CREATE_TABLE_QUERY = "CREATE TABLE XML_Data (id INTEGER, Data LONG)"; static final String DROP_TABLE_QUERY = "DROP TABLE XML_Data"; static final String XML_DATA = "<Employee><id>100</id><first>Zara</first><last>Ali</last><Salary>10000</Salary><Dob>18-08-1978</Dob></Employee>"; public static void createXMLTable(Statement stmt) throws SQLException{ System.out.println("Creating XML_Data table..." ); //Drop table first if it exists. try{ stmt.executeUpdate(DROP_TABLE_QUERY); }catch(SQLException se){ } stmt.executeUpdate(CREATE_TABLE_QUERY); } public static void main(String[] args) { // Open a connection try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); Statement stmt = conn.createStatement(); PreparedStatement pstmt = conn.prepareStatement(INSERT_QUERY); ) { createXMLTable(stmt); ByteArrayInputStream bis = new ByteArrayInputStream(XML_DATA.getBytes()); pstmt.setInt(1,100); pstmt.setAsciiStream(2,bis,XML_DATA.getBytes().length); pstmt.execute(); //Close input stream bis.close(); ResultSet rs = stmt.executeQuery(QUERY); // Get the first row if (rs.next ()){ //Retrieve data from input stream InputStream xmlInputStream = rs.getAsciiStream (1); int c; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while (( c = xmlInputStream.read ()) != -1) bos.write(c); //Print results System.out.println(bos.toString()); } // Clean-up environment rs.close(); } catch (SQLException | IOException e) { e.printStackTrace(); } } } Now let us compile the above example as follows − C:\>javac TestApplication.java C:\> When you run TestApplication, it produces the following result − C:\>java TestApplication Creating XML_Data table... <Employee><id>100</id><first>Zara</first><last>Ali</last><Salary>10000</Salary><Dob>18-08-1978</Dob></Employee> C:\> 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": 2910, "s": 2686, "text": "A PreparedStatement object has the ability to use input and output streams to supply parameter data. This enables you to place entire files into database columns that can\nhold large values, such as CLOB and BLOB data types." }, { "code": null, "e": 2976, "s": 2910, "text": "There are following methods, which can be used to stream data −" }, { "code": null, "e": 3045, "s": 2976, "text": "setAsciiStream() − This method is used to supply large ASCII values." }, { "code": null, "e": 3114, "s": 3045, "text": "setAsciiStream() − This method is used to supply large ASCII values." }, { "code": null, "e": 3189, "s": 3114, "text": "setCharacterStream() − This method is used to supply large UNICODE values." }, { "code": null, "e": 3264, "s": 3189, "text": "setCharacterStream() − This method is used to supply large UNICODE values." }, { "code": null, "e": 3335, "s": 3264, "text": "setBinaryStream() − This method is used to supply large binary values." }, { "code": null, "e": 3406, "s": 3335, "text": "setBinaryStream() − This method is used to supply large binary values." }, { "code": null, "e": 3608, "s": 3406, "text": "The setXXXStream() method requires an extra parameter, the file size, besides the parameter placeholder. This parameter informs the driver how much data should be sent to the database using the stream." }, { "code": null, "e": 3715, "s": 3608, "text": "This example would create a database table XML_Data and then XML content would be written into this table." }, { "code": null, "e": 3806, "s": 3715, "text": "Copy and paste the following example in TestApplication.java, compile and run as follows −" }, { "code": null, "e": 6378, "s": 3806, "text": "import java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\npublic class TestApplication {\n static final String DB_URL = \"jdbc:mysql://localhost/TUTORIALSPOINT\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n static final String QUERY = \"SELECT Data FROM XML_Data WHERE id=100\";\n static final String INSERT_QUERY=\"INSERT INTO XML_Data VALUES (?,?)\";\n static final String CREATE_TABLE_QUERY = \"CREATE TABLE XML_Data (id INTEGER, Data LONG)\";\n static final String DROP_TABLE_QUERY = \"DROP TABLE XML_Data\";\n static final String XML_DATA = \"<Employee><id>100</id><first>Zara</first><last>Ali</last><Salary>10000</Salary><Dob>18-08-1978</Dob></Employee>\";\n \n public static void createXMLTable(Statement stmt) \n throws SQLException{\n System.out.println(\"Creating XML_Data table...\" );\n //Drop table first if it exists.\n try{\n stmt.executeUpdate(DROP_TABLE_QUERY);\n }catch(SQLException se){\n }\n stmt.executeUpdate(CREATE_TABLE_QUERY);\n }\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n Statement stmt = conn.createStatement();\n PreparedStatement pstmt = conn.prepareStatement(INSERT_QUERY);\n ) {\t\t \n createXMLTable(stmt);\n\n ByteArrayInputStream bis = new ByteArrayInputStream(XML_DATA.getBytes());\n\n pstmt.setInt(1,100);\n pstmt.setAsciiStream(2,bis,XML_DATA.getBytes().length);\n pstmt.execute();\n\n //Close input stream\n bis.close();\n\n ResultSet rs = stmt.executeQuery(QUERY);\n // Get the first row\n if (rs.next ()){\n //Retrieve data from input stream\n InputStream xmlInputStream = rs.getAsciiStream (1);\n int c;\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\n while (( c = xmlInputStream.read ()) != -1)\n bos.write(c);\n //Print results\n System.out.println(bos.toString());\n }\n // Clean-up environment\n rs.close();\n\n } catch (SQLException | IOException e) {\n e.printStackTrace();\n } \n }\n}" }, { "code": null, "e": 6428, "s": 6378, "text": "Now let us compile the above example as follows −" }, { "code": null, "e": 6465, "s": 6428, "text": "C:\\>javac TestApplication.java\nC:\\>\n" }, { "code": null, "e": 6530, "s": 6465, "text": "When you run TestApplication, it produces the following result −" }, { "code": null, "e": 6700, "s": 6530, "text": "C:\\>java TestApplication\nCreating XML_Data table...\n<Employee><id>100</id><first>Zara</first><last>Ali</last><Salary>10000</Salary><Dob>18-08-1978</Dob></Employee>\nC:\\>\n" }, { "code": null, "e": 6733, "s": 6700, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 6749, "s": 6733, "text": " Malhar Lathkar" }, { "code": null, "e": 6782, "s": 6749, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 6798, "s": 6782, "text": " Malhar Lathkar" }, { "code": null, "e": 6833, "s": 6798, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6847, "s": 6833, "text": " Anadi Sharma" }, { "code": null, "e": 6881, "s": 6847, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 6895, "s": 6881, "text": " Tushar Kale" }, { "code": null, "e": 6932, "s": 6895, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 6947, "s": 6932, "text": " Monica Mittal" }, { "code": null, "e": 6980, "s": 6947, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 6999, "s": 6980, "text": " Arnab Chakraborty" }, { "code": null, "e": 7006, "s": 6999, "text": " Print" }, { "code": null, "e": 7017, "s": 7006, "text": " Add Notes" } ]
Reverse array in groups | Practice | GeeksforGeeks
Given an array arr[] of positive integers of size N. Reverse every sub-array group of size K. Example 1: Input: N = 5, K = 3 arr[] = {1,2,3,4,5} Output: 3 2 1 5 4 Explanation: First group consists of elements 1, 2, 3. Second group consists of 4,5. Example 2: Input: N = 4, K = 3 arr[] = {5,6,8,9} Output: 8 6 5 9 Your Task: You don't need to read input or print anything. The task is to complete the function reverseInGroups() which takes the array, N and K as input parameters and modifies the array in-place. Expected Time Complexity: O(N) Expected Auxiliary Space: O(N) Constraints: 1 ≤ N, K ≤ 107 1 ≤ A[i] ≤ 1018 +2 moryasivam2 days ago void reverseInGroups(vector<long long>& arr, int n, int k){ int i=0; while(i<n){ if(i+k<n){ reverse(arr.begin()+i,arr.begin()+i+k); } else{ reverse(arr.begin()+i,arr.end()); } i+=k; } } 0 kushwaharajshree233 days ago C++ solution → void reverseInGroups(vector<long long>& arr, int n, int k){ for(int i=0;i<n;i+=k) { int l=i; int r=min(i+k-1, n-1); while(l<r) { int temp= arr[l]; arr[l]=arr[r]; arr[r]= temp; l++; r--; } } } +1 iit20212054 days ago class Solution{public: //Function to reverse every sub-array group of size k. void reverseInGroups(vector<long long>& arr, int n, int k){ int p=n/k; int l=n%k; for(int i=0;i<n-l;i=i+k){ reverse(arr.begin()+i,arr.begin()+i+k); } reverse(arr.end()-l,arr.end()); }};//easiest approach to an easy problem 0 harshscode5 days ago most simple amongest all for(int i=0;i<n;i=i+k) { int l=i; int r=min(n-1,i+k-1); while(l<r) { int t=a[l]; a[l]=a[r]; a[r]=t; l++; r--; } } 0 choudharyshraddha125 days ago class Solution{public: //Function to reverse every sub-array group of size k. void reverseInGroups(vector<long long>& arr, int n, int k){ int k1=0; int perfectgroupsformed=n/k; for(int i=0;i<perfectgroupsformed;i++) { reverse(arr.begin()+(i*k),arr.begin()+(k+k1)); k1+=k; } reverse(arr.begin()+(perfectgroupsformed*k),arr.begin()+n); }}; 0 kerim26 days ago Javascript reverse(arr,n, l, r){ while(l<r){ [arr[l],arr[r]] = [arr[r],arr[l]]; l++, r--; } } reverseInGroups(arr, n, k){ for(let i = 0; i < n; i+=k){ if(i+k < n) this.reverse(arr,n,i,i+k-1); else this.reverse(arr,n,i,n-1); } } 0 kerim2 This comment was deleted. +2 deeplakhotia8761 week ago void reverseInGroups(vector<long long>& arr, int n, int k){ int i=0; while(i<n){ if(i+k<n){ reverse(arr.begin()+i,arr.begin()+i+k); } else{ reverse(arr.begin()+i,arr.end()); } i+=k; } } 0 hharshit81181 week ago Time Complexity = O(nk); Space : O(k) void reverseInGroups(vector<long long>& arr, int n, int k){ stack<long long> s; for(int i=0; i<n; ){ for(int j = 0, l = i; j<k && l<n; j++, l++){ s.push(arr[l]); } while(s.empty() == false){ arr[i] = s.top(); s.pop(); i++; } } } 0 tannupriya18991 week ago //Time Complexity=O(n*n/k) int start=0; int end=k-1; int start1=0; int end1=k-1; int cnt=0; while(start1<n && end1<n) { while(start<=end) swap(arr[start++],arr[end--]); start1+=k; end1+=k; start=start1; end=end1; cnt++; } start=cnt*k; end=n-1; while(start<=end) swap(arr[start++],arr[end--]); We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 332, "s": 238, "text": "Given an array arr[] of positive integers of size N. Reverse every sub-array group of size K." }, { "code": null, "e": 345, "s": 334, "text": "Example 1:" }, { "code": null, "e": 488, "s": 345, "text": "Input:\nN = 5, K = 3\narr[] = {1,2,3,4,5}\nOutput: 3 2 1 5 4\nExplanation: First group consists of elements\n1, 2, 3. Second group consists of 4,5." }, { "code": null, "e": 501, "s": 490, "text": "Example 2:" }, { "code": null, "e": 556, "s": 501, "text": "Input:\nN = 4, K = 3\narr[] = {5,6,8,9}\nOutput: 8 6 5 9\n" }, { "code": null, "e": 757, "s": 558, "text": "Your Task:\nYou don't need to read input or print anything. The task is to complete the function reverseInGroups() which takes the array, N and K as input parameters and modifies the array in-place. " }, { "code": null, "e": 821, "s": 759, "text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 867, "s": 823, "text": "Constraints:\n1 ≤ N, K ≤ 107\n1 ≤ A[i] ≤ 1018" }, { "code": null, "e": 870, "s": 867, "text": "+2" }, { "code": null, "e": 891, "s": 870, "text": "moryasivam2 days ago" }, { "code": null, "e": 1156, "s": 891, "text": " void reverseInGroups(vector<long long>& arr, int n, int k){ int i=0; while(i<n){ if(i+k<n){ reverse(arr.begin()+i,arr.begin()+i+k); } else{ reverse(arr.begin()+i,arr.end()); } i+=k; } }" }, { "code": null, "e": 1160, "s": 1158, "text": "0" }, { "code": null, "e": 1189, "s": 1160, "text": "kushwaharajshree233 days ago" }, { "code": null, "e": 1204, "s": 1189, "text": "C++ solution →" }, { "code": null, "e": 1577, "s": 1204, "text": "void reverseInGroups(vector<long long>& arr, int n, int k){\n for(int i=0;i<n;i+=k)\n {\n int l=i;\n int r=min(i+k-1, n-1);\n while(l<r)\n {\n int temp= arr[l];\n arr[l]=arr[r];\n arr[r]= temp;\n l++;\n r--;\n }\n \n }\n }" }, { "code": null, "e": 1580, "s": 1577, "text": "+1" }, { "code": null, "e": 1601, "s": 1580, "text": "iit20212054 days ago" }, { "code": null, "e": 1948, "s": 1601, "text": "class Solution{public: //Function to reverse every sub-array group of size k. void reverseInGroups(vector<long long>& arr, int n, int k){ int p=n/k; int l=n%k; for(int i=0;i<n-l;i=i+k){ reverse(arr.begin()+i,arr.begin()+i+k); } reverse(arr.end()-l,arr.end()); }};//easiest approach to an easy problem" }, { "code": null, "e": 1950, "s": 1948, "text": "0" }, { "code": null, "e": 1971, "s": 1950, "text": "harshscode5 days ago" }, { "code": null, "e": 1996, "s": 1971, "text": "most simple amongest all" }, { "code": null, "e": 2199, "s": 1996, "text": " for(int i=0;i<n;i=i+k) { int l=i; int r=min(n-1,i+k-1); while(l<r) { int t=a[l]; a[l]=a[r]; a[r]=t; l++; r--; } }" }, { "code": null, "e": 2201, "s": 2199, "text": "0" }, { "code": null, "e": 2231, "s": 2201, "text": "choudharyshraddha125 days ago" }, { "code": null, "e": 2631, "s": 2231, "text": "class Solution{public: //Function to reverse every sub-array group of size k. void reverseInGroups(vector<long long>& arr, int n, int k){ int k1=0; int perfectgroupsformed=n/k; for(int i=0;i<perfectgroupsformed;i++) { reverse(arr.begin()+(i*k),arr.begin()+(k+k1)); k1+=k; } reverse(arr.begin()+(perfectgroupsformed*k),arr.begin()+n); }};" }, { "code": null, "e": 2633, "s": 2631, "text": "0" }, { "code": null, "e": 2650, "s": 2633, "text": "kerim26 days ago" }, { "code": null, "e": 2661, "s": 2650, "text": "Javascript" }, { "code": null, "e": 2912, "s": 2663, "text": "reverse(arr,n, l, r){\n while(l<r){\n [arr[l],arr[r]] = [arr[r],arr[l]];\n l++, r--;\n }\n}\n \nreverseInGroups(arr, n, k){\n for(let i = 0; i < n; i+=k){\n if(i+k < n) this.reverse(arr,n,i,i+k-1);\n else this.reverse(arr,n,i,n-1);\n }\n}" }, { "code": null, "e": 2914, "s": 2912, "text": "0" }, { "code": null, "e": 2921, "s": 2914, "text": "kerim2" }, { "code": null, "e": 2947, "s": 2921, "text": "This comment was deleted." }, { "code": null, "e": 2950, "s": 2947, "text": "+2" }, { "code": null, "e": 2976, "s": 2950, "text": "deeplakhotia8761 week ago" }, { "code": null, "e": 3260, "s": 2976, "text": "void reverseInGroups(vector<long long>& arr, int n, int k){ int i=0; while(i<n){ if(i+k<n){ reverse(arr.begin()+i,arr.begin()+i+k); } else{ reverse(arr.begin()+i,arr.end()); } i+=k; } }" }, { "code": null, "e": 3262, "s": 3260, "text": "0" }, { "code": null, "e": 3285, "s": 3262, "text": "hharshit81181 week ago" }, { "code": null, "e": 3310, "s": 3285, "text": "Time Complexity = O(nk);" }, { "code": null, "e": 3324, "s": 3310, "text": "Space : O(k) " }, { "code": null, "e": 3671, "s": 3324, "text": " void reverseInGroups(vector<long long>& arr, int n, int k){ stack<long long> s; for(int i=0; i<n; ){ for(int j = 0, l = i; j<k && l<n; j++, l++){ s.push(arr[l]); } while(s.empty() == false){ arr[i] = s.top(); s.pop(); i++; } } }" }, { "code": null, "e": 3673, "s": 3671, "text": "0" }, { "code": null, "e": 3698, "s": 3673, "text": "tannupriya18991 week ago" }, { "code": null, "e": 3725, "s": 3698, "text": "//Time Complexity=O(n*n/k)" }, { "code": null, "e": 4135, "s": 3725, "text": "int start=0; int end=k-1; int start1=0; int end1=k-1; int cnt=0; while(start1<n && end1<n) { while(start<=end) swap(arr[start++],arr[end--]); start1+=k; end1+=k; start=start1; end=end1; cnt++; } start=cnt*k; end=n-1; while(start<=end) swap(arr[start++],arr[end--]);" }, { "code": null, "e": 4281, "s": 4135, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 4317, "s": 4281, "text": " Login to access your submissions. " }, { "code": null, "e": 4327, "s": 4317, "text": "\nProblem\n" }, { "code": null, "e": 4337, "s": 4327, "text": "\nContest\n" }, { "code": null, "e": 4400, "s": 4337, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4548, "s": 4400, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 4756, "s": 4548, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 4862, "s": 4756, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Integration of Hadoop and R Programming Language
28 Dec, 2021 Hadoop is an open-source framework that was introduced by the ASF — Apache Software Foundation. Hadoop is the most crucial framework for copying with Big Data. Hadoop has been written in Java, and it is not based on OLAP (Online Analytical Processing). The best part of this big data framework is that it is scalable and can be deployed for any type of data in various varieties like the structured, unstructured, and semi-structured type. Hadoop is a middleware tool that provides us with a platform that manages a large and complex cluster of computers that was developed in Java and although Java is the main programming language for Hadoop other languages could be used to- R, Python, or Ruby. The Hadoop framework includes : Hadoop Distributed File System (HDFS) – It is a file system that provides a robust distributed file system. Hadoop has a framework that is used for job scheduling and cluster resource management whose name is YARN. Hadoop MapReduce –It is a system for parallel processing of large data sets that implement the MapReduce model of distributed programming. Hadoop extends an easier distributed storage with the help of HDFS and provides an analysis system through MapReduce. It has a well-designed architecture to scale up or scale down the servers as per the requirements of the user from one to hundreds or thousands of computers, having a high degree of fault tolerance. Hadoop has proved its infallible need and standards in big data processing and efficient storage management, it provides unlimited scalability and is supported by major vendors in the software industry. As we know that data is the precious thing that matters most for an organization and it’ll be not an exaggeration if we say data is the most valuable asset. But in order to deal with this huge structure and unstructured we need an effective tool that could effectively do the data analysis, so we get this tool by merging the features of both R language and Hadoop framework of big data analysis, this merging result increment in its scalability. Hence, we need to integrate both then only we can find better insights and result from data. Soon we’ll go through the various methodologies which help to integrate these two. R is an open-source programming language that is extensively used for statistical and graphical analysis. R supports a large variety of Statistical-Mathematical based library for(linear and nonlinear modeling, classical-statistical tests, time-series analysis, data classification, data clustering, etc) and graphical techniques for processing data efficiently. One major quality of R’s is that it produces well-designed quality plots with greater ease, including mathematical symbols and formulae where needed. If you are in a crisis of strong data-analytics and visualization features then combining this R language with Hadoop into your task will be the last choice for you to reduce the complexity. It is a highly extensible object-oriented programming language and it has strong graphical capabilities. Some reasons for which R is considered the best fit for data analytics : A robust collection of packages Powerful data visualization techniques Commendable Statistical and graphical programming features Object-oriented programming language It has a wide smart collection of operators for calculations of arrays, particular matrices, etc Graphical representation capability on display or on hard copy. No suspicion, that R is the most picked programming language for statistical computing, graphical analysis of data, data analytics, and data visualization. On the other hand, Hadoop is a powerful Bigdata framework that is capable to deal with a large amount of data. In all the processing and analysis of data the distributed file system(HDFS) of Hadoop plays a vital role, It applies the map-reduce processing approach during data processing(provides by rmr package of R Hadoop), Which make the data analyzing process more efficient and easier. What would happen, if both collaborated with each other? Obviously, the efficiency of the data management and analyzing process will get increase multiple times. So, in order to have efficiency in the process of data analytics and visualization process, we have to combine R with Hadoop. After joining these two technologies, R’s statistical computing power becomes increases, then we enable to : Use Hadoop for the execution of the R codes. Use R for accessing the data stored in Hadoop. The most popular and frequently picked methods are shown below but there are some other RODBC/RJDBC that could be used but are not popular as the below methods are. The general architecture of the analytics tools integrated with Hadoop is shown below along with its different layered structure as follows. The first layer: It is the hardware layer — it consists of a cluster of computers systems, The second layer: It is the middleware layer of Hadoop. This layer also takes care of the distributions of the files flawlessly through using HDFS and the features of the MapReduce job. The third layer: It is the interface layer that provides the interface for analysis of data. At this level, we can use an effective tool like Pig which provides a high-level platform to us for creating MapReduce programs using a language which we called Pig-Latin. We can also use Hive which is a data warehouse infrastructure developed by Apache and built on top of Hadoop. Hive provides a number of facilities to us for running complex queries and helps to analyze the data using an SQL-like language called HiveQL and it also extends support for implementing MapReduce tasks. Besides using Hive and Pig, We can also use Rhipe or Rhadoop libraries that build an interface to provide integration between Hadoop and R and enables users to access data from the Hadoop file system and enable to write his own script to implement the Map and Reduce jobs, or we can also use the Hadoop- streaming that is a technology which is used to integrate the Hadoop. a) R Hadoop: R Hadoop method includes four packages, which are as follows: The rmr package –rmr package provides Hadoop MapReduce functionality in R. So, the R programmer only has to do just divide the logic and idea of their application into the map and reduce phases associates and just submit it with the rmr methods. After that, The rmr package makes a call to the Hadoop streaming and the MapReduce API through multiple job parameters as input directory, output directory, reducer, mapper, and so on, to perform the R MapReduce job over Hadoop cluster(most of the components are similar as Hadoop streaming). The rhbase package –Allows R developer to connect Hadoop HBASE to R using Thrift Server. It also offers functionality like (read, write, and modify tables stored in HBase from R). A script that utilizes the RHаdoop functionality looks like the figure shown below as follows. R library(rmr)map<-function(k,v){...}reduce<-function(k,vv){...}mapreduce(input = "data.txt",output ="output",textinputformat = rawtextinputformat,map = map,reduce = reduce) The rhdfs package –It provides HDFS file management in R, because data itself stores in Hadoop file system. Functions of this package are as given as follows. File Manipulations -( hdfs.delete, hdfs.rm, hdfs.del, hdfs.chown, hdfs.put, hdfs.get etc), File Read/Write -(hdfs.flush, hdfs.read, hdfs.seek, hdfs.tell, hdfs.line.reader etc), Directory -hdfs.dircreate, hdfs.mkdir, Initialization: hdfs.init, hdfs.defaults. The plyrmr package –It provides functionality likes data manipulation, summaries of the output result, performing set operations(union, intersection, subtraction, merge, unique). b) RHIPE: Rhipe is used in R to do an intricate analysis of the large collection of data sets via Hadoop is an integrated programming environment tool that is brought by the Divide and Recombine (D & R) to analyze the huge amount of data. RHIPE = R and Hadoop Integrated Programming Environment RHIPE is a package of R that enables the use of API in Hadoop. Thus, this way we can read, save the complete data that is created using RHIPE MapReduce. RHIPE is deployed with many features that help us to effectively interact with HDFS. An individual can also use various languages like Perl, Java, or Python to read data sets in RHIPE. The general structure of the R script that uses Rhipe is shown below as follows. R library(Rhipe) rhint(TRUE, TRUE);map < -expression({lapply(map.values, function(mapper)...)})reduce < -expression(pre={...},reduce={...},post={...}, }x < - rhmr(map=map, reduce=reduce,ifolder=inputPath,ofolder=outputPath,inout=c('text', 'text'),jobname='a job name'))rhex(z) Rhipe allows the R user to create MapReduce jobs(rmr package also helps to do this job) that work entirely within the R environment using R expressions. This MapReduce functionality: allows an analyst to quickly specify Maps and Reduces using the full power, flexibility, and expressiveness of the R interpreted language. c) Oracle R Connector for Hadoop (ORCH) : Orch is a collection of R packages that provide the following features. Various attractive Interfaces to work with the data maintained in Hive tables, able to use the Apache Hadoop based computing infrastructure, and also provides the local R environment and Oracle database tables.Us a predictive analytic technique, written in R or Java as Hadoop MapReduce jobs, that can be applied to data stored in HDFS files Various attractive Interfaces to work with the data maintained in Hive tables, able to use the Apache Hadoop based computing infrastructure, and also provides the local R environment and Oracle database tables. Us a predictive analytic technique, written in R or Java as Hadoop MapReduce jobs, that can be applied to data stored in HDFS files After installing this package in R you’ll become able to do the various functions as follows. Able to make the easier access and transform HDFS data using a Hive-enabled transparency layer for general use, We enable to use the R language for writing mappers and reducers effectively, Copying of data between the R memory to the local file system, to the HDFS, to the Hive, and to the Oracle databases, Able to Schedule the R programs easily in order to execute the program as Hadoop MapReduce jobs and return the results to any of those corresponding locations etc. Oracle R Connector for Hadoop enables access from a local client of R to Apache Hadoop using the following function prefixes: Hadoop –Identifies functions that provide an interface to Hadoop MapReduce. hdfs –Identifies functions that provide an interface to HDFS. Orch –Identifies a variety of functions; orch is a general prefix for ORCH functions. Ore –Identifies functions that provide an interface to a Hive data store. d) Hadoop Streaming: Hadoop streaming is a Hadoop utility for running the Hadoop MapReduce job with executable scripts such as Mapper and Reducer. The script is available as part of the R package on CRAN. And its aim is to make R more accessible to the Hadoop streaming-based applications. This is just congruent to the pipe operation in Linux. With this, the text input file is printed on stream (stdin), which is provided as an input to Mapper, and the output (stdout) of Mapper is provided as an input to the Reducer; finally, Reducer writes the output to the HDFS directory. А command line with mаp аnd reduce tasks implemented аs R scripts would look like the following. R $ ${HADOOP_HOME}/bin/Hadoop jar$ {HADOOP_HOME}/contrib/streaming/*.jar\-inputformat org.apache.hadoop.mapred.TextInputFormat \-input input_data.txt \-output output \-mapper /home/tst/src/map.R \-reducer /home/tst/src/reduce.R \-file /home/ts/src/map.R \-file /home/tst/src/reduce.R The main benefit of the Hadoop streaming is to allow the execution of the Java, as well as non-Java based programmed MapReduce jobs over Hadoop clusters. The Hadoop streaming supports various languages like Perl, Python, PHP, R, and C++, and other programming languages efficiently. Various components of the Hadoop streaming MapReduce job. gabaa406 kumar_satyam Hadoop R Language Hadoop Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Dec, 2021" }, { "code": null, "e": 728, "s": 28, "text": "Hadoop is an open-source framework that was introduced by the ASF — Apache Software Foundation. Hadoop is the most crucial framework for copying with Big Data. Hadoop has been written in Java, and it is not based on OLAP (Online Analytical Processing). The best part of this big data framework is that it is scalable and can be deployed for any type of data in various varieties like the structured, unstructured, and semi-structured type. Hadoop is a middleware tool that provides us with a platform that manages a large and complex cluster of computers that was developed in Java and although Java is the main programming language for Hadoop other languages could be used to- R, Python, or Ruby. " }, { "code": null, "e": 760, "s": 728, "text": "The Hadoop framework includes :" }, { "code": null, "e": 975, "s": 760, "text": "Hadoop Distributed File System (HDFS) – It is a file system that provides a robust distributed file system. Hadoop has a framework that is used for job scheduling and cluster resource management whose name is YARN." }, { "code": null, "e": 1114, "s": 975, "text": "Hadoop MapReduce –It is a system for parallel processing of large data sets that implement the MapReduce model of distributed programming." }, { "code": null, "e": 1635, "s": 1114, "text": "Hadoop extends an easier distributed storage with the help of HDFS and provides an analysis system through MapReduce. It has a well-designed architecture to scale up or scale down the servers as per the requirements of the user from one to hundreds or thousands of computers, having a high degree of fault tolerance. Hadoop has proved its infallible need and standards in big data processing and efficient storage management, it provides unlimited scalability and is supported by major vendors in the software industry. " }, { "code": null, "e": 2258, "s": 1635, "text": "As we know that data is the precious thing that matters most for an organization and it’ll be not an exaggeration if we say data is the most valuable asset. But in order to deal with this huge structure and unstructured we need an effective tool that could effectively do the data analysis, so we get this tool by merging the features of both R language and Hadoop framework of big data analysis, this merging result increment in its scalability. Hence, we need to integrate both then only we can find better insights and result from data. Soon we’ll go through the various methodologies which help to integrate these two." }, { "code": null, "e": 2621, "s": 2258, "text": "R is an open-source programming language that is extensively used for statistical and graphical analysis. R supports a large variety of Statistical-Mathematical based library for(linear and nonlinear modeling, classical-statistical tests, time-series analysis, data classification, data clustering, etc) and graphical techniques for processing data efficiently. " }, { "code": null, "e": 3068, "s": 2621, "text": "One major quality of R’s is that it produces well-designed quality plots with greater ease, including mathematical symbols and formulae where needed. If you are in a crisis of strong data-analytics and visualization features then combining this R language with Hadoop into your task will be the last choice for you to reduce the complexity. It is a highly extensible object-oriented programming language and it has strong graphical capabilities. " }, { "code": null, "e": 3141, "s": 3068, "text": "Some reasons for which R is considered the best fit for data analytics :" }, { "code": null, "e": 3173, "s": 3141, "text": "A robust collection of packages" }, { "code": null, "e": 3212, "s": 3173, "text": "Powerful data visualization techniques" }, { "code": null, "e": 3271, "s": 3212, "text": "Commendable Statistical and graphical programming features" }, { "code": null, "e": 3308, "s": 3271, "text": "Object-oriented programming language" }, { "code": null, "e": 3405, "s": 3308, "text": "It has a wide smart collection of operators for calculations of arrays, particular matrices, etc" }, { "code": null, "e": 3469, "s": 3405, "text": "Graphical representation capability on display or on hard copy." }, { "code": null, "e": 4015, "s": 3469, "text": "No suspicion, that R is the most picked programming language for statistical computing, graphical analysis of data, data analytics, and data visualization. On the other hand, Hadoop is a powerful Bigdata framework that is capable to deal with a large amount of data. In all the processing and analysis of data the distributed file system(HDFS) of Hadoop plays a vital role, It applies the map-reduce processing approach during data processing(provides by rmr package of R Hadoop), Which make the data analyzing process more efficient and easier." }, { "code": null, "e": 4303, "s": 4015, "text": "What would happen, if both collaborated with each other? Obviously, the efficiency of the data management and analyzing process will get increase multiple times. So, in order to have efficiency in the process of data analytics and visualization process, we have to combine R with Hadoop." }, { "code": null, "e": 4412, "s": 4303, "text": "After joining these two technologies, R’s statistical computing power becomes increases, then we enable to :" }, { "code": null, "e": 4457, "s": 4412, "text": "Use Hadoop for the execution of the R codes." }, { "code": null, "e": 4504, "s": 4457, "text": "Use R for accessing the data stored in Hadoop." }, { "code": null, "e": 4811, "s": 4504, "text": "The most popular and frequently picked methods are shown below but there are some other RODBC/RJDBC that could be used but are not popular as the below methods are. The general architecture of the analytics tools integrated with Hadoop is shown below along with its different layered structure as follows." }, { "code": null, "e": 4903, "s": 4811, "text": "The first layer: It is the hardware layer — it consists of a cluster of computers systems, " }, { "code": null, "e": 5090, "s": 4903, "text": "The second layer: It is the middleware layer of Hadoop. This layer also takes care of the distributions of the files flawlessly through using HDFS and the features of the MapReduce job. " }, { "code": null, "e": 5671, "s": 5090, "text": "The third layer: It is the interface layer that provides the interface for analysis of data. At this level, we can use an effective tool like Pig which provides a high-level platform to us for creating MapReduce programs using a language which we called Pig-Latin. We can also use Hive which is a data warehouse infrastructure developed by Apache and built on top of Hadoop. Hive provides a number of facilities to us for running complex queries and helps to analyze the data using an SQL-like language called HiveQL and it also extends support for implementing MapReduce tasks. " }, { "code": null, "e": 6045, "s": 5671, "text": "Besides using Hive and Pig, We can also use Rhipe or Rhadoop libraries that build an interface to provide integration between Hadoop and R and enables users to access data from the Hadoop file system and enable to write his own script to implement the Map and Reduce jobs, or we can also use the Hadoop- streaming that is a technology which is used to integrate the Hadoop." }, { "code": null, "e": 6120, "s": 6045, "text": "a) R Hadoop: R Hadoop method includes four packages, which are as follows:" }, { "code": null, "e": 6659, "s": 6120, "text": "The rmr package –rmr package provides Hadoop MapReduce functionality in R. So, the R programmer only has to do just divide the logic and idea of their application into the map and reduce phases associates and just submit it with the rmr methods. After that, The rmr package makes a call to the Hadoop streaming and the MapReduce API through multiple job parameters as input directory, output directory, reducer, mapper, and so on, to perform the R MapReduce job over Hadoop cluster(most of the components are similar as Hadoop streaming)." }, { "code": null, "e": 6839, "s": 6659, "text": "The rhbase package –Allows R developer to connect Hadoop HBASE to R using Thrift Server. It also offers functionality like (read, write, and modify tables stored in HBase from R)." }, { "code": null, "e": 6935, "s": 6839, "text": " A script that utilizes the RHаdoop functionality looks like the figure shown below as follows." }, { "code": null, "e": 6937, "s": 6935, "text": "R" }, { "code": "library(rmr)map<-function(k,v){...}reduce<-function(k,vv){...}mapreduce(input = \"data.txt\",output =\"output\",textinputformat = rawtextinputformat,map = map,reduce = reduce)", "e": 7109, "s": 6937, "text": null }, { "code": null, "e": 7526, "s": 7109, "text": "The rhdfs package –It provides HDFS file management in R, because data itself stores in Hadoop file system. Functions of this package are as given as follows. File Manipulations -( hdfs.delete, hdfs.rm, hdfs.del, hdfs.chown, hdfs.put, hdfs.get etc), File Read/Write -(hdfs.flush, hdfs.read, hdfs.seek, hdfs.tell, hdfs.line.reader etc), Directory -hdfs.dircreate, hdfs.mkdir, Initialization: hdfs.init, hdfs.defaults." }, { "code": null, "e": 7705, "s": 7526, "text": "The plyrmr package –It provides functionality likes data manipulation, summaries of the output result, performing set operations(union, intersection, subtraction, merge, unique)." }, { "code": null, "e": 7945, "s": 7705, "text": "b) RHIPE: Rhipe is used in R to do an intricate analysis of the large collection of data sets via Hadoop is an integrated programming environment tool that is brought by the Divide and Recombine (D & R) to analyze the huge amount of data. " }, { "code": null, "e": 8001, "s": 7945, "text": "RHIPE = R and Hadoop Integrated Programming Environment" }, { "code": null, "e": 8421, "s": 8001, "text": "RHIPE is a package of R that enables the use of API in Hadoop. Thus, this way we can read, save the complete data that is created using RHIPE MapReduce. RHIPE is deployed with many features that help us to effectively interact with HDFS. An individual can also use various languages like Perl, Java, or Python to read data sets in RHIPE. The general structure of the R script that uses Rhipe is shown below as follows." }, { "code": null, "e": 8423, "s": 8421, "text": "R" }, { "code": "library(Rhipe) rhint(TRUE, TRUE);map < -expression({lapply(map.values, function(mapper)...)})reduce < -expression(pre={...},reduce={...},post={...}, }x < - rhmr(map=map, reduce=reduce,ifolder=inputPath,ofolder=outputPath,inout=c('text', 'text'),jobname='a job name'))rhex(z)", "e": 8698, "s": 8423, "text": null }, { "code": null, "e": 9020, "s": 8698, "text": "Rhipe allows the R user to create MapReduce jobs(rmr package also helps to do this job) that work entirely within the R environment using R expressions. This MapReduce functionality: allows an analyst to quickly specify Maps and Reduces using the full power, flexibility, and expressiveness of the R interpreted language." }, { "code": null, "e": 9063, "s": 9020, "text": "c) Oracle R Connector for Hadoop (ORCH) : " }, { "code": null, "e": 9135, "s": 9063, "text": "Orch is a collection of R packages that provide the following features." }, { "code": null, "e": 9477, "s": 9135, "text": "Various attractive Interfaces to work with the data maintained in Hive tables, able to use the Apache Hadoop based computing infrastructure, and also provides the local R environment and Oracle database tables.Us a predictive analytic technique, written in R or Java as Hadoop MapReduce jobs, that can be applied to data stored in HDFS files" }, { "code": null, "e": 9688, "s": 9477, "text": "Various attractive Interfaces to work with the data maintained in Hive tables, able to use the Apache Hadoop based computing infrastructure, and also provides the local R environment and Oracle database tables." }, { "code": null, "e": 9820, "s": 9688, "text": "Us a predictive analytic technique, written in R or Java as Hadoop MapReduce jobs, that can be applied to data stored in HDFS files" }, { "code": null, "e": 9914, "s": 9820, "text": "After installing this package in R you’ll become able to do the various functions as follows." }, { "code": null, "e": 10026, "s": 9914, "text": "Able to make the easier access and transform HDFS data using a Hive-enabled transparency layer for general use," }, { "code": null, "e": 10104, "s": 10026, "text": "We enable to use the R language for writing mappers and reducers effectively," }, { "code": null, "e": 10222, "s": 10104, "text": "Copying of data between the R memory to the local file system, to the HDFS, to the Hive, and to the Oracle databases," }, { "code": null, "e": 10386, "s": 10222, "text": "Able to Schedule the R programs easily in order to execute the program as Hadoop MapReduce jobs and return the results to any of those corresponding locations etc." }, { "code": null, "e": 10512, "s": 10386, "text": "Oracle R Connector for Hadoop enables access from a local client of R to Apache Hadoop using the following function prefixes:" }, { "code": null, "e": 10588, "s": 10512, "text": "Hadoop –Identifies functions that provide an interface to Hadoop MapReduce." }, { "code": null, "e": 10650, "s": 10588, "text": "hdfs –Identifies functions that provide an interface to HDFS." }, { "code": null, "e": 10736, "s": 10650, "text": "Orch –Identifies a variety of functions; orch is a general prefix for ORCH functions." }, { "code": null, "e": 10810, "s": 10736, "text": "Ore –Identifies functions that provide an interface to a Hive data store." }, { "code": null, "e": 11101, "s": 10810, "text": "d) Hadoop Streaming: Hadoop streaming is a Hadoop utility for running the Hadoop MapReduce job with executable scripts such as Mapper and Reducer. The script is available as part of the R package on CRAN. And its aim is to make R more accessible to the Hadoop streaming-based applications. " }, { "code": null, "e": 11392, "s": 11101, "text": " This is just congruent to the pipe operation in Linux. With this, the text input file is printed on stream (stdin), which is provided as an input to Mapper, and the output (stdout) of Mapper is provided as an input to the Reducer; finally, Reducer writes the output to the HDFS directory. " }, { "code": null, "e": 11489, "s": 11392, "text": "А command line with mаp аnd reduce tasks implemented аs R scripts would look like the following." }, { "code": null, "e": 11491, "s": 11489, "text": "R" }, { "code": "$ ${HADOOP_HOME}/bin/Hadoop jar$ {HADOOP_HOME}/contrib/streaming/*.jar\\-inputformat org.apache.hadoop.mapred.TextInputFormat \\-input input_data.txt \\-output output \\-mapper /home/tst/src/map.R \\-reducer /home/tst/src/reduce.R \\-file /home/ts/src/map.R \\-file /home/tst/src/reduce.R", "e": 11773, "s": 11491, "text": null }, { "code": null, "e": 12114, "s": 11773, "text": "The main benefit of the Hadoop streaming is to allow the execution of the Java, as well as non-Java based programmed MapReduce jobs over Hadoop clusters. The Hadoop streaming supports various languages like Perl, Python, PHP, R, and C++, and other programming languages efficiently. Various components of the Hadoop streaming MapReduce job." }, { "code": null, "e": 12123, "s": 12114, "text": "gabaa406" }, { "code": null, "e": 12136, "s": 12123, "text": "kumar_satyam" }, { "code": null, "e": 12143, "s": 12136, "text": "Hadoop" }, { "code": null, "e": 12154, "s": 12143, "text": "R Language" }, { "code": null, "e": 12161, "s": 12154, "text": "Hadoop" } ]
Python | Split given dictionary in half
26 Jul, 2019 While working with dictionaries, sometimes we might have a problem in which we need to reduce the space taken by single container and wish to divide the dictionary into 2 halves. Let’s discuss certain ways in which this task can be performed. Method #1 : Using items() + len() + list slicingThe combination of above functions can easily perform this particular task in which slicing into half is done by list slicing and items of dictionary are extracted by items() # Python3 code to demonstrate working of# Split dictionary by half# Using items() + len() + list slicing # Initialize dictionarytest_dict = {'gfg' : 6, 'is' : 4, 'for' : 2, 'CS' : 10} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # Using items() + len() + list slicing# Split dictionary by halfres1 = dict(list(test_dict.items())[len(test_dict)//2:])res2 = dict(list(test_dict.items())[:len(test_dict)//2]) # printing result print("The first half of dictionary : " + str(res1))print("The second half of dictionary : " + str(res2)) The original dictionary : {‘CS’: 10, ‘for’: 2, ‘is’: 4, ‘gfg’: 6}The first half of dictionary : {‘is’: 4, ‘gfg’: 6}The second half of dictionary : {‘for’: 2, ‘CS’: 10} Method #2 : Using slice() + len() + items()The combination of above functions can be used to perform this particular task. In this, we perform task similar to above method, just the difference is the slice operation is performed by slice() instead of list slicing. # Python3 code to demonstrate working of# Split dictionary by half# Using items() + len() + slice()from itertools import islice # Initialize dictionarytest_dict = {'gfg' : 6, 'is' : 4, 'for' : 2, 'CS' : 10} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # Using items() + len() + slice()# Split dictionary by halfinc = iter(test_dict.items())res1 = dict(islice(inc, len(test_dict) // 2)) res2 = dict(inc) # printing result print("The first half of dictionary : " + str(res1))print("The second half of dictionary : " + str(res2)) The original dictionary : {‘CS’: 10, ‘for’: 2, ‘is’: 4, ‘gfg’: 6}The first half of dictionary : {‘is’: 4, ‘gfg’: 6}The second half of dictionary : {‘for’: 2, ‘CS’: 10} Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jul, 2019" }, { "code": null, "e": 271, "s": 28, "text": "While working with dictionaries, sometimes we might have a problem in which we need to reduce the space taken by single container and wish to divide the dictionary into 2 halves. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 494, "s": 271, "text": "Method #1 : Using items() + len() + list slicingThe combination of above functions can easily perform this particular task in which slicing into half is done by list slicing and items of dictionary are extracted by items()" }, { "code": "# Python3 code to demonstrate working of# Split dictionary by half# Using items() + len() + list slicing # Initialize dictionarytest_dict = {'gfg' : 6, 'is' : 4, 'for' : 2, 'CS' : 10} # printing original dictionaryprint(\"The original dictionary : \" + str(test_dict)) # Using items() + len() + list slicing# Split dictionary by halfres1 = dict(list(test_dict.items())[len(test_dict)//2:])res2 = dict(list(test_dict.items())[:len(test_dict)//2]) # printing result print(\"The first half of dictionary : \" + str(res1))print(\"The second half of dictionary : \" + str(res2))", "e": 1067, "s": 494, "text": null }, { "code": null, "e": 1235, "s": 1067, "text": "The original dictionary : {‘CS’: 10, ‘for’: 2, ‘is’: 4, ‘gfg’: 6}The first half of dictionary : {‘is’: 4, ‘gfg’: 6}The second half of dictionary : {‘for’: 2, ‘CS’: 10}" }, { "code": null, "e": 1502, "s": 1237, "text": "Method #2 : Using slice() + len() + items()The combination of above functions can be used to perform this particular task. In this, we perform task similar to above method, just the difference is the slice operation is performed by slice() instead of list slicing." }, { "code": "# Python3 code to demonstrate working of# Split dictionary by half# Using items() + len() + slice()from itertools import islice # Initialize dictionarytest_dict = {'gfg' : 6, 'is' : 4, 'for' : 2, 'CS' : 10} # printing original dictionaryprint(\"The original dictionary : \" + str(test_dict)) # Using items() + len() + slice()# Split dictionary by halfinc = iter(test_dict.items())res1 = dict(islice(inc, len(test_dict) // 2)) res2 = dict(inc) # printing result print(\"The first half of dictionary : \" + str(res1))print(\"The second half of dictionary : \" + str(res2))", "e": 2072, "s": 1502, "text": null }, { "code": null, "e": 2240, "s": 2072, "text": "The original dictionary : {‘CS’: 10, ‘for’: 2, ‘is’: 4, ‘gfg’: 6}The first half of dictionary : {‘is’: 4, ‘gfg’: 6}The second half of dictionary : {‘for’: 2, ‘CS’: 10}" }, { "code": null, "e": 2267, "s": 2240, "text": "Python dictionary-programs" }, { "code": null, "e": 2274, "s": 2267, "text": "Python" }, { "code": null, "e": 2290, "s": 2274, "text": "Python Programs" } ]
PHP vs. Node.js
06 Jan, 2022 PHP and Node.js are both used for server side development and thus have become a competitor for each other. Below are some differences based on different parameters to understand the two and make decisions between the two giants. Both platforms have access to the command line interface via: Example: Printing ‘Hello World’ in PHP and Node.js The following snippets compare the print ‘Hello World’ program in both languages: PHP // Printing Hello GeeksforGeeks in PHPecho 'Hello GeeksForGeeks'; Node.js console.log('Hello GeeksForGeeks'); Note: To run the Node.js code, please use the REPL environment. Synchronous code executes line by line and proceeds to execute the next line of code when the current line has been executed. Asynchronous code executes all the code at the same time. Note: Program can get stuck in a ‘callback hell’ if a lot of functions needs to be chained which might require piping data from one function to another. However, it can be resolved by Node.js as it has feature of Async/Await which can help a block of code execute synchronously. The Switch between different environments and languages is attributed to the drop of efficiency when writing code. Changing between multiple coding languages leads to drop in the efficiency of the programmer. PHP uses module installing technologies like PEAR(a veteran package system), and Composer which is comparatively new. PEAR is a framework and distribution system for reusable PHP components. Composer is a tool for dependency management in PHP. It allows users to declare the libraries on which the project depends and it will manage (install/update) them for user. Example: Laravel framework // requires Composer installed on your system // run following command on terminal. // This installs laravel on your system composer global require "laravel/installer" // Below command creates a folder called // GeeksForGeeks with laravel installed laravel new GeeksForGeeks Example: Express framework web server: // Below command installs ExpressJS // in your project folder npm install express --save // creating web server using Express framework // write the following code in your gfg.js file var express = require('express'); var app = express(); express.listen('3000', function(){ console.log(' GeeksForGeeks demo server running on express'); }); Negative point PHP: MySQL database systems are especially prone to SQL injection attacks, Cross-side scripting(XSS), and others. Negative point Node.js: Even though they are not that common, NoSQL injection attacks are a documented vulnerability. But compared to SQL injection, they are negligible. The major reason for this is that they are new and their code design is in such a way that they are inherently resistant to such attacks. Example: Starting PHP server PHP // starting php server$ php -S localhost:8000 // index.js file code<?php echo 'Hello! This is GeeksForGeeks';?> The PHP webserver was provided to aid application development and can’t be used efficiently as a full-fledged web server. Example: Starting Node.js server Javascript // starting Node.js server$ node app.js // app.js source code var http = require('http');http.createServer(function(req, res) { res.writeHead(200, { 'Content-Type' : 'text/plain' }); res.end('Hi Programmer\n'); }) .listen(8080, '127.0.0.1');console.log('GeeksForGeeks Server running at http://127.0.0.1:8080/'); Own web servers can be coded in Node.js on which Node.js applications can run. These servers have the potential of high scalability if configured and monitored properly. Used in developing CPU-intensive applications like meteorology applications and scientific applications. LAMP stack is used in API development. CMS (Content Management Systems) like WordPress, Drupal also use PHP which makes it possible to be used in creating blogs, websites, e-commerce sites etc. Nodejs is ideal for developing highly scalable server-side solutions because of its non-blocking I/O, and event-driven model. Used massively in Real-time applications like chat applications, blogs, video streaming applications. Used in developing single-page applications like resume portfolios, individual websites. Note: PHP should be used in applications in which client does not have to interact with the server again and again and Node.js should be used for the applications which require a lot of interaction between client and server. kk773572498 JavaScript-Misc Node.js JavaScript PHP Technical Scripter Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request How to execute PHP code using command line ? PHP in_array() Function How to delete an array element based on key in PHP? How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ?
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Jan, 2022" }, { "code": null, "e": 285, "s": 54, "text": "PHP and Node.js are both used for server side development and thus have become a competitor for each other. Below are some differences based on different parameters to understand the two and make decisions between the two giants. " }, { "code": null, "e": 348, "s": 285, "text": "Both platforms have access to the command line interface via: " }, { "code": null, "e": 482, "s": 348, "text": "Example: Printing ‘Hello World’ in PHP and Node.js The following snippets compare the print ‘Hello World’ program in both languages: " }, { "code": null, "e": 486, "s": 482, "text": "PHP" }, { "code": "// Printing Hello GeeksforGeeks in PHPecho 'Hello GeeksForGeeks'; ", "e": 554, "s": 486, "text": null }, { "code": null, "e": 562, "s": 554, "text": "Node.js" }, { "code": null, "e": 600, "s": 562, "text": "\nconsole.log('Hello GeeksForGeeks');\n" }, { "code": null, "e": 665, "s": 600, "text": "Note: To run the Node.js code, please use the REPL environment. " }, { "code": null, "e": 849, "s": 665, "text": "Synchronous code executes line by line and proceeds to execute the next line of code when the current line has been executed. Asynchronous code executes all the code at the same time." }, { "code": null, "e": 1128, "s": 849, "text": "Note: Program can get stuck in a ‘callback hell’ if a lot of functions needs to be chained which might require piping data from one function to another. However, it can be resolved by Node.js as it has feature of Async/Await which can help a block of code execute synchronously." }, { "code": null, "e": 1338, "s": 1128, "text": "The Switch between different environments and languages is attributed to the drop of efficiency when writing code. Changing between multiple coding languages leads to drop in the efficiency of the programmer. " }, { "code": null, "e": 1458, "s": 1338, "text": "PHP uses module installing technologies like PEAR(a veteran package system), and Composer which is comparatively new. " }, { "code": null, "e": 1531, "s": 1458, "text": "PEAR is a framework and distribution system for reusable PHP components." }, { "code": null, "e": 1705, "s": 1531, "text": "Composer is a tool for dependency management in PHP. It allows users to declare the libraries on which the project depends and it will manage (install/update) them for user." }, { "code": null, "e": 1733, "s": 1705, "text": "Example: Laravel framework " }, { "code": null, "e": 2009, "s": 1733, "text": "// requires Composer installed on your system\n// run following command on terminal.\n// This installs laravel on your system\ncomposer global require \"laravel/installer\"\n\n// Below command creates a folder called\n// GeeksForGeeks with laravel installed\nlaravel new GeeksForGeeks" }, { "code": null, "e": 2049, "s": 2009, "text": "Example: Express framework web server: " }, { "code": null, "e": 2410, "s": 2049, "text": "// Below command installs ExpressJS \n// in your project folder\nnpm install express --save\n\n// creating web server using Express framework\n// write the following code in your gfg.js file\n\nvar express = require('express');\nvar app = express();\nexpress.listen('3000', function(){\nconsole.log(' GeeksForGeeks demo server\n running on express');\n});" }, { "code": null, "e": 2539, "s": 2410, "text": "Negative point PHP: MySQL database systems are especially prone to SQL injection attacks, Cross-side scripting(XSS), and others." }, { "code": null, "e": 2847, "s": 2539, "text": "Negative point Node.js: Even though they are not that common, NoSQL injection attacks are a documented vulnerability. But compared to SQL injection, they are negligible. The major reason for this is that they are new and their code design is in such a way that they are inherently resistant to such attacks." }, { "code": null, "e": 2877, "s": 2847, "text": "Example: Starting PHP server " }, { "code": null, "e": 2881, "s": 2877, "text": "PHP" }, { "code": "// starting php server$ php -S localhost:8000 // index.js file code<?php echo 'Hello! This is GeeksForGeeks';?>", "e": 2994, "s": 2881, "text": null }, { "code": null, "e": 3116, "s": 2994, "text": "The PHP webserver was provided to aid application development and can’t be used efficiently as a full-fledged web server." }, { "code": null, "e": 3150, "s": 3116, "text": "Example: Starting Node.js server " }, { "code": null, "e": 3161, "s": 3150, "text": "Javascript" }, { "code": "// starting Node.js server$ node app.js // app.js source code var http = require('http');http.createServer(function(req, res) { res.writeHead(200, { 'Content-Type' : 'text/plain' }); res.end('Hi Programmer\\n'); }) .listen(8080, '127.0.0.1');console.log('GeeksForGeeks Server running at http://127.0.0.1:8080/');", "e": 3503, "s": 3161, "text": null }, { "code": null, "e": 3674, "s": 3503, "text": "Own web servers can be coded in Node.js on which Node.js applications can run. These servers have the potential of high scalability if configured and monitored properly. " }, { "code": null, "e": 3779, "s": 3674, "text": "Used in developing CPU-intensive applications like meteorology applications and scientific applications." }, { "code": null, "e": 3818, "s": 3779, "text": "LAMP stack is used in API development." }, { "code": null, "e": 3973, "s": 3818, "text": "CMS (Content Management Systems) like WordPress, Drupal also use PHP which makes it possible to be used in creating blogs, websites, e-commerce sites etc." }, { "code": null, "e": 4099, "s": 3973, "text": "Nodejs is ideal for developing highly scalable server-side solutions because of its non-blocking I/O, and event-driven model." }, { "code": null, "e": 4201, "s": 4099, "text": "Used massively in Real-time applications like chat applications, blogs, video streaming applications." }, { "code": null, "e": 4290, "s": 4201, "text": "Used in developing single-page applications like resume portfolios, individual websites." }, { "code": null, "e": 4517, "s": 4290, "text": "Note: PHP should be used in applications in which client does not have to interact with the server again and again and Node.js should be used for the applications which require a lot of interaction between client and server. " }, { "code": null, "e": 4529, "s": 4517, "text": "kk773572498" }, { "code": null, "e": 4545, "s": 4529, "text": "JavaScript-Misc" }, { "code": null, "e": 4553, "s": 4545, "text": "Node.js" }, { "code": null, "e": 4564, "s": 4553, "text": "JavaScript" }, { "code": null, "e": 4568, "s": 4564, "text": "PHP" }, { "code": null, "e": 4587, "s": 4568, "text": "Technical Scripter" }, { "code": null, "e": 4604, "s": 4587, "text": "Web Technologies" }, { "code": null, "e": 4608, "s": 4604, "text": "PHP" }, { "code": null, "e": 4706, "s": 4608, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4767, "s": 4706, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4839, "s": 4767, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 4879, "s": 4839, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 4921, "s": 4879, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 4962, "s": 4921, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 5007, "s": 4962, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 5031, "s": 5007, "text": "PHP in_array() Function" }, { "code": null, "e": 5083, "s": 5031, "text": "How to delete an array element based on key in PHP?" }, { "code": null, "e": 5133, "s": 5083, "text": "How to Insert Form Data into Database using PHP ?" } ]
SQL Query to find the Nth Largest Value in a Column using Limit and Offset - GeeksforGeeks
30 Jun, 2021 Prerequisite – How to find Nth highest salary from a table Problem Statement : Write an SQL query to find the nth largest value from the column using LIMIT and OFFSET. Example-1 : Table – BILLS The above table has the electricity bills of all the flats in an apartment. You have to find the nth largest electricity bill in the table. SELECT DISTINCT ElectricityBill AS NthHighestElectricityBill FROM Bills ORDER BY ElectricityBill DESC LIMIT 1 OFFSET n-1; Here n should be an integer whose value must be greater than zero. Explaination : In the above query, we are sorting the values of ElectricityBill column in descending order using Order By clause and by selecting only distinct values. After sorting it in descending order we have to find the Nth value from the top, so we use OFFSET n-1 which eliminates the top n-1 values from the list, now from the remaining list we have to select only its top element, to do that we use LIMIT 1. If we want to find the 3rd highest electricity bill the query will be – SELECT DISTINCT ElectricityBill AS 3rdHighestElectricityBill FROM Bills ORDER BY ElectricityBill DESC LIMIT 1 OFFSET 2; The result of the above query will be – Example-2 : Table – EmployeeSalary The above table has the salaries of employees working in a small company. Find the employee id who is earning the 4th highest salary. SELECT EmployeeID AS 4thHighestEarningEmployee FROM EmployeeSalary ORDER BY SalaryInThousands DESC LIMIT 1 OFFSET 3; Explaination : Here distinct is not used because we need employee whose earnings stand at 4th place among all the employee’s (i.e 316k not 259k). The result of the above query will be – as5853535 DBMS-SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments CTE in SQL SQL | Views Difference between DELETE, DROP and TRUNCATE How to Update Multiple Columns in Single Update Statement in SQL? Difference between SQL and NoSQL Difference between DDL and DML in DBMS SQL Interview Questions What is Temporary Table in SQL? MySQL | Group_CONCAT() Function SQL - ORDER BY
[ { "code": null, "e": 24509, "s": 24481, "text": "\n30 Jun, 2021" }, { "code": null, "e": 24678, "s": 24509, "text": "Prerequisite – How to find Nth highest salary from a table Problem Statement : Write an SQL query to find the nth largest value from the column using LIMIT and OFFSET. " }, { "code": null, "e": 24691, "s": 24678, "text": "Example-1 : " }, { "code": null, "e": 24706, "s": 24691, "text": "Table – BILLS " }, { "code": null, "e": 24849, "s": 24708, "text": "The above table has the electricity bills of all the flats in an apartment. You have to find the nth largest electricity bill in the table. " }, { "code": null, "e": 24974, "s": 24851, "text": "SELECT DISTINCT ElectricityBill AS NthHighestElectricityBill\nFROM Bills\nORDER BY ElectricityBill DESC\nLIMIT 1 \nOFFSET n-1;" }, { "code": null, "e": 25042, "s": 24974, "text": "Here n should be an integer whose value must be greater than zero. " }, { "code": null, "e": 25459, "s": 25042, "text": "Explaination : In the above query, we are sorting the values of ElectricityBill column in descending order using Order By clause and by selecting only distinct values. After sorting it in descending order we have to find the Nth value from the top, so we use OFFSET n-1 which eliminates the top n-1 values from the list, now from the remaining list we have to select only its top element, to do that we use LIMIT 1. " }, { "code": null, "e": 25532, "s": 25459, "text": "If we want to find the 3rd highest electricity bill the query will be – " }, { "code": null, "e": 25654, "s": 25534, "text": "SELECT DISTINCT ElectricityBill AS 3rdHighestElectricityBill\nFROM Bills\nORDER BY ElectricityBill DESC\nLIMIT 1\nOFFSET 2;" }, { "code": null, "e": 25695, "s": 25654, "text": "The result of the above query will be – " }, { "code": null, "e": 25710, "s": 25697, "text": "Example-2 : " }, { "code": null, "e": 25734, "s": 25710, "text": "Table – EmployeeSalary " }, { "code": null, "e": 25871, "s": 25736, "text": "The above table has the salaries of employees working in a small company. Find the employee id who is earning the 4th highest salary. " }, { "code": null, "e": 25992, "s": 25873, "text": "SELECT EmployeeID AS 4thHighestEarningEmployee \nFROM EmployeeSalary\nORDER BY SalaryInThousands DESC\nLIMIT 1 \nOFFSET 3;" }, { "code": null, "e": 26139, "s": 25992, "text": "Explaination : Here distinct is not used because we need employee whose earnings stand at 4th place among all the employee’s (i.e 316k not 259k). " }, { "code": null, "e": 26180, "s": 26139, "text": "The result of the above query will be – " }, { "code": null, "e": 26194, "s": 26184, "text": "as5853535" }, { "code": null, "e": 26203, "s": 26194, "text": "DBMS-SQL" }, { "code": null, "e": 26207, "s": 26203, "text": "SQL" }, { "code": null, "e": 26211, "s": 26207, "text": "SQL" }, { "code": null, "e": 26309, "s": 26211, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26318, "s": 26309, "text": "Comments" }, { "code": null, "e": 26331, "s": 26318, "text": "Old Comments" }, { "code": null, "e": 26342, "s": 26331, "text": "CTE in SQL" }, { "code": null, "e": 26354, "s": 26342, "text": "SQL | Views" }, { "code": null, "e": 26399, "s": 26354, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 26465, "s": 26399, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 26498, "s": 26465, "text": "Difference between SQL and NoSQL" }, { "code": null, "e": 26537, "s": 26498, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 26561, "s": 26537, "text": "SQL Interview Questions" }, { "code": null, "e": 26593, "s": 26561, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 26625, "s": 26593, "text": "MySQL | Group_CONCAT() Function" } ]
Apache POI PPT - Slide Management
After completing this chapter, you will be able to delete, reorder, and perform read and write operations on a slide. We can change the page size of a slide using the setPageSize() method of the XMLSlideShow class. Initially create a presentation as shown below − File file = new File("C://POIPPT//Examples// TitleAndContentLayout.pptx"); //create presentation XMLSlideShow ppt = new XMLSlideShow(new FileInputStream(file)); Get the size of the current slide using the getPageSize() method of the XMLSlideShow class. java.awt.Dimension pgsize = ppt.getPageSize(); Set the size of the page using the setPageSize() method. ppt.setPageSize(new java.awt.Dimension(1024, 768)); The complete program for changing the size of a slide is given below − import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.xslf.usermodel.XMLSlideShow; public class ChangingSlide { public static void main(String args[]) throws IOException { //create file object File file = new File("TitleAndContentLayout.pptx"); //create presentation XMLSlideShow ppt = new XMLSlideShow(); //getting the current page size java.awt.Dimension pgsize = ppt.getPageSize(); int pgw = pgsize.width; //slide width in points int pgh = pgsize.height; //slide height in points System.out.println("current page size of the PPT is:"); System.out.println("width :" + pgw); System.out.println("height :" + pgh); //set new page size ppt.setPageSize(new java.awt.Dimension(2048,1536)); //creating file object FileOutputStream out = new FileOutputStream(file); //saving the changes to a file ppt.write(out); System.out.println("slide size changed to given dimentions "); out.close(); } } Save the above Java code as ChangingSlide.java, and then compile and execute it from the command prompt as follows − $javac ChangingSlide.java $java ChangingSlide It will compile and execute to generate the following output. current page size of the presentation is : width :720 height :540 slide size changed to given dimensions Given below is the snapshot of the presentation before changing the slide size − The slide appears as follows after changing its size − You can set the slide order using the setSlideOrder() method. Given below is the procedure to set the order of the slides. Open an existing PPT document as shown below − File file = new File("C://POIPPT//Examples//example1.pptx"); XMLSlideShow ppt = new XMLSlideShow(new FileInputStream(file)); Get the slides using the getSlides() method as shown below − List<XSLFSlide> slides = ppt.getSlides(); Select a slide from the array of the slides, and change the order using the setSlideOrder() method as shown below − //selecting the fourth slide XSLFSlide selectesdslide = slides.get(4); //bringing it to the top ppt.setSlideOrder(selectesdslide, 1); Given below is the complete program to reorder the slides in a presentation − import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import org.apache.poi.xslf.usermodel.XMLSlideShow; import org.apache.poi.xslf.usermodel.XSLFSlide; public class ReorderSlide { public static void main(String args[]) throws IOException { //opening an existing presentation File file = new File("example1.pptx"); XMLSlideShow ppt = new XMLSlideShow(new FileInputStream(file)); //get the slides List<XSLFSlide> slides = ppt.getSlides(); //selecting the fourth slide XSLFSlide selectesdslide = slides.get(13); //bringing it to the top ppt.setSlideOrder(selectesdslide, 0); //creating an file object FileOutputStream out = new FileOutputStream(file); //saving the changes to a file ppt.write(out); out.close(); } } Save the above Java code as ReorderSlide.java, and then compile and execute it from the command prompt as follows − $javac ReorderSlide.java $java ReorderSlide It will compile and execute to generate the following output. Reordering of the slides is done Given below is the snapshot of the presentation before reordering the slides − After reordering the slides, the presentation appears as follows. Here we have selected the slide with image and moved it to the top. You can delete the slides using the removeSlide() method. Follow the steps given below to delete slides. Open an existing presentation using the XMLSlideShow class as shown below − File file = new File("C://POIPPT//Examples//image.pptx"); XMLSlideShow ppt = new XMLSlideShow(new FileInputStream(file)); Delete the required slide using the removeSlide() method. This method accepts an integer parameter. Pass the index of the slide that is to be deleted to this method. ppt.removeSlide(1); Given below is the program to delete slides from a presentation − import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.xslf.usermodel.XMLSlideShow; public class Deleteslide { public static void main(String args[]) throws IOException { //Opening an existing slide File file = new File("image.pptx"); XMLSlideShow ppt = new XMLSlideShow(new FileInputStream(file)); //deleting a slide ppt.removeSlide(1); //creating a file object FileOutputStream out = new FileOutputStream(file); //Saving the changes to the presentation ppt.write(out); out.close(); } } Save the above Java code as Deleteslide.java, and then compile and execute it from the command prompt as follows − $javac Deleteslide.java $java Deleteslide It will compile and execute to generate the following output − reordering of the slides is done The snapshot below is of the presentation before deleting the slide − After deleting the slide, the presentation appears as follows − 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2135, "s": 2017, "text": "After completing this chapter, you will be able to delete, reorder, and perform read and write operations on a slide." }, { "code": null, "e": 2232, "s": 2135, "text": "We can change the page size of a slide using the setPageSize() method of the XMLSlideShow class." }, { "code": null, "e": 2281, "s": 2232, "text": "Initially create a presentation as shown below −" }, { "code": null, "e": 2444, "s": 2281, "text": "File file = new File(\"C://POIPPT//Examples// TitleAndContentLayout.pptx\");\n\n//create presentation\nXMLSlideShow ppt = new XMLSlideShow(new FileInputStream(file));\n" }, { "code": null, "e": 2536, "s": 2444, "text": "Get the size of the current slide using the getPageSize() method of the XMLSlideShow class." }, { "code": null, "e": 2584, "s": 2536, "text": "java.awt.Dimension pgsize = ppt.getPageSize();\n" }, { "code": null, "e": 2641, "s": 2584, "text": "Set the size of the page using the setPageSize() method." }, { "code": null, "e": 2694, "s": 2641, "text": "ppt.setPageSize(new java.awt.Dimension(1024, 768));\n" }, { "code": null, "e": 2765, "s": 2694, "text": "The complete program for changing the size of a slide is given below −" }, { "code": null, "e": 3862, "s": 2765, "text": "import java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport org.apache.poi.xslf.usermodel.XMLSlideShow;\n\npublic class ChangingSlide {\n public static void main(String args[]) throws IOException {\n //create file object\n File file = new File(\"TitleAndContentLayout.pptx\");\n\t \n //create presentation\n XMLSlideShow ppt = new XMLSlideShow();\n \n //getting the current page size\n java.awt.Dimension pgsize = ppt.getPageSize();\n int pgw = pgsize.width; //slide width in points\n int pgh = pgsize.height; //slide height in points\n \n System.out.println(\"current page size of the PPT is:\");\n System.out.println(\"width :\" + pgw);\n System.out.println(\"height :\" + pgh);\n \n //set new page size\n ppt.setPageSize(new java.awt.Dimension(2048,1536));\n \n //creating file object\n FileOutputStream out = new FileOutputStream(file);\n \n //saving the changes to a file\n ppt.write(out);\n System.out.println(\"slide size changed to given dimentions \");\n out.close();\t\n }\n}" }, { "code": null, "e": 3979, "s": 3862, "text": "Save the above Java code as ChangingSlide.java, and then compile and execute it from the command prompt as follows −" }, { "code": null, "e": 4026, "s": 3979, "text": "$javac ChangingSlide.java\n$java ChangingSlide\n" }, { "code": null, "e": 4088, "s": 4026, "text": "It will compile and execute to generate the following output." }, { "code": null, "e": 4195, "s": 4088, "text": "current page size of the presentation is : \nwidth :720\nheight :540\nslide size changed to given dimensions\n" }, { "code": null, "e": 4276, "s": 4195, "text": "Given below is the snapshot of the presentation before changing the slide size −" }, { "code": null, "e": 4331, "s": 4276, "text": "The slide appears as follows after changing its size −" }, { "code": null, "e": 4454, "s": 4331, "text": "You can set the slide order using the setSlideOrder() method. Given below is the procedure to set the order of the slides." }, { "code": null, "e": 4501, "s": 4454, "text": "Open an existing PPT document as shown below −" }, { "code": null, "e": 4627, "s": 4501, "text": "File file = new File(\"C://POIPPT//Examples//example1.pptx\");\nXMLSlideShow ppt = new XMLSlideShow(new FileInputStream(file));\n" }, { "code": null, "e": 4688, "s": 4627, "text": "Get the slides using the getSlides() method as shown below −" }, { "code": null, "e": 4731, "s": 4688, "text": "List<XSLFSlide> slides = ppt.getSlides();\n" }, { "code": null, "e": 4847, "s": 4731, "text": "Select a slide from the array of the slides, and change the order using the setSlideOrder() method as shown below −" }, { "code": null, "e": 4983, "s": 4847, "text": "//selecting the fourth slide\nXSLFSlide selectesdslide = slides.get(4);\n\n//bringing it to the top\nppt.setSlideOrder(selectesdslide, 1);\n" }, { "code": null, "e": 5061, "s": 4983, "text": "Given below is the complete program to reorder the slides in a presentation −" }, { "code": null, "e": 5989, "s": 5061, "text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.util.List;\nimport org.apache.poi.xslf.usermodel.XMLSlideShow;\nimport org.apache.poi.xslf.usermodel.XSLFSlide;\n\npublic class ReorderSlide {\t\n public static void main(String args[]) throws IOException {\n //opening an existing presentation\n File file = new File(\"example1.pptx\");\n XMLSlideShow ppt = new XMLSlideShow(new FileInputStream(file));\n \n //get the slides \n List<XSLFSlide> slides = ppt.getSlides(); \n \n //selecting the fourth slide\n XSLFSlide selectesdslide = slides.get(13);\n \n //bringing it to the top\n ppt.setSlideOrder(selectesdslide, 0);\n \n //creating an file object \n FileOutputStream out = new FileOutputStream(file);\n\t \n //saving the changes to a file\n ppt.write(out);\n out.close();\t\n }\n}" }, { "code": null, "e": 6105, "s": 5989, "text": "Save the above Java code as ReorderSlide.java, and then compile and execute it from the command prompt as follows −" }, { "code": null, "e": 6150, "s": 6105, "text": "$javac ReorderSlide.java\n$java ReorderSlide\n" }, { "code": null, "e": 6212, "s": 6150, "text": "It will compile and execute to generate the following output." }, { "code": null, "e": 6246, "s": 6212, "text": "Reordering of the slides is done\n" }, { "code": null, "e": 6325, "s": 6246, "text": "Given below is the snapshot of the presentation before reordering the slides −" }, { "code": null, "e": 6459, "s": 6325, "text": "After reordering the slides, the presentation appears as follows. Here we have selected the slide with image and moved it to the top." }, { "code": null, "e": 6564, "s": 6459, "text": "You can delete the slides using the removeSlide() method. Follow the steps given below to delete slides." }, { "code": null, "e": 6640, "s": 6564, "text": "Open an existing presentation using the XMLSlideShow class as shown below −" }, { "code": null, "e": 6763, "s": 6640, "text": "File file = new File(\"C://POIPPT//Examples//image.pptx\");\nXMLSlideShow ppt = new XMLSlideShow(new FileInputStream(file));\n" }, { "code": null, "e": 6929, "s": 6763, "text": "Delete the required slide using the removeSlide() method. This method accepts an integer parameter. Pass the index of the slide that is to be deleted to this method." }, { "code": null, "e": 6950, "s": 6929, "text": "ppt.removeSlide(1);\n" }, { "code": null, "e": 7016, "s": 6950, "text": "Given below is the program to delete slides from a presentation −" }, { "code": null, "e": 7676, "s": 7016, "text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\n\nimport org.apache.poi.xslf.usermodel.XMLSlideShow;\n\npublic class Deleteslide { \n public static void main(String args[]) throws IOException {\n //Opening an existing slide\n File file = new File(\"image.pptx\");\n XMLSlideShow ppt = new XMLSlideShow(new FileInputStream(file));\n \n //deleting a slide\n ppt.removeSlide(1);\n \n //creating a file object\n FileOutputStream out = new FileOutputStream(file);\n \n //Saving the changes to the presentation\n ppt.write(out);\n out.close();\t\n }\n}" }, { "code": null, "e": 7791, "s": 7676, "text": "Save the above Java code as Deleteslide.java, and then compile and execute it from the command prompt as follows −" }, { "code": null, "e": 7834, "s": 7791, "text": "$javac Deleteslide.java\n$java Deleteslide\n" }, { "code": null, "e": 7897, "s": 7834, "text": "It will compile and execute to generate the following output −" }, { "code": null, "e": 7931, "s": 7897, "text": "reordering of the slides is done\n" }, { "code": null, "e": 8001, "s": 7931, "text": "The snapshot below is of the presentation before deleting the slide −" }, { "code": null, "e": 8065, "s": 8001, "text": "After deleting the slide, the presentation appears as follows −" }, { "code": null, "e": 8100, "s": 8065, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8119, "s": 8100, "text": " Arnab Chakraborty" }, { "code": null, "e": 8154, "s": 8119, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8175, "s": 8154, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 8208, "s": 8175, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 8221, "s": 8208, "text": " Nilay Mehta" }, { "code": null, "e": 8256, "s": 8221, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8274, "s": 8256, "text": " Bigdata Engineer" }, { "code": null, "e": 8307, "s": 8274, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 8325, "s": 8307, "text": " Bigdata Engineer" }, { "code": null, "e": 8358, "s": 8325, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 8376, "s": 8358, "text": " Bigdata Engineer" }, { "code": null, "e": 8383, "s": 8376, "text": " Print" }, { "code": null, "e": 8394, "s": 8383, "text": " Add Notes" } ]
Union of two Objects in R Programming - union() Function - GeeksforGeeks
19 May, 2020 union() function in R Language is used to combine the data of two objects. This function takes two objects like Vectors, dataframes, etc. as arguments and results in a third object with the combination of the data of both the objects. Syntax: union(x, y) Parameters:x and y: Objects with sequence of items Example 1: Union of two Vectors # R program to illustrate# union of two vectors # Vector 1x1 <- c(1, 2, 3, 4, 5, 6, 5, 5) # Vector 2 x2 <- c(8, 9) # Union of two vectors x3 <- union(x1, x2) print(x3) Output: [1] 1 2 3 4 5 6 8 9 Here in the above code, the vector x1 contains values from 1-6, and x2 has two values. Now the union of these two vector x1 and x2 will combine each of the values present in them just once. Note: Union of two vectors removes the duplicate elements in the final vector. Example 2: Union of two dataframes # R program to illustrate # the union of two data frames # Data frame 1data_x <- data.frame(x1 = c(5, 6, 7), x2 = c(1, 1, 1)) # Data frame 2data_y <- data.frame(y1 = c(2, 3, 4), y2 = c(2, 2, 2)) # R union two data framesdata_z <- union(data_x, data_y) print(data_z) Output: [[1]] [1] 5 6 7 [[2]] [1] 1 1 1 [[3]] [1] 2 3 4 [[4]] [1] 2 2 2 Here in the above code, we have created two data frames first with x1, x2 and second have y1, y2. Union of these two data frames creates a third data frame with combined values. R-dataStructures R-Functions Programming Language R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Decorators with parameters in Python Top 10 Programming Languages to Learn in 2022 Shallow Copy and Deep Copy in C++ C# | Data Types Difference between Shallow and Deep copy of a class Change column name of a given DataFrame in R How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Adding elements in a vector in R programming - append() method Loops in R (for, while, repeat)
[ { "code": null, "e": 25400, "s": 25372, "text": "\n19 May, 2020" }, { "code": null, "e": 25635, "s": 25400, "text": "union() function in R Language is used to combine the data of two objects. This function takes two objects like Vectors, dataframes, etc. as arguments and results in a third object with the combination of the data of both the objects." }, { "code": null, "e": 25655, "s": 25635, "text": "Syntax: union(x, y)" }, { "code": null, "e": 25706, "s": 25655, "text": "Parameters:x and y: Objects with sequence of items" }, { "code": null, "e": 25738, "s": 25706, "text": "Example 1: Union of two Vectors" }, { "code": "# R program to illustrate# union of two vectors # Vector 1x1 <- c(1, 2, 3, 4, 5, 6, 5, 5) # Vector 2 x2 <- c(8, 9) # Union of two vectors x3 <- union(x1, x2) print(x3) ", "e": 25962, "s": 25738, "text": null }, { "code": null, "e": 25970, "s": 25962, "text": "Output:" }, { "code": null, "e": 25990, "s": 25970, "text": "[1] 1 2 3 4 5 6 8 9" }, { "code": null, "e": 26180, "s": 25990, "text": "Here in the above code, the vector x1 contains values from 1-6, and x2 has two values. Now the union of these two vector x1 and x2 will combine each of the values present in them just once." }, { "code": null, "e": 26259, "s": 26180, "text": "Note: Union of two vectors removes the duplicate elements in the final vector." }, { "code": null, "e": 26294, "s": 26259, "text": "Example 2: Union of two dataframes" }, { "code": "# R program to illustrate # the union of two data frames # Data frame 1data_x <- data.frame(x1 = c(5, 6, 7), x2 = c(1, 1, 1)) # Data frame 2data_y <- data.frame(y1 = c(2, 3, 4), y2 = c(2, 2, 2)) # R union two data framesdata_z <- union(data_x, data_y) print(data_z) ", "e": 26632, "s": 26294, "text": null }, { "code": null, "e": 26640, "s": 26632, "text": "Output:" }, { "code": null, "e": 26708, "s": 26640, "text": "[[1]]\n[1] 5 6 7\n\n[[2]]\n[1] 1 1 1\n\n[[3]]\n[1] 2 3 4\n\n[[4]]\n[1] 2 2 2\n" }, { "code": null, "e": 26886, "s": 26708, "text": "Here in the above code, we have created two data frames first with x1, x2 and second have y1, y2. Union of these two data frames creates a third data frame with combined values." }, { "code": null, "e": 26903, "s": 26886, "text": "R-dataStructures" }, { "code": null, "e": 26915, "s": 26903, "text": "R-Functions" }, { "code": null, "e": 26936, "s": 26915, "text": "Programming Language" }, { "code": null, "e": 26947, "s": 26936, "text": "R Language" }, { "code": null, "e": 27045, "s": 26947, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27082, "s": 27045, "text": "Decorators with parameters in Python" }, { "code": null, "e": 27128, "s": 27082, "text": "Top 10 Programming Languages to Learn in 2022" }, { "code": null, "e": 27162, "s": 27128, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 27178, "s": 27162, "text": "C# | Data Types" }, { "code": null, "e": 27230, "s": 27178, "text": "Difference between Shallow and Deep copy of a class" }, { "code": null, "e": 27275, "s": 27230, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 27333, "s": 27275, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 27385, "s": 27333, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 27448, "s": 27385, "text": "Adding elements in a vector in R programming - append() method" } ]
What is the difference between int and Int32 in C#?
Int32 is a type provided by .NET framework whereas int is an alias for Int32 in C# language. Int32 x = 5; Int32 x = 5; int x = 5; int x = 5; So, in use both the above statements will hold a 32bit integer. They compile to the same code, so at execution time there is no difference whatsoever. The only minor difference is Int32 can be only used with System namespace. While validating the type of a value like mentioned above we can use Int32 or int. typeof(int) == typeof(Int32) == typeof(System.Int32) The below example shows how an integer is declared using System.Int32. Live Demo using System; namespace DemoApplication{ class Program{ static void Main(string[] args){ Int32 x = 5; Console.WriteLine(x); //Output: 5 } } } 5 The below example shows how an integer is declared using int keyword. Live Demo using System; namespace DemoApplication{ class Program{ static void Main(string[] args){ int x = 5; Console.WriteLine(x); //Output: 5 } } } 5
[ { "code": null, "e": 1155, "s": 1062, "text": "Int32 is a type provided by .NET framework whereas int is an alias for Int32 in C# language." }, { "code": null, "e": 1168, "s": 1155, "text": "Int32 x = 5;" }, { "code": null, "e": 1181, "s": 1168, "text": "Int32 x = 5;" }, { "code": null, "e": 1192, "s": 1181, "text": "int x = 5;" }, { "code": null, "e": 1203, "s": 1192, "text": "int x = 5;" }, { "code": null, "e": 1354, "s": 1203, "text": "So, in use both the above statements will hold a 32bit integer. They compile to the same code, so at execution time there is no difference whatsoever." }, { "code": null, "e": 1512, "s": 1354, "text": "The only minor difference is Int32 can be only used with System namespace. While validating the type of a value like mentioned above we can use Int32 or int." }, { "code": null, "e": 1565, "s": 1512, "text": "typeof(int) == typeof(Int32) == typeof(System.Int32)" }, { "code": null, "e": 1636, "s": 1565, "text": "The below example shows how an integer is declared using System.Int32." }, { "code": null, "e": 1647, "s": 1636, "text": " Live Demo" }, { "code": null, "e": 1825, "s": 1647, "text": "using System;\nnamespace DemoApplication{\n class Program{\n static void Main(string[] args){\n Int32 x = 5;\n Console.WriteLine(x); //Output: 5\n }\n }\n}" }, { "code": null, "e": 1827, "s": 1825, "text": "5" }, { "code": null, "e": 1897, "s": 1827, "text": "The below example shows how an integer is declared using int keyword." }, { "code": null, "e": 1908, "s": 1897, "text": " Live Demo" }, { "code": null, "e": 2084, "s": 1908, "text": "using System;\nnamespace DemoApplication{\n class Program{\n static void Main(string[] args){\n int x = 5;\n Console.WriteLine(x); //Output: 5\n }\n }\n}" }, { "code": null, "e": 2086, "s": 2084, "text": "5" } ]
Betweenness Centrality (Centrality Measure) - GeeksforGeeks
10 Feb, 2018 In graph theory, betweenness centrality is a measure of centrality in a graph based on shortest paths. For every pair of vertices in a connected graph, there exists at least one shortest path between the vertices such that either the number of edges that the path passes through (for unweighted graphs) or the sum of the weights of the edges (for weighted graphs) is minimized. The betweenness centrality for each vertex is the number of these shortest paths that pass through the vertex. Betweenness centrality finds wide application in network theory: it represents the degree of which nodes stand between each other. For example, in a telecommunications network, a node with higher betweenness centrality would have more control over the network, because more information will pass through that node. Betweenness centrality was devised as a general measure of centrality: it applies to a wide range of problems in network theory, including problems related to social networks, biology, transport and scientific cooperation. Definition The betweenness centrality of a node {\displaystyle v} v is given by the expression: where is the total number of shortest paths from node to node and is the number of those paths that pass through . Note that the betweenness centrality of a node scales with the number of pairs of nodes as implied by the summation indices. Therefore, the calculation may be rescaled by dividing through by the number of pairs of nodes not including , so that . The division is done by for directed graphs and for undirected graphs, where is the number of nodes in the giant component. Note that this scales for the highest possible value, where one node is crossed by every single shortest path. This is often not the case, and a normalization can be performed without a loss of precision which results in: Note that this will always be a scaling from a smaller range into a larger range, so no precision is lost. Weighted NetworksIn a weighted network the links connecting the nodes are no longer treated as binary interactions, but are weighted in proportion to their capacity, influence, frequency, etc., which adds another dimension of heterogeneity within the network beyond the topological effects. A node’s strength in a weighted network is given by the sum of the weights of its adjacent edges. With and being adjacency and weight matrices between nodes and , respectively. Analogous to the power law distribution of degree found in scale free networks, the strength of a given node follows a power law distribution as well. A study of the average value of the strength for vertices with betweenness shows that the functional behavior can be approximated by a scaling form Following is the code for the calculation of the betweenness centrality of the graph and its various nodes. def betweenness_centrality(G, k=None, normalized=True, weight=None, endpoints=False, seed=None): r"""Compute the shortest-path betweenness centrality for nodes. Betweenness centrality of a node $v$ is the sum of the fraction of all-pairs shortest paths that pass through $v$ .. math:: c_B(v) =\sum_{s,t \in V} \frac{\sigma(s, t|v)}{\sigma(s, t)} where $V$ is the set of nodes, $\sigma(s, t)$ is the number of shortest $(s, t)$-paths, and $\sigma(s, t|v)$ is the number of those paths passing through some node $v$ other than $s, t$. If $s = t$, $\sigma(s, t) = 1$, and if $v \in {s, t}$, $\sigma(s, t|v) = 0$ [2]_. Parameters ---------- G : graph A NetworkX graph. k : int, optional (default=None) If k is not None use k node samples to estimate betweenness. The value of k <= n where n is the number of nodes in the graph. Higher values give better approximation. normalized : bool, optional If True the betweenness values are normalized by `2/((n-1)(n-2))` for graphs, and `1/((n-1)(n-2))` for directed graphs where `n` is the number of nodes in G. weight : None or string, optional (default=None) If None, all edge weights are considered equal. Otherwise holds the name of the edge attribute used as weight. endpoints : bool, optional If True include the endpoints in the shortest path counts. Returns ------- nodes : dictionary Dictionary of nodes with betweenness centrality as the value. Notes ----- The algorithm is from Ulrik Brandes [1]_. See [4]_ for the original first published version and [2]_ for details on algorithms for variations and related metrics. For approximate betweenness calculations set k=#samples to use k nodes ("pivots") to estimate the betweenness values. For an estimate of the number of pivots needed see [3]_. For weighted graphs the edge weights must be greater than zero. Zero edge weights can produce an infinite number of equal length paths between pairs of nodes. """ betweenness = dict.fromkeys(G, 0.0) # b[v]=0 for v in G if k is None: nodes = G else: random.seed(seed) nodes = random.sample(G.nodes(), k) for s in nodes: # single source shortest paths if weight is None: # use BFS S, P, sigma = _single_source_shortest_path_basic(G, s) else: # use Dijkstra's algorithm S, P, sigma = _single_source_dijkstra_path_basic(G, s, weight) # accumulation if endpoints: betweenness = _accumulate_endpoints(betweenness, S, P, sigma, s) else: betweenness = _accumulate_basic(betweenness, S, P, sigma, s) # rescaling betweenness = _rescale(betweenness, len(G), normalized=normalized, directed=G.is_directed(), k=k) return betweenness The above function is invoked using the networkx library and once the library is installed, you can eventually use it and the following code has to be written in python for the implementation of the betweenness centrality of a node. >>> import networkx as nx>>> G=nx.erdos_renyi_graph(50,0.5)>>> b=nx.betweenness_centrality(G)>>> print(b) The result of it is: {0: 0.01220586070437195, 1: 0.009125402885768874, 2: 0.010481510111098788, 3: 0.014645690907182346, 4: 0.013407129955492722, 5: 0.008165902336070403, 6: 0.008515486873573529, 7: 0.0067362883337957575, 8: 0.009167651113672941, 9: 0.012386122359980324, 10: 0.00711685931010503, 11: 0.01146358835858978, 12: 0.010392276809830674, 13: 0.0071149912635190965, 14: 0.011112503660641336, 15: 0.008013362669468532, 16: 0.01332441710128969, 17: 0.009307485134691016, 18: 0.006974541084171777, 19: 0.006534636068324543, 20: 0.007794762718607258, 21: 0.012297442232146375, 22: 0.011081427155225095, 23: 0.018715475770172643, 24: 0.011527827410298818, 25: 0.012294312339823964, 26: 0.008103941622217354, 27: 0.011063824792934858, 28: 0.00876321613116331, 29: 0.01539738650994337, 30: 0.014968892689224241, 31: 0.006942569786325711, 32: 0.01389881951343378, 33: 0.005315473883526104, 34: 0.012485048548223817, 35: 0.009147849010405877, 36: 0.00755662592209711, 37: 0.007387027127423285, 38: 0.015993065123210606, 39: 0.0111516804297535, 40: 0.010720274864419366, 41: 0.007769933231367805, 42: 0.009986222659285306, 43: 0.005102869708942402, 44: 0.007652686310399397, 45: 0.017408689421606432, 46: 0.008512679806690831, 47: 0.01027761151708757, 48: 0.008908600658162324, 49: 0.013439198921385216} The above result is a dictionary depicting the value of betweenness centrality of each node. The above is an extension of my article series on the centrality measures. Keep networking!!! ReferencesYou can read more about the same at https://en.wikipedia.org/wiki/Betweenness_centrality http://networkx.readthedocs.io/en/networkx-1.10/index.html.This article is contributed by Jayant Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes arrow_drop_upSave . This article is contributed by Jayant Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Engineering Mathematics Graph Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inequalities in LaTeX Activation Functions Arrow Symbols in LaTeX Newton's Divided Difference Interpolation Formula Set Notations in LaTeX Breadth First Search or BFS for a Graph Depth First Search or DFS for a Graph 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
[ { "code": null, "e": 31467, "s": 31439, "text": "\n10 Feb, 2018" }, { "code": null, "e": 31956, "s": 31467, "text": "In graph theory, betweenness centrality is a measure of centrality in a graph based on shortest paths. For every pair of vertices in a connected graph, there exists at least one shortest path between the vertices such that either the number of edges that the path passes through (for unweighted graphs) or the sum of the weights of the edges (for weighted graphs) is minimized. The betweenness centrality for each vertex is the number of these shortest paths that pass through the vertex." }, { "code": null, "e": 32494, "s": 31956, "text": "Betweenness centrality finds wide application in network theory: it represents the degree of which nodes stand between each other. For example, in a telecommunications network, a node with higher betweenness centrality would have more control over the network, because more information will pass through that node. Betweenness centrality was devised as a general measure of centrality: it applies to a wide range of problems in network theory, including problems related to social networks, biology, transport and scientific cooperation." }, { "code": null, "e": 32505, "s": 32494, "text": "Definition" }, { "code": null, "e": 32590, "s": 32505, "text": "The betweenness centrality of a node {\\displaystyle v} v is given by the expression:" }, { "code": null, "e": 32708, "s": 32590, "text": "where is the total number of shortest paths from node to node and is the number of those paths that pass through ." }, { "code": null, "e": 33285, "s": 32708, "text": "Note that the betweenness centrality of a node scales with the number of pairs of nodes as implied by the summation indices. Therefore, the calculation may be rescaled by dividing through by the number of pairs of nodes not including , so that . The division is done by for directed graphs and for undirected graphs, where is the number of nodes in the giant component. Note that this scales for the highest possible value, where one node is crossed by every single shortest path. This is often not the case, and a normalization can be performed without a loss of precision" }, { "code": null, "e": 33303, "s": 33285, "text": "which results in:" }, { "code": null, "e": 33410, "s": 33303, "text": "Note that this will always be a scaling from a smaller range into a larger range, so no precision is lost." }, { "code": null, "e": 33799, "s": 33410, "text": "Weighted NetworksIn a weighted network the links connecting the nodes are no longer treated as binary interactions, but are weighted in proportion to their capacity, influence, frequency, etc., which adds another dimension of heterogeneity within the network beyond the topological effects. A node’s strength in a weighted network is given by the sum of the weights of its adjacent edges." }, { "code": null, "e": 34031, "s": 33799, "text": "With and being adjacency and weight matrices between nodes and , respectively. Analogous to the power law distribution of degree found in scale free networks, the strength of a given node follows a power law distribution as well." }, { "code": null, "e": 34181, "s": 34031, "text": "A study of the average value of the strength for vertices with betweenness shows that the functional behavior can be approximated by a scaling form" }, { "code": null, "e": 34289, "s": 34181, "text": "Following is the code for the calculation of the betweenness centrality of the graph and its various nodes." }, { "code": "def betweenness_centrality(G, k=None, normalized=True, weight=None, endpoints=False, seed=None): r\"\"\"Compute the shortest-path betweenness centrality for nodes. Betweenness centrality of a node $v$ is the sum of the fraction of all-pairs shortest paths that pass through $v$ .. math:: c_B(v) =\\sum_{s,t \\in V} \\frac{\\sigma(s, t|v)}{\\sigma(s, t)} where $V$ is the set of nodes, $\\sigma(s, t)$ is the number of shortest $(s, t)$-paths, and $\\sigma(s, t|v)$ is the number of those paths passing through some node $v$ other than $s, t$. If $s = t$, $\\sigma(s, t) = 1$, and if $v \\in {s, t}$, $\\sigma(s, t|v) = 0$ [2]_. Parameters ---------- G : graph A NetworkX graph. k : int, optional (default=None) If k is not None use k node samples to estimate betweenness. The value of k <= n where n is the number of nodes in the graph. Higher values give better approximation. normalized : bool, optional If True the betweenness values are normalized by `2/((n-1)(n-2))` for graphs, and `1/((n-1)(n-2))` for directed graphs where `n` is the number of nodes in G. weight : None or string, optional (default=None) If None, all edge weights are considered equal. Otherwise holds the name of the edge attribute used as weight. endpoints : bool, optional If True include the endpoints in the shortest path counts. Returns ------- nodes : dictionary Dictionary of nodes with betweenness centrality as the value. Notes ----- The algorithm is from Ulrik Brandes [1]_. See [4]_ for the original first published version and [2]_ for details on algorithms for variations and related metrics. For approximate betweenness calculations set k=#samples to use k nodes (\"pivots\") to estimate the betweenness values. For an estimate of the number of pivots needed see [3]_. For weighted graphs the edge weights must be greater than zero. Zero edge weights can produce an infinite number of equal length paths between pairs of nodes. \"\"\" betweenness = dict.fromkeys(G, 0.0) # b[v]=0 for v in G if k is None: nodes = G else: random.seed(seed) nodes = random.sample(G.nodes(), k) for s in nodes: # single source shortest paths if weight is None: # use BFS S, P, sigma = _single_source_shortest_path_basic(G, s) else: # use Dijkstra's algorithm S, P, sigma = _single_source_dijkstra_path_basic(G, s, weight) # accumulation if endpoints: betweenness = _accumulate_endpoints(betweenness, S, P, sigma, s) else: betweenness = _accumulate_basic(betweenness, S, P, sigma, s) # rescaling betweenness = _rescale(betweenness, len(G), normalized=normalized, directed=G.is_directed(), k=k) return betweenness", "e": 37240, "s": 34289, "text": null }, { "code": null, "e": 37473, "s": 37240, "text": "The above function is invoked using the networkx library and once the library is installed, you can eventually use it and the following code has to be written in python for the implementation of the betweenness centrality of a node." }, { "code": ">>> import networkx as nx>>> G=nx.erdos_renyi_graph(50,0.5)>>> b=nx.betweenness_centrality(G)>>> print(b)", "e": 37579, "s": 37473, "text": null }, { "code": null, "e": 37600, "s": 37579, "text": "The result of it is:" }, { "code": "{0: 0.01220586070437195, 1: 0.009125402885768874, 2: 0.010481510111098788, 3: 0.014645690907182346, 4: 0.013407129955492722, 5: 0.008165902336070403, 6: 0.008515486873573529, 7: 0.0067362883337957575, 8: 0.009167651113672941, 9: 0.012386122359980324, 10: 0.00711685931010503, 11: 0.01146358835858978, 12: 0.010392276809830674, 13: 0.0071149912635190965, 14: 0.011112503660641336, 15: 0.008013362669468532, 16: 0.01332441710128969, 17: 0.009307485134691016, 18: 0.006974541084171777, 19: 0.006534636068324543, 20: 0.007794762718607258, 21: 0.012297442232146375, 22: 0.011081427155225095, 23: 0.018715475770172643, 24: 0.011527827410298818, 25: 0.012294312339823964, 26: 0.008103941622217354, 27: 0.011063824792934858, 28: 0.00876321613116331, 29: 0.01539738650994337, 30: 0.014968892689224241, 31: 0.006942569786325711, 32: 0.01389881951343378, 33: 0.005315473883526104, 34: 0.012485048548223817, 35: 0.009147849010405877, 36: 0.00755662592209711, 37: 0.007387027127423285, 38: 0.015993065123210606, 39: 0.0111516804297535, 40: 0.010720274864419366, 41: 0.007769933231367805, 42: 0.009986222659285306, 43: 0.005102869708942402, 44: 0.007652686310399397, 45: 0.017408689421606432, 46: 0.008512679806690831, 47: 0.01027761151708757, 48: 0.008908600658162324, 49: 0.013439198921385216}", "e": 38882, "s": 37600, "text": null }, { "code": null, "e": 39069, "s": 38882, "text": "The above result is a dictionary depicting the value of betweenness centrality of each node. The above is an extension of my article series on the centrality measures. Keep networking!!!" }, { "code": null, "e": 39115, "s": 39069, "text": "ReferencesYou can read more about the same at" }, { "code": null, "e": 39168, "s": 39115, "text": "https://en.wikipedia.org/wiki/Betweenness_centrality" }, { "code": null, "e": 39686, "s": 39168, "text": "http://networkx.readthedocs.io/en/networkx-1.10/index.html.This article is contributed by Jayant Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 39688, "s": 39686, "text": "." }, { "code": null, "e": 39988, "s": 39688, "text": "This article is contributed by Jayant Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 40113, "s": 39988, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 40137, "s": 40113, "text": "Engineering Mathematics" }, { "code": null, "e": 40143, "s": 40137, "text": "Graph" }, { "code": null, "e": 40149, "s": 40143, "text": "Graph" }, { "code": null, "e": 40247, "s": 40149, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40269, "s": 40247, "text": "Inequalities in LaTeX" }, { "code": null, "e": 40290, "s": 40269, "text": "Activation Functions" }, { "code": null, "e": 40313, "s": 40290, "text": "Arrow Symbols in LaTeX" }, { "code": null, "e": 40363, "s": 40313, "text": "Newton's Divided Difference Interpolation Formula" }, { "code": null, "e": 40386, "s": 40363, "text": "Set Notations in LaTeX" }, { "code": null, "e": 40426, "s": 40386, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 40464, "s": 40426, "text": "Depth First Search or DFS for a Graph" }, { "code": null, "e": 40515, "s": 40464, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 40573, "s": 40515, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" } ]
Program to find Nth term in the series 0, 2, 1, 3, 1, 5, 2, 7, 3,... - GeeksforGeeks
15 Mar, 2021 Given a number N. The task is to write a program to find the N-th term in the below series: 0, 2, 1, 3, 1, 5, 2, 7, 3, ... Examples: Input: N = 5 Output: 1 Input: N = 10 Output: 11 When we look carefully at the series, we find that the series is a mixture of 2 series: Terms at odd positions in the given series forms fibonacci series.Terms at even positions in the given series forms a series of prime numbers. Terms at odd positions in the given series forms fibonacci series. Terms at even positions in the given series forms a series of prime numbers. Now, To solve the above-given problem, first check whether the input number N is even or odd. If it is odd, set N=(N/2) + 1(since there are Two series running parallelly) and find the Nth fibonacci number. If N is even, simply set N=N/2 and find Nth prime number. Below is the implementation of above approach: C++ Java Python 3 C# PHP Javascript // CPP program to find N-th term// in the series#include<bits/stdc++.h>#define MAX 1000using namespace std; // Function to find Nth Prime Numberint NthPrime(int n){ int count = 0; for (int i = 2; i <= MAX; i++) { int check = 0; for (int j = 2; j <= sqrt(i); j++) { if (i % j == 0) { check = 1; break; } } if (check == 0) count++; if (count == n) { return i; break; } }} // Function to find Nth Fibonacci Numberint NthFib(int n){ // Declare an array to store // Fibonacci numbers. int f[n + 2]; int i; // 0th and 1st number of the // series are 0 and 1 f[0] = 0; f[1] = 1; for (i = 2; i <= n; i++) { f[i] = f[i - 1] + f[i - 2]; } return f[n];} // Function to find N-th term// in the seriesvoid findNthTerm(int n){ // If n is even if (n % 2 == 0) { n = n / 2; n = NthPrime(n); cout << n << endl; } // If n is odd else { n = (n / 2) + 1; n = NthFib(n - 1); cout << n << endl; }} // Driver codeint main(){ int X = 5; findNthTerm(X); X = 10; findNthTerm(X); return 0;} // Java program to find N-th// term in the seriesclass GFG{ static int MAX = 1000; // Function to find Nth Prime Numberstatic int NthPrime(int n){int count = 0;int i;for (i = 2; i <= MAX; i++){ int check = 0; for (int j = 2; j <= Math.sqrt(i); j++) { if (i % j == 0) { check = 1; break; } } if (check == 0) count++; if (count == n) { return i; }} return 0;} // Function to find Nth Fibonacci Numberstatic int NthFib(int n){// Declare an array to store// Fibonacci numbers.int []f = new int[n + 2];int i; // 0th and 1st number of the// series are 0 and 1f[0] = 0;f[1] = 1; for (i = 2; i <= n; i++){ f[i] = f[i - 1] + f[i - 2];} return f[n];} // Function to find N-th term// in the seriesstatic void findNthTerm(int n){// If n is evenif (n % 2 == 0){ n = n / 2; n = NthPrime(n); System.out.println(n);} // If n is oddelse{ n = (n / 2) + 1; n = NthFib(n - 1); System.out.println(n);}} // Driver codepublic static void main(String[] args){ int X = 5; findNthTerm(X); X = 10; findNthTerm(X);}} // This code is contributed// by ChitraNayal # Python 3 program to find N-th# term in the series # import sqrt method from math modulefrom math import sqrt # Globally declare constant valueMAX = 1000 # Function to find Nth Prime Numberdef NthPrime(n) : count = 0 for i in range(2, MAX + 1) : check = 0 for j in range(2, int(sqrt(i)) + 1) : if i % j == 0 : check = 1 break if check == 0 : count += 1 if count == n : return i break # Function to find Nth Fibonacci Numberdef NthFib(n) : # Create a list of size n+2 # to store Fibonacci numbers. f = [0] * (n + 2) # 0th and 1st number of the # series are 0 and 1 f[0], f[1] = 0, 1 for i in range(2, n + 1) : f[i] = f[i - 1] + f[i - 2] return f[n] # Function to find N-th# term in the seriesdef findNthTerm(n) : # If n is even if n % 2 == 0 : n //= 2 n = NthPrime(n) print(n) # If n is odd else : n = (n // 2) + 1 n = NthFib(n - 1) print(n) # Driver codeif __name__ == "__main__" : X = 5 # function calling findNthTerm(X) X = 10 findNthTerm(X) # This code is contributed by ANKITRAI1 // C# program to find N-th term// in the seriesusing System; class GFG{static int MAX = 1000; // Function to find Nth Prime Numberstatic int NthPrime(int n){int count = 0;int i;for ( i = 2; i <= MAX; i++){ int check = 0; for (int j = 2; j <= Math.Sqrt(i); j++) { if (i % j == 0) { check = 1; break; } } if (check == 0) count++; if (count == n) { return i; }} return 0;} // Function to find Nth Fibonacci Numberstatic int NthFib(int n){ // Declare an array to store// Fibonacci numbers.int []f = new int[n + 2];int i; // 0th and 1st number of the// series are 0 and 1f[0] = 0;f[1] = 1; for (i = 2; i <= n; i++){ f[i] = f[i - 1] + f[i - 2];} return f[n];} // Function to find N-th term// in the seriesstatic void findNthTerm(int n){// If n is evenif (n % 2 == 0){ n = n / 2; n = NthPrime(n); Console.WriteLine(n);} // If n is oddelse{ n = (n / 2) + 1; n = NthFib(n - 1); Console.WriteLine(n);}} // Driver codepublic static void Main(){ int X = 5; findNthTerm(X); X = 10; findNthTerm(X);}} // This code is contributed// by ChitraNayal <?php// PHP program to find// N-th term in the series$MAX = 1000; // Function to find// Nth Prime Numberfunction NthPrime($n){ global $MAX; $count = 0; for ($i = 2; $i <= $MAX; $i++) { $check = 0; for ($j = 2; $j <= sqrt($i); $j++) { if ($i % $j == 0) { $check = 1; break; } } if ($check == 0) $count++; if ($count == $n) { return $i; break; } }} // Function to find// Nth Fibonacci Numberfunction NthFib($n){ // Declare an array to store // Fibonacci numbers. $f = array($n + 2); // 0th and 1st number of // the series are 0 and 1 $f[0] = 0; $f[1] = 1; for ($i = 2; $i <= $n; $i++) { $f[$i] = $f[$i - 1] + $f[$i - 2]; } return $f[$n];} // Function to find N-th// term in the seriesfunction findNthTerm($n){ // If n is even if ($n % 2 == 0) { $n = $n / 2; $n = NthPrime($n); echo $n . "\n"; } // If n is odd else { $n = ($n / 2) + 1; $n = NthFib($n - 1); echo $n . "\n"; }} // Driver code$X = 5;findNthTerm($X); $X = 10;findNthTerm($X); // This Code is contributed// by mits?> <script> // JavaScript program to find N-th term// in the series let MAX =1000;// Function to find Nth Prime Numberfunction NthPrime( n){ let count = 0; for (let i = 2; i <= MAX; i++) { let check = 0; for (let j = 2; j <= Math.sqrt(i); j++) { if (i % j == 0) { check = 1; break; } } if (check == 0) count++; if (count == n) { return i; break; } }} // Function to find Nth Fibonacci Numberfunction NthFib( n){ // Declare an array to store // Fibonacci numbers. var f=new Int16Array(n+2).fill(0); let i; // 0th and 1st number of the // series are 0 and 1 f[0] = 0; f[1] = 1; for (i = 2; i <= n; i++) { f[i] = f[i - 1] + f[i - 2]; } return f[n];} // Function to find N-th term// in the seriesfunction findNthTerm( n){ // If n is even if (n % 2 == 0) { n = n / 2; n = NthPrime(n); document.write(n +"<br/>"); } // If n is odd else { n = parseInt(n / 2) + 1; n = NthFib(n - 1); document.write(n +"<br/>"); }} // Driver code let X = 5; findNthTerm(X); X = 10; findNthTerm(X); // This code contributed by aashish1995 </script> 1 11 Mithun Kumar ankthon ukasp aashish1995 Fibonacci Prime Number series Mathematical School Programming Mathematical Prime Number series Fibonacci Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Modulo Operator (%) in C/C++ with Examples Print all possible combinations of r elements in a given array of size n The Knight's tour problem | Backtracking-1 Operators in C / C++ Program for factorial of a number Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26583, "s": 26555, "text": "\n15 Mar, 2021" }, { "code": null, "e": 26677, "s": 26583, "text": "Given a number N. The task is to write a program to find the N-th term in the below series: " }, { "code": null, "e": 26710, "s": 26677, "text": "0, 2, 1, 3, 1, 5, 2, 7, 3, ... " }, { "code": null, "e": 26722, "s": 26710, "text": "Examples: " }, { "code": null, "e": 26771, "s": 26722, "text": "Input: N = 5\nOutput: 1\n\nInput: N = 10\nOutput: 11" }, { "code": null, "e": 26863, "s": 26773, "text": "When we look carefully at the series, we find that the series is a mixture of 2 series: " }, { "code": null, "e": 27007, "s": 26863, "text": "Terms at odd positions in the given series forms fibonacci series.Terms at even positions in the given series forms a series of prime numbers. " }, { "code": null, "e": 27074, "s": 27007, "text": "Terms at odd positions in the given series forms fibonacci series." }, { "code": null, "e": 27152, "s": 27074, "text": "Terms at even positions in the given series forms a series of prime numbers. " }, { "code": null, "e": 27248, "s": 27152, "text": "Now, To solve the above-given problem, first check whether the input number N is even or odd. " }, { "code": null, "e": 27360, "s": 27248, "text": "If it is odd, set N=(N/2) + 1(since there are Two series running parallelly) and find the Nth fibonacci number." }, { "code": null, "e": 27418, "s": 27360, "text": "If N is even, simply set N=N/2 and find Nth prime number." }, { "code": null, "e": 27467, "s": 27418, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 27471, "s": 27467, "text": "C++" }, { "code": null, "e": 27476, "s": 27471, "text": "Java" }, { "code": null, "e": 27485, "s": 27476, "text": "Python 3" }, { "code": null, "e": 27488, "s": 27485, "text": "C#" }, { "code": null, "e": 27492, "s": 27488, "text": "PHP" }, { "code": null, "e": 27503, "s": 27492, "text": "Javascript" }, { "code": "// CPP program to find N-th term// in the series#include<bits/stdc++.h>#define MAX 1000using namespace std; // Function to find Nth Prime Numberint NthPrime(int n){ int count = 0; for (int i = 2; i <= MAX; i++) { int check = 0; for (int j = 2; j <= sqrt(i); j++) { if (i % j == 0) { check = 1; break; } } if (check == 0) count++; if (count == n) { return i; break; } }} // Function to find Nth Fibonacci Numberint NthFib(int n){ // Declare an array to store // Fibonacci numbers. int f[n + 2]; int i; // 0th and 1st number of the // series are 0 and 1 f[0] = 0; f[1] = 1; for (i = 2; i <= n; i++) { f[i] = f[i - 1] + f[i - 2]; } return f[n];} // Function to find N-th term// in the seriesvoid findNthTerm(int n){ // If n is even if (n % 2 == 0) { n = n / 2; n = NthPrime(n); cout << n << endl; } // If n is odd else { n = (n / 2) + 1; n = NthFib(n - 1); cout << n << endl; }} // Driver codeint main(){ int X = 5; findNthTerm(X); X = 10; findNthTerm(X); return 0;}", "e": 28725, "s": 27503, "text": null }, { "code": "// Java program to find N-th// term in the seriesclass GFG{ static int MAX = 1000; // Function to find Nth Prime Numberstatic int NthPrime(int n){int count = 0;int i;for (i = 2; i <= MAX; i++){ int check = 0; for (int j = 2; j <= Math.sqrt(i); j++) { if (i % j == 0) { check = 1; break; } } if (check == 0) count++; if (count == n) { return i; }} return 0;} // Function to find Nth Fibonacci Numberstatic int NthFib(int n){// Declare an array to store// Fibonacci numbers.int []f = new int[n + 2];int i; // 0th and 1st number of the// series are 0 and 1f[0] = 0;f[1] = 1; for (i = 2; i <= n; i++){ f[i] = f[i - 1] + f[i - 2];} return f[n];} // Function to find N-th term// in the seriesstatic void findNthTerm(int n){// If n is evenif (n % 2 == 0){ n = n / 2; n = NthPrime(n); System.out.println(n);} // If n is oddelse{ n = (n / 2) + 1; n = NthFib(n - 1); System.out.println(n);}} // Driver codepublic static void main(String[] args){ int X = 5; findNthTerm(X); X = 10; findNthTerm(X);}} // This code is contributed// by ChitraNayal", "e": 29887, "s": 28725, "text": null }, { "code": "# Python 3 program to find N-th# term in the series # import sqrt method from math modulefrom math import sqrt # Globally declare constant valueMAX = 1000 # Function to find Nth Prime Numberdef NthPrime(n) : count = 0 for i in range(2, MAX + 1) : check = 0 for j in range(2, int(sqrt(i)) + 1) : if i % j == 0 : check = 1 break if check == 0 : count += 1 if count == n : return i break # Function to find Nth Fibonacci Numberdef NthFib(n) : # Create a list of size n+2 # to store Fibonacci numbers. f = [0] * (n + 2) # 0th and 1st number of the # series are 0 and 1 f[0], f[1] = 0, 1 for i in range(2, n + 1) : f[i] = f[i - 1] + f[i - 2] return f[n] # Function to find N-th# term in the seriesdef findNthTerm(n) : # If n is even if n % 2 == 0 : n //= 2 n = NthPrime(n) print(n) # If n is odd else : n = (n // 2) + 1 n = NthFib(n - 1) print(n) # Driver codeif __name__ == \"__main__\" : X = 5 # function calling findNthTerm(X) X = 10 findNthTerm(X) # This code is contributed by ANKITRAI1", "e": 31123, "s": 29887, "text": null }, { "code": "// C# program to find N-th term// in the seriesusing System; class GFG{static int MAX = 1000; // Function to find Nth Prime Numberstatic int NthPrime(int n){int count = 0;int i;for ( i = 2; i <= MAX; i++){ int check = 0; for (int j = 2; j <= Math.Sqrt(i); j++) { if (i % j == 0) { check = 1; break; } } if (check == 0) count++; if (count == n) { return i; }} return 0;} // Function to find Nth Fibonacci Numberstatic int NthFib(int n){ // Declare an array to store// Fibonacci numbers.int []f = new int[n + 2];int i; // 0th and 1st number of the// series are 0 and 1f[0] = 0;f[1] = 1; for (i = 2; i <= n; i++){ f[i] = f[i - 1] + f[i - 2];} return f[n];} // Function to find N-th term// in the seriesstatic void findNthTerm(int n){// If n is evenif (n % 2 == 0){ n = n / 2; n = NthPrime(n); Console.WriteLine(n);} // If n is oddelse{ n = (n / 2) + 1; n = NthFib(n - 1); Console.WriteLine(n);}} // Driver codepublic static void Main(){ int X = 5; findNthTerm(X); X = 10; findNthTerm(X);}} // This code is contributed// by ChitraNayal", "e": 32278, "s": 31123, "text": null }, { "code": "<?php// PHP program to find// N-th term in the series$MAX = 1000; // Function to find// Nth Prime Numberfunction NthPrime($n){ global $MAX; $count = 0; for ($i = 2; $i <= $MAX; $i++) { $check = 0; for ($j = 2; $j <= sqrt($i); $j++) { if ($i % $j == 0) { $check = 1; break; } } if ($check == 0) $count++; if ($count == $n) { return $i; break; } }} // Function to find// Nth Fibonacci Numberfunction NthFib($n){ // Declare an array to store // Fibonacci numbers. $f = array($n + 2); // 0th and 1st number of // the series are 0 and 1 $f[0] = 0; $f[1] = 1; for ($i = 2; $i <= $n; $i++) { $f[$i] = $f[$i - 1] + $f[$i - 2]; } return $f[$n];} // Function to find N-th// term in the seriesfunction findNthTerm($n){ // If n is even if ($n % 2 == 0) { $n = $n / 2; $n = NthPrime($n); echo $n . \"\\n\"; } // If n is odd else { $n = ($n / 2) + 1; $n = NthFib($n - 1); echo $n . \"\\n\"; }} // Driver code$X = 5;findNthTerm($X); $X = 10;findNthTerm($X); // This Code is contributed// by mits?>", "e": 33561, "s": 32278, "text": null }, { "code": "<script> // JavaScript program to find N-th term// in the series let MAX =1000;// Function to find Nth Prime Numberfunction NthPrime( n){ let count = 0; for (let i = 2; i <= MAX; i++) { let check = 0; for (let j = 2; j <= Math.sqrt(i); j++) { if (i % j == 0) { check = 1; break; } } if (check == 0) count++; if (count == n) { return i; break; } }} // Function to find Nth Fibonacci Numberfunction NthFib( n){ // Declare an array to store // Fibonacci numbers. var f=new Int16Array(n+2).fill(0); let i; // 0th and 1st number of the // series are 0 and 1 f[0] = 0; f[1] = 1; for (i = 2; i <= n; i++) { f[i] = f[i - 1] + f[i - 2]; } return f[n];} // Function to find N-th term// in the seriesfunction findNthTerm( n){ // If n is even if (n % 2 == 0) { n = n / 2; n = NthPrime(n); document.write(n +\"<br/>\"); } // If n is odd else { n = parseInt(n / 2) + 1; n = NthFib(n - 1); document.write(n +\"<br/>\"); }} // Driver code let X = 5; findNthTerm(X); X = 10; findNthTerm(X); // This code contributed by aashish1995 </script>", "e": 34843, "s": 33561, "text": null }, { "code": null, "e": 34848, "s": 34843, "text": "1\n11" }, { "code": null, "e": 34863, "s": 34850, "text": "Mithun Kumar" }, { "code": null, "e": 34871, "s": 34863, "text": "ankthon" }, { "code": null, "e": 34877, "s": 34871, "text": "ukasp" }, { "code": null, "e": 34889, "s": 34877, "text": "aashish1995" }, { "code": null, "e": 34899, "s": 34889, "text": "Fibonacci" }, { "code": null, "e": 34912, "s": 34899, "text": "Prime Number" }, { "code": null, "e": 34919, "s": 34912, "text": "series" }, { "code": null, "e": 34932, "s": 34919, "text": "Mathematical" }, { "code": null, "e": 34951, "s": 34932, "text": "School Programming" }, { "code": null, "e": 34964, "s": 34951, "text": "Mathematical" }, { "code": null, "e": 34977, "s": 34964, "text": "Prime Number" }, { "code": null, "e": 34984, "s": 34977, "text": "series" }, { "code": null, "e": 34994, "s": 34984, "text": "Fibonacci" }, { "code": null, "e": 35092, "s": 34994, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35135, "s": 35092, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 35208, "s": 35135, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 35251, "s": 35208, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 35272, "s": 35251, "text": "Operators in C / C++" }, { "code": null, "e": 35306, "s": 35272, "text": "Program for factorial of a number" }, { "code": null, "e": 35324, "s": 35306, "text": "Python Dictionary" }, { "code": null, "e": 35340, "s": 35324, "text": "Arrays in C/C++" }, { "code": null, "e": 35359, "s": 35340, "text": "Inheritance in C++" }, { "code": null, "e": 35384, "s": 35359, "text": "Reverse a string in Java" } ]
Find the index of an array element in Java - GeeksforGeeks
27 Oct, 2021 Given an array of N elements and an element K, find the index of an array element in Java. Examples: Input: a[] = { 5, 4, 6, 1, 3, 2, 7, 8, 9 }, K = 5 Output: 0 Input: a[] = { 5, 4, 6, 1, 3, 2, 7, 8, 9 }, K = 7 Output: 6 An element in an array of N integers can be searched using the below-mentioned methods. Linear Search: Doing a linear search in an array, the element can be found in O(N) complexity. Below is the implementation of the linear-search approach: Linear Search: Doing a linear search in an array, the element can be found in O(N) complexity. Below is the implementation of the linear-search approach: Java // Java program to find index of// an element in N elementsimport java.util.*;public class index { // Linear-search function to find the index of an element public static int findIndex(int arr[], int t) { // if array is Null if (arr == null) { return -1; } // find length of array int len = arr.length; int i = 0; // traverse in the array while (i < len) { // if the i-th element is t // then return the index if (arr[i] == t) { return i; } else { i = i + 1; } } return -1; } // Driver Code public static void main(String[] args) { int[] my_array = { 5, 4, 6, 1, 3, 2, 7, 8, 9 }; // find the index of 5 System.out.println("Index position of 5 is: " + findIndex(my_array, 5)); // find the index of 7 System.out.println("Index position of 7 is: " + findIndex(my_array, 7)); }} Index position of 5 is: 0 Index position of 7 is: 6 2. Binary search: Binary search can also be used to find the index of the array element in an array. But the binary search can only be used if the array is sorted. Java provides us with an inbuilt function which can be found in the Arrays library of Java which will return the index if the element is present, else it returns -1. The complexity will be O(log n). Below is the implementation of Binary search. Java // Java program to find index of// an element in N elementsimport java.util.Arrays; public class index { // Function to find the index of an element public static int findIndex(int arr[], int t) { int index = Arrays.binarySearch(arr, t); return (index < 0) ? -1 : index; } // Driver Code public static void main(String[] args) { int[] my_array = { 1, 2, 3, 4, 5, 6, 7 }; // find the index of 5 System.out.println("Index position of 5 is: " + findIndex(my_array, 5)); // find the index of 7 System.out.println("Index position of 7 is: " + findIndex(my_array, 7)); }} Index position of 5 is: 4 Index position of 7 is: 6 3. Guava: Guava is an open source, Java-based library developed by Google. It provides utility methods for collections, caching, primitives support, concurrency, common annotations, string processing, I/O, and validations. Guava provides several-utility class pertaining to be primitive like Ints for int, Longs for long, Doubles for double etc. Each utility class has an indexOf() method that returns the index of the first appearance of the element in array.Below is the implementation of Guava. Java // Java program to find index of// an element in N elementsimport java.util.List;import com.google.common.primitives.Ints;public class index { // Function to find the index of an element using public static int findIndex(int arr[], int t) { return Ints.indexOf(arr, t); } // Driver Code public static void main(String[] args) { int[] my_array = { 5, 4, 6, 1, 3, 2, 7, 8, 9 }; System.out.println("Index position of 5 is: " + findIndex(my_array, 5)); System.out.println("Index position of 7 is: " + findIndex(my_array, 7)); }} Index position of 5 is: 0 Index position of 7 is: 6 4. Stream API: Stream is a new abstract layer introduced in Java 8. Using stream, you can process data in a declarative way similar to SQL statements. The stream represents a sequence of objects from a source, which supports aggregate operations. In order to find the index of an element Stream package provides utility, IntStream. Using the length of an array we can get an IntStream of array indices from 0 to n-1, where n is the length of an array.Below is the implementation of Stream API approach. Java // Java program to find index of// an element in N elementsimport java.util.stream.IntStream;public class index { // Function to find the index of an element public static int findIndex(int arr[], int t) { int len = arr.length; return IntStream.range(0, len) .filter(i -> t == arr[i]) .findFirst() // first occurrence .orElse(-1); // No element found } public static void main(String[] args) { int[] my_array = { 5, 4, 6, 1, 3, 2, 7, 8, 9 }; System.out.println("Index position of 5 is: " + findIndex(my_array, 5)); System.out.println("Index position of 7 is: " + findIndex(my_array, 7)); }} Index position of 5 is: 0 Index position of 7 is: 6 5. Using ArrayList In this approach, we will convert the array into ArrayList, and then we will use the indexOf method of ArrayList to get the index of the element. Java // Java program for the above approachimport java.util.ArrayList; public class GFG { public static int findIndex(int arr[], int t) { // Creating ArrayList ArrayList<Integer> clist = new ArrayList<>(); // adding elements of array // to ArrayList for (int i : arr) clist.add(i); // returning index of the element return clist.indexOf(t); } // Driver program public static void main(String[] args) { int[] my_array = { 5, 4, 6, 1, 3, 2, 7, 8, 9 }; System.out.println("Index position of 5 is: " + findIndex(my_array, 5)); System.out.println("Index position of 7 is: " + findIndex(my_array, 7)); }} Output: Index position of 5 is: 0 Index position of 7 is: 6 6. Using Recursion We will use recursion to find the first index of the given element. Java // Java program for the above approachpublic class GFG { public static int index(int arr[], int t, int start) { // base case when // start equals the length of the // array we return -1 if(start==arr.length) return -1; // if element at index start equals t // we return start if(arr[start]==t) return start; // we find for the rest // position in the array return index(arr,t,start+1); } public static int findIndex(int arr[], int t) { return index(arr,t,0); } // Driver Code public static void main(String[] args) { int[] my_array = { 5, 4, 6, 1, 3, 2, 7, 8, 9 }; System.out.println("Index position of 5 is: " + findIndex(my_array, 5)); System.out.println("Index position of 7 is: " + findIndex(my_array, 7)); }} Output: Index position of 5 is: 0 Index position of 7 is: 6 nidhi_biet le0 surindertarika1234 Binary Search Java-Array-Programs Java-Arrays java-guava java-stream Java-Stream-programs Picked Java Searching Searching Java Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java Binary Search Maximum and minimum of an array using minimum number of comparisons Linear Search Search an element in a sorted and rotated array Find the Missing Number
[ { "code": null, "e": 26338, "s": 26310, "text": "\n27 Oct, 2021" }, { "code": null, "e": 26440, "s": 26338, "text": "Given an array of N elements and an element K, find the index of an array element in Java. Examples: " }, { "code": null, "e": 26561, "s": 26440, "text": "Input: a[] = { 5, 4, 6, 1, 3, 2, 7, 8, 9 }, K = 5\nOutput: 0\n\nInput: a[] = { 5, 4, 6, 1, 3, 2, 7, 8, 9 }, K = 7\nOutput: 6" }, { "code": null, "e": 26651, "s": 26561, "text": "An element in an array of N integers can be searched using the below-mentioned methods. " }, { "code": null, "e": 26805, "s": 26651, "text": "Linear Search: Doing a linear search in an array, the element can be found in O(N) complexity. Below is the implementation of the linear-search approach:" }, { "code": null, "e": 26959, "s": 26805, "text": "Linear Search: Doing a linear search in an array, the element can be found in O(N) complexity. Below is the implementation of the linear-search approach:" }, { "code": null, "e": 26964, "s": 26959, "text": "Java" }, { "code": "// Java program to find index of// an element in N elementsimport java.util.*;public class index { // Linear-search function to find the index of an element public static int findIndex(int arr[], int t) { // if array is Null if (arr == null) { return -1; } // find length of array int len = arr.length; int i = 0; // traverse in the array while (i < len) { // if the i-th element is t // then return the index if (arr[i] == t) { return i; } else { i = i + 1; } } return -1; } // Driver Code public static void main(String[] args) { int[] my_array = { 5, 4, 6, 1, 3, 2, 7, 8, 9 }; // find the index of 5 System.out.println(\"Index position of 5 is: \" + findIndex(my_array, 5)); // find the index of 7 System.out.println(\"Index position of 7 is: \" + findIndex(my_array, 7)); }}", "e": 28035, "s": 26964, "text": null }, { "code": null, "e": 28087, "s": 28035, "text": "Index position of 5 is: 0\nIndex position of 7 is: 6" }, { "code": null, "e": 28499, "s": 28089, "text": "2. Binary search: Binary search can also be used to find the index of the array element in an array. But the binary search can only be used if the array is sorted. Java provides us with an inbuilt function which can be found in the Arrays library of Java which will return the index if the element is present, else it returns -1. The complexity will be O(log n). Below is the implementation of Binary search. " }, { "code": null, "e": 28504, "s": 28499, "text": "Java" }, { "code": "// Java program to find index of// an element in N elementsimport java.util.Arrays; public class index { // Function to find the index of an element public static int findIndex(int arr[], int t) { int index = Arrays.binarySearch(arr, t); return (index < 0) ? -1 : index; } // Driver Code public static void main(String[] args) { int[] my_array = { 1, 2, 3, 4, 5, 6, 7 }; // find the index of 5 System.out.println(\"Index position of 5 is: \" + findIndex(my_array, 5)); // find the index of 7 System.out.println(\"Index position of 7 is: \" + findIndex(my_array, 7)); }}", "e": 29199, "s": 28504, "text": null }, { "code": null, "e": 29251, "s": 29199, "text": "Index position of 5 is: 4\nIndex position of 7 is: 6" }, { "code": null, "e": 29752, "s": 29253, "text": "3. Guava: Guava is an open source, Java-based library developed by Google. It provides utility methods for collections, caching, primitives support, concurrency, common annotations, string processing, I/O, and validations. Guava provides several-utility class pertaining to be primitive like Ints for int, Longs for long, Doubles for double etc. Each utility class has an indexOf() method that returns the index of the first appearance of the element in array.Below is the implementation of Guava. " }, { "code": null, "e": 29757, "s": 29752, "text": "Java" }, { "code": "// Java program to find index of// an element in N elementsimport java.util.List;import com.google.common.primitives.Ints;public class index { // Function to find the index of an element using public static int findIndex(int arr[], int t) { return Ints.indexOf(arr, t); } // Driver Code public static void main(String[] args) { int[] my_array = { 5, 4, 6, 1, 3, 2, 7, 8, 9 }; System.out.println(\"Index position of 5 is: \" + findIndex(my_array, 5)); System.out.println(\"Index position of 7 is: \" + findIndex(my_array, 7)); }}", "e": 30386, "s": 29757, "text": null }, { "code": null, "e": 30438, "s": 30386, "text": "Index position of 5 is: 0\nIndex position of 7 is: 6" }, { "code": null, "e": 30944, "s": 30440, "text": "4. Stream API: Stream is a new abstract layer introduced in Java 8. Using stream, you can process data in a declarative way similar to SQL statements. The stream represents a sequence of objects from a source, which supports aggregate operations. In order to find the index of an element Stream package provides utility, IntStream. Using the length of an array we can get an IntStream of array indices from 0 to n-1, where n is the length of an array.Below is the implementation of Stream API approach. " }, { "code": null, "e": 30949, "s": 30944, "text": "Java" }, { "code": "// Java program to find index of// an element in N elementsimport java.util.stream.IntStream;public class index { // Function to find the index of an element public static int findIndex(int arr[], int t) { int len = arr.length; return IntStream.range(0, len) .filter(i -> t == arr[i]) .findFirst() // first occurrence .orElse(-1); // No element found } public static void main(String[] args) { int[] my_array = { 5, 4, 6, 1, 3, 2, 7, 8, 9 }; System.out.println(\"Index position of 5 is: \" + findIndex(my_array, 5)); System.out.println(\"Index position of 7 is: \" + findIndex(my_array, 7)); }}", "e": 31682, "s": 30949, "text": null }, { "code": null, "e": 31734, "s": 31682, "text": "Index position of 5 is: 0\nIndex position of 7 is: 6" }, { "code": null, "e": 31755, "s": 31736, "text": "5. Using ArrayList" }, { "code": null, "e": 31901, "s": 31755, "text": "In this approach, we will convert the array into ArrayList, and then we will use the indexOf method of ArrayList to get the index of the element." }, { "code": null, "e": 31906, "s": 31901, "text": "Java" }, { "code": "// Java program for the above approachimport java.util.ArrayList; public class GFG { public static int findIndex(int arr[], int t) { // Creating ArrayList ArrayList<Integer> clist = new ArrayList<>(); // adding elements of array // to ArrayList for (int i : arr) clist.add(i); // returning index of the element return clist.indexOf(t); } // Driver program public static void main(String[] args) { int[] my_array = { 5, 4, 6, 1, 3, 2, 7, 8, 9 }; System.out.println(\"Index position of 5 is: \" + findIndex(my_array, 5)); System.out.println(\"Index position of 7 is: \" + findIndex(my_array, 7)); }}", "e": 32660, "s": 31906, "text": null }, { "code": null, "e": 32668, "s": 32660, "text": "Output:" }, { "code": null, "e": 32720, "s": 32668, "text": "Index position of 5 is: 0\nIndex position of 7 is: 6" }, { "code": null, "e": 32739, "s": 32720, "text": "6. Using Recursion" }, { "code": null, "e": 32807, "s": 32739, "text": "We will use recursion to find the first index of the given element." }, { "code": null, "e": 32812, "s": 32807, "text": "Java" }, { "code": "// Java program for the above approachpublic class GFG { public static int index(int arr[], int t, int start) { // base case when // start equals the length of the // array we return -1 if(start==arr.length) return -1; // if element at index start equals t // we return start if(arr[start]==t) return start; // we find for the rest // position in the array return index(arr,t,start+1); } public static int findIndex(int arr[], int t) { return index(arr,t,0); } // Driver Code public static void main(String[] args) { int[] my_array = { 5, 4, 6, 1, 3, 2, 7, 8, 9 }; System.out.println(\"Index position of 5 is: \" + findIndex(my_array, 5)); System.out.println(\"Index position of 7 is: \" + findIndex(my_array, 7)); }}", "e": 33740, "s": 32812, "text": null }, { "code": null, "e": 33748, "s": 33740, "text": "Output:" }, { "code": null, "e": 33800, "s": 33748, "text": "Index position of 5 is: 0\nIndex position of 7 is: 6" }, { "code": null, "e": 33811, "s": 33800, "text": "nidhi_biet" }, { "code": null, "e": 33815, "s": 33811, "text": "le0" }, { "code": null, "e": 33834, "s": 33815, "text": "surindertarika1234" }, { "code": null, "e": 33848, "s": 33834, "text": "Binary Search" }, { "code": null, "e": 33868, "s": 33848, "text": "Java-Array-Programs" }, { "code": null, "e": 33880, "s": 33868, "text": "Java-Arrays" }, { "code": null, "e": 33891, "s": 33880, "text": "java-guava" }, { "code": null, "e": 33903, "s": 33891, "text": "java-stream" }, { "code": null, "e": 33924, "s": 33903, "text": "Java-Stream-programs" }, { "code": null, "e": 33931, "s": 33924, "text": "Picked" }, { "code": null, "e": 33936, "s": 33931, "text": "Java" }, { "code": null, "e": 33946, "s": 33936, "text": "Searching" }, { "code": null, "e": 33956, "s": 33946, "text": "Searching" }, { "code": null, "e": 33961, "s": 33956, "text": "Java" }, { "code": null, "e": 33975, "s": 33961, "text": "Binary Search" }, { "code": null, "e": 34073, "s": 33975, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34124, "s": 34073, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 34154, "s": 34124, "text": "HashMap in Java with Examples" }, { "code": null, "e": 34169, "s": 34154, "text": "Stream In Java" }, { "code": null, "e": 34188, "s": 34169, "text": "Interfaces in Java" }, { "code": null, "e": 34219, "s": 34188, "text": "How to iterate any Map in Java" }, { "code": null, "e": 34233, "s": 34219, "text": "Binary Search" }, { "code": null, "e": 34301, "s": 34233, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 34315, "s": 34301, "text": "Linear Search" }, { "code": null, "e": 34363, "s": 34315, "text": "Search an element in a sorted and rotated array" } ]
Data Structures | Tree Traversals | Question 11 - GeeksforGeeks
28 Jun, 2021 Let LASTPOST, LASTIN and LASTPRE denote the last vertex visited in a postorder, inorder and preorder traversal. Respectively, of a complete binary tree. Which of the following is always true? (GATE CS 2000)(A) LASTIN = LASTPOST(B) LASTIN = LASTPRE(C) LASTPRE = LASTPOST(D) None of the aboveAnswer: (D)Explanation: It is given that the given tree is complete binary tree. For a complete binary tree, the last visited node will always be same for inorder and preorder traversal. None of the above is true even for a complete binary tree. The option (a) is incorrect because the last node visited in Inorder traversal is right child and last node visited in Postorder traversal is root. The option (c) is incorrect because the last node visited in Preorder traversal is right child and last node visited in Postorder traversal is root. For option (b), see the following counter example. Thanks to Hunaif Muhammed for providing the correct explanation. 1 / \ 2 3 / \ / 4 5 6 Inorder traversal is 4 2 5 1 6 3 Preorder traversal is 1 2 4 5 3 6 Quiz of this Question Data Structures Data Structures-Tree Traversals Tree Traversals Data Structures Data Structures Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Data Structures | Linked List | Question 5 Data Structures | Linked List | Question 6 Difference between Singly linked list and Doubly linked list Advantages and Disadvantages of Linked List Data Structures | Graph | Question 9 FIFO vs LIFO approach in Programming C program to implement Adjacency Matrix of a given Graph Data Structures | Stack | Question 1 Introduction to Data Structures Binary Search Tree | Set 3 (Iterative Delete)
[ { "code": null, "e": 26275, "s": 26247, "text": "\n28 Jun, 2021" }, { "code": null, "e": 26811, "s": 26275, "text": "Let LASTPOST, LASTIN and LASTPRE denote the last vertex visited in a postorder, inorder and preorder traversal. Respectively, of a complete binary tree. Which of the following is always true? (GATE CS 2000)(A) LASTIN = LASTPOST(B) LASTIN = LASTPRE(C) LASTPRE = LASTPOST(D) None of the aboveAnswer: (D)Explanation: It is given that the given tree is complete binary tree. For a complete binary tree, the last visited node will always be same for inorder and preorder traversal. None of the above is true even for a complete binary tree." }, { "code": null, "e": 26959, "s": 26811, "text": "The option (a) is incorrect because the last node visited in Inorder traversal is right child and last node visited in Postorder traversal is root." }, { "code": null, "e": 27108, "s": 26959, "text": "The option (c) is incorrect because the last node visited in Preorder traversal is right child and last node visited in Postorder traversal is root." }, { "code": null, "e": 27224, "s": 27108, "text": "For option (b), see the following counter example. Thanks to Hunaif Muhammed for providing the correct explanation." }, { "code": null, "e": 27343, "s": 27224, "text": " 1\n / \\\n 2 3\n / \\ /\n4 5 6 \n\nInorder traversal is 4 2 5 1 6 3\nPreorder traversal is 1 2 4 5 3 6 \n" }, { "code": null, "e": 27365, "s": 27343, "text": "Quiz of this Question" }, { "code": null, "e": 27381, "s": 27365, "text": "Data Structures" }, { "code": null, "e": 27413, "s": 27381, "text": "Data Structures-Tree Traversals" }, { "code": null, "e": 27429, "s": 27413, "text": "Tree Traversals" }, { "code": null, "e": 27445, "s": 27429, "text": "Data Structures" }, { "code": null, "e": 27461, "s": 27445, "text": "Data Structures" }, { "code": null, "e": 27559, "s": 27461, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27602, "s": 27559, "text": "Data Structures | Linked List | Question 5" }, { "code": null, "e": 27645, "s": 27602, "text": "Data Structures | Linked List | Question 6" }, { "code": null, "e": 27706, "s": 27645, "text": "Difference between Singly linked list and Doubly linked list" }, { "code": null, "e": 27750, "s": 27706, "text": "Advantages and Disadvantages of Linked List" }, { "code": null, "e": 27787, "s": 27750, "text": "Data Structures | Graph | Question 9" }, { "code": null, "e": 27824, "s": 27787, "text": "FIFO vs LIFO approach in Programming" }, { "code": null, "e": 27881, "s": 27824, "text": "C program to implement Adjacency Matrix of a given Graph" }, { "code": null, "e": 27918, "s": 27881, "text": "Data Structures | Stack | Question 1" }, { "code": null, "e": 27950, "s": 27918, "text": "Introduction to Data Structures" } ]
Is it possible to prevent users from taking screenshots of webpage ? - GeeksforGeeks
21 Nov, 2021 The screenshot is a feature of OS in windows. We can simply press the print screen ( print screen ) on the keyboard to take screenshots. If the keyboard doesn’t have prt sc key, we can use Fn + Windows logo key + Space Bar. Also, we can use Snip & Sketch or Snipping tool by pressing the Windows logo key + Shift + S and select an area for the screenshot. In MacOS, we can use Command + Shift + 3 and Command + Shift + 4 for taking screenshot. All these commands are controlled by our operating system, and we can’t disable or block them in the browser using HTML/CSS/JavaScript. So, we can’t prevent users from taking screenshots. Besides all these things if the user wants to get the content of our webpage, they can copy it, print it, use some third-party applications or take a picture of it using some other devices. So it’s very difficult to prevent users from taking screenshots or content of our webpage. We cannot stop this, but we can use some methods to avoid this all to some extent. Example 1: In this example, we will disable the printing option of our webpage. HTML <!DOCTYPE html><html lang="en"> <head> <style> /* We are stopping user from printing our webpage */ @media print { html, body { /* Hide the whole page */ display: none; } } </style></head> <body> <div> Python is a high-level, general-purpose and a very popular programming language. <br />Python programming language (latest Python 3)is being used in web development, <br />Machine Learning applications, along with all cutting edge technology in Software Industry.<br />Python Programming Language is very well suited for Beginners, <br />also for experienced programmers with other programming languages like C++ and Java.<br /> </div></body> </html> Output: This will simply output the content of our webpage but when we try to print it, we will get nothing. Printing will not work Example 2. In this example, we will change the text selection feature using CSS. HTML <!DOCTYPE html><html lang="en"> <head> <style> html { user-select: none; } </style></head> <body> <div> Python is a high-level, general-purpose and a very popular programming language. <br />Python programming language (latest Python 3)is being used in web development, <br />Machine Learning applications, along with all cutting edge technology in Software Industry.<br />Python Programming Language is very well suited for Beginners, <br />also for experienced programmers with other programming languages like C++ and Java.<br /> </div></body> </html> Output: This will stop the user from selecting and copying our text contents. copying is not happening Example 3. In this example, we will display a warning message to the user to not copy/steal/print/screenshot of our web page. HTML <!DOCTYPE html><html lang="en"> <head> <script> alert("Do not take screenshot of this page"); </script></head> <body> <div> Python is a high-level, general-purpose and a very popular programming language.<br /> Python programming language (latest Python 3) is being used in web development,<br /> Machine Learning applications, along with all cutting edge technology in Software Industry. </br />Python Programming Language is very well suited for Beginners, also for <br /> experienced programmers with other programming languages like C++ and Java.<br /> </div></body> </html> Output: This will show an alert message to the user that he should not take any screenshot of this webpage. warning alert message Example 4. In this example, we will add a copyright message of our webpage that will show all the content of this web page belongs to us, and it is strictly not allowed to use our content in any form. HTML <!DOCTYPE html><html lang="en"> <head> <style> /* Styling the footer */ footer { text-align: center; padding: 10px; background-color: green; color: white; } </style></head> <body> <div> Python is a high-level, general-purpose and a very popular programming language.<br /> Python programming language (latest Python 3) is being used in web development,<br /> Machine Learning applications, along with all cutting edge technology in Software Industry. </br />Python Programming Language is very well suited for Beginners, also for <br /> experienced programmers with other programming languages like C++ and Java.<br /><br /> </div> <footer> <p> © 2021 GFG All the content of this webpage belongs to us </p> </footer></body> </html> Output: We added a copyright message in the footer with a simple message. footer message Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. gulshankumarar231 varshagumber28 CSS-Properties CSS-Questions HTML-Questions Picked CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a web page using HTML and CSS Form validation using jQuery How to style a checkbox using CSS? Search Bar using HTML, CSS and JavaScript How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26621, "s": 26593, "text": "\n21 Nov, 2021" }, { "code": null, "e": 26977, "s": 26621, "text": "The screenshot is a feature of OS in windows. We can simply press the print screen ( print screen ) on the keyboard to take screenshots. If the keyboard doesn’t have prt sc key, we can use Fn + Windows logo key + Space Bar. Also, we can use Snip & Sketch or Snipping tool by pressing the Windows logo key + Shift + S and select an area for the screenshot." }, { "code": null, "e": 27066, "s": 26977, "text": " In MacOS, we can use Command + Shift + 3 and Command + Shift + 4 for taking screenshot." }, { "code": null, "e": 27254, "s": 27066, "text": "All these commands are controlled by our operating system, and we can’t disable or block them in the browser using HTML/CSS/JavaScript. So, we can’t prevent users from taking screenshots." }, { "code": null, "e": 27535, "s": 27254, "text": "Besides all these things if the user wants to get the content of our webpage, they can copy it, print it, use some third-party applications or take a picture of it using some other devices. So it’s very difficult to prevent users from taking screenshots or content of our webpage." }, { "code": null, "e": 27618, "s": 27535, "text": "We cannot stop this, but we can use some methods to avoid this all to some extent." }, { "code": null, "e": 27698, "s": 27618, "text": "Example 1: In this example, we will disable the printing option of our webpage." }, { "code": null, "e": 27703, "s": 27698, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> /* We are stopping user from printing our webpage */ @media print { html, body { /* Hide the whole page */ display: none; } } </style></head> <body> <div> Python is a high-level, general-purpose and a very popular programming language. <br />Python programming language (latest Python 3)is being used in web development, <br />Machine Learning applications, along with all cutting edge technology in Software Industry.<br />Python Programming Language is very well suited for Beginners, <br />also for experienced programmers with other programming languages like C++ and Java.<br /> </div></body> </html>", "e": 28547, "s": 27703, "text": null }, { "code": null, "e": 28658, "s": 28549, "text": "Output: This will simply output the content of our webpage but when we try to print it, we will get nothing." }, { "code": null, "e": 28681, "s": 28658, "text": "Printing will not work" }, { "code": null, "e": 28762, "s": 28681, "text": "Example 2. In this example, we will change the text selection feature using CSS." }, { "code": null, "e": 28767, "s": 28762, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> html { user-select: none; } </style></head> <body> <div> Python is a high-level, general-purpose and a very popular programming language. <br />Python programming language (latest Python 3)is being used in web development, <br />Machine Learning applications, along with all cutting edge technology in Software Industry.<br />Python Programming Language is very well suited for Beginners, <br />also for experienced programmers with other programming languages like C++ and Java.<br /> </div></body> </html>", "e": 29436, "s": 28767, "text": null }, { "code": null, "e": 29514, "s": 29436, "text": "Output: This will stop the user from selecting and copying our text contents." }, { "code": null, "e": 29539, "s": 29514, "text": "copying is not happening" }, { "code": null, "e": 29665, "s": 29539, "text": "Example 3. In this example, we will display a warning message to the user to not copy/steal/print/screenshot of our web page." }, { "code": null, "e": 29670, "s": 29665, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <script> alert(\"Do not take screenshot of this page\"); </script></head> <body> <div> Python is a high-level, general-purpose and a very popular programming language.<br /> Python programming language (latest Python 3) is being used in web development,<br /> Machine Learning applications, along with all cutting edge technology in Software Industry. </br />Python Programming Language is very well suited for Beginners, also for <br /> experienced programmers with other programming languages like C++ and Java.<br /> </div></body> </html>", "e": 30338, "s": 29670, "text": null }, { "code": null, "e": 30448, "s": 30340, "text": "Output: This will show an alert message to the user that he should not take any screenshot of this webpage." }, { "code": null, "e": 30470, "s": 30448, "text": "warning alert message" }, { "code": null, "e": 30671, "s": 30470, "text": "Example 4. In this example, we will add a copyright message of our webpage that will show all the content of this web page belongs to us, and it is strictly not allowed to use our content in any form." }, { "code": null, "e": 30676, "s": 30671, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> /* Styling the footer */ footer { text-align: center; padding: 10px; background-color: green; color: white; } </style></head> <body> <div> Python is a high-level, general-purpose and a very popular programming language.<br /> Python programming language (latest Python 3) is being used in web development,<br /> Machine Learning applications, along with all cutting edge technology in Software Industry. </br />Python Programming Language is very well suited for Beginners, also for <br /> experienced programmers with other programming languages like C++ and Java.<br /><br /> </div> <footer> <p> © 2021 GFG All the content of this webpage belongs to us </p> </footer></body> </html>", "e": 31603, "s": 30676, "text": null }, { "code": null, "e": 31679, "s": 31605, "text": "Output: We added a copyright message in the footer with a simple message." }, { "code": null, "e": 31694, "s": 31679, "text": "footer message" }, { "code": null, "e": 31831, "s": 31694, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 31849, "s": 31831, "text": "gulshankumarar231" }, { "code": null, "e": 31864, "s": 31849, "text": "varshagumber28" }, { "code": null, "e": 31879, "s": 31864, "text": "CSS-Properties" }, { "code": null, "e": 31893, "s": 31879, "text": "CSS-Questions" }, { "code": null, "e": 31908, "s": 31893, "text": "HTML-Questions" }, { "code": null, "e": 31915, "s": 31908, "text": "Picked" }, { "code": null, "e": 31919, "s": 31915, "text": "CSS" }, { "code": null, "e": 31924, "s": 31919, "text": "HTML" }, { "code": null, "e": 31941, "s": 31924, "text": "Web Technologies" }, { "code": null, "e": 31946, "s": 31941, "text": "HTML" }, { "code": null, "e": 32044, "s": 31946, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32083, "s": 32044, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 32120, "s": 32083, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 32149, "s": 32120, "text": "Form validation using jQuery" }, { "code": null, "e": 32184, "s": 32149, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 32226, "s": 32184, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 32286, "s": 32226, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 32339, "s": 32286, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 32400, "s": 32339, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 32424, "s": 32400, "text": "REST API (Introduction)" } ]
Tensorflow.js Introduction - GeeksforGeeks
15 Aug, 2021What is Tensorflow.js?TensorFlow.js is a JavaScript library for training and deploying machine learning models on web applications and in Node.js. You can develop the machine learning models from scratch using tensorflow.js or can use the APIs provided to train your existing models in the browser or on your Node.js server.To learn more you can directly go to this link: https://www.tensorflow.org/resources/learn-ml/basics-of-tensorflow-for-js-development.Prerequisite: Before starting Tensorflow.js, you need to know the following:For browser:HTML: Basics knowledge of HTML is requiredJavaScript: Good knowledge of JS is required For server-side:Node.js: Having a good command of Node.js. Also since Node.js is a JS runtime, so having command over JavaScript would help a lot.Other requirements:NPM or Yarn: These are packages that need to be installed in your system.Setting Up Tensorflow.js:Browser Setup There are two ways to add TensorFlow.js in your browser-based application:Using script tags.Installation from NPM1. Using Script tags: Add the following script tag to your main HTML file.<script src=”https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js”></script>Example:HTMLHTML<!DOCTYPE html><html lang="en"> <head> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js"> </script></head> <body> <script> // Value of a scalar var value = "Hello Geeks! Tensorflow here." // Creating the value of a scalar var tens = tf.scalar(value) document.write(tens) </script></body> </html> Output:2. Using NPM/ yarn: We can either use NPM or Yarn to install tensorflow.js.yarn add @tensorflow/tfjsornpm install @tensorflow/tfjsNode.js Setup:Option 1: Install TensorFlow.js with native C++ bindings.yarn add @tensorflow/tfjs-nodeornpm install @tensorflow/tfjs-nodeOption 2: (Linux Only) If your system has a NVIDIA® GPU with CUDA support, use the GPU package even for higher performance.yarn add @tensorflow/tfjs-node-gpuornpm install @tensorflow/tfjs-node-gpuOption 3: Install the pure JavaScript version. This is the slowest option performance-wise.yarn add @tensorflow/tfjsornpm install @tensorflow/tfjsMy Personal Notes arrow_drop_upSave Like0PreviousTensorFlow.js Browser Complete ReferenceNext Tensorflow.js tf.backend() FunctionRecommended ArticlesPage :Introduction to Apache Maven | A build automation tool for Java projects17, May 18Introduction to React Native07, Jun 17Introduction to Apache POI17, Jul 17Apache Kafka | Introduction28, Aug 17Introduction of Firewall in Computer Network31, Aug 17WordPress Introduction23, Jul 18Introduction to Object Oriented Programming in JavaScript18, Sep 17ReactJS | Introduction to JSX09, Mar 18React.js (Introduction and Working)27, Sep 17Introduction to Web Scraping06, Nov 19PHP | MySQL Database Introduction22, Nov 17jQuery | Introduction29, Jan 18Django Introduction | Set 2 (Creating a Project)01, Feb 18Introduction to JavaScript29, Jan 20Introduction to Xamarin | A Software for Mobile App Development and App Creation16, Mar 18ReactJS | Calculator App ( Introduction )25, Mar 18CSS Introduction10, Apr 18Introduction to Web Development and the Holy Trinity of it27, Apr 18Introduction to Postman for API Development28, May 18Ajax Introduction09, Jul 18XHTML | Introduction31, Aug 18REST API (Introduction)02, Sep 18Introduction to JavaScript Course | Learn how to Build a task tracker using JavaScript24, Apr 19Introduction to Scripting Languages21, Sep 18Article Contributed By :ghoshsuman0129@ghoshsuman0129Vote for difficultyEasy Normal Medium Hard ExpertArticle Tags :Tensorflow.jsJavaScriptWeb TechnologiesImprove ArticleReport IssueWriting code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Load CommentsWhat's NewInterview Series- Prepare, Practice & UpskillView DetailsData Structures & Algorithms- Self Paced CourseView DetailsComplete Interview PreparationView DetailsMost popular in JavaScriptRemove elements from a JavaScript ArrayConvert a string to an integer in JavaScriptDifference between var, let and const keywords in JavaScriptDifferences between Functional Components and Class Components in ReactHow to calculate the number of days between two dates in javascript?Most visited in Web TechnologiesRemove elements from a JavaScript ArrayInstallation of Node.js on LinuxConvert a string to an integer in JavaScriptHow to fetch data from an API in ReactJS ?How to insert spaces/tabs in text using HTML/CSS?Improve your Coding Skills with PracticeTry It! 5th Floor, A-118,Sector-136, Noida, Uttar Pradesh - 201305 [email protected] UsCareersIn MediaContact UsPrivacy PolicyCopyright PolicyLearnAlgorithmsData StructuresSDE Cheat SheetMachine learningCS SubjectsVideo TutorialsNewsTop NewsTechnologyWork & CareerBusinessFinanceLifestyleLanguagesPythonJavaCPPGolangC#SQLWeb DevelopmentWeb TutorialsDjango TutorialHTMLCSSJavaScriptBootstrapContributeWrite an ArticleImprove an ArticlePick Topics to WriteWrite Interview ExperienceInternshipsVideo Internship@geeksforgeeks , Some rights reserved We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy Got It ! Start Your Coding Journey Now!Login Register Tensorflow.js tf.tensor() Function Tensorflow.js tf.scalar() Function TenserFlow.js Tensors Creation Complete Reference Tensorflow.js tf.Tensor class .buffer() Method Tensorflow.js tf.Tensor class .bufferSync() Method TensorFlow.js Tensors Classes Complete Reference Tensorflow.js tf.booleanMaskAsync() Function Tensorflow.js tf.concat() Function TensorFlow.js Tensors Transformations Complete Reference TensorFlow.js Slicing and Joining Complete Reference Tensorflow.js tf.einsum() Function Tensorflow.js tf.multinomial() Function TensorFlow.js Tensor Random Complete Reference Tensorflow.js Introduction Tensorflow.js tf.input() Function Tensorflow.js tf.loadGraphModel() Function Tensorflow.js tf.io.http() Function TensorFlow.js Models Loading Complete Reference Tensorflow.js tf.io.copyModel() Function Tensorflow.js tf.io.listModels() Function Tensorflow.js tf.io.moveModel() Function TensorFlow.js Models Management Complete Reference Tensorflow.js tf.GraphModel Class Tensorflow.js tf.GraphModel class .save() Method Tensorflow.js tf.GraphModel class .predict() Method Tensorflow.js tf.GraphModel class .execute() Method TensorFlow.js Models Classes Complete Reference Tensorflow.js Introduction Tensorflow.js tf.layers.elu() Function Tensorflow.js tf.layers.activation() Function TensorFlow.js Layers Basic Complete Reference Tensorflow.js tf.layers.conv1d() Function TensorFlow.js Layers Convolutional Complete Reference Tensorflow.js tf.layers.add() Function TensorFlow.js Layers Merge Complete Reference Tensorflow.js tf.layers.globalAveragePooling1d() Function TensorFlow.js Layers Pooling Complete Reference TensorFlow.js Layers Noise Complete Reference Tensorflow.js tf.layers.bidirectional() Function Tensorflow.js tf.layers.timeDistributed() Function TensorFlow.js Layers Classes Complete Reference Tensorflow.js tf.layers.zeroPadding2d() Function Tensorflow.js tf.layers.masking() Function Tensorflow.js Introduction TensorFlow.js Operations Arithmetic Complete Reference TensorFlow.js Operations Basic Math Complete Reference TensorFlow.js Operations Matrices Complete Reference TensorFlow.js Operations Normalization Complete Reference TensorFlow.js Operations Images Complete Reference TensorFlow.js Operations Logical Complete Reference TensorFlow.js Operations Evaluation Complete Reference Tensorflow.js tf.cumsum() Function TensorFlow.js Operations Slicing and Joining Complete Reference TensorFlow.js Operations Spectral Complete Reference Tensorflow.js tf.unsortedSegmentSum() Function Tensorflow.js tf.movingAverage() Function Tensorflow.js tf.dropout() Function TensorFlow.js Operations Signal Complete Reference Tensorflow.js tf.linalg.bandPart() Function Tensorflow.js tf.linalg.gramSchmidt() Function Tensorflow.js tf.linalg.qr() Function TensorFlow.js Operations Sparse Complete Reference Tensorflow.js Introduction Tensorflow.js tf.grad() Function Tensorflow.js tf.grads() Function Tensorflow.js tf.customGrad() Function TensorFlow.js Training Gradients Complete ReferenceTensorflow.js TrainingTensorflow.js tf.train.momentum() FunctionTensorflow.js tf.train.adagrad() FunctionTensorFlow.js Training Optimizers Complete ReferenceTensorflow.js tf.losses.absoluteDifference() FunctionTensorflow.js tf.losses.computeWeightedLoss() FunctionTensorflow.js tf.losses.cosineDistance() FunctionTensorFlow.js Training Losses Complete ReferenceTensorflow.js tf.train.Optimizer ClassTensorflow.js tf.train.Optimizer class .minimize() MethodTensorFlow.js Training Classes Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.time() FunctionTensorflow.js tf.nextFrame() FunctionTensorflow.js tf.profile() FunctionTensorFlow.js Performance Memory Complete ReferenceTensorflow.js PerformanceTensorflow.js tf.disposeVariables() FunctionTensorflow.js tf.enableDebugMode() FunctionTensorflow.js tf.enableProdMode() FunctionTensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js IntroductionTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js IntroductionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js MetricsTable of ContentsTensorFlow.jsTensorflow.js IntroductionTensorflow.js TensorsTensorflow.js tf.tensor() FunctionTensorflow.js tf.scalar() FunctionTenserFlow.js Tensors Creation Complete ReferenceTensorflow.js tf.Tensor class .buffer() MethodTensorflow.js tf.Tensor class .bufferSync() MethodTensorFlow.js Tensors Classes Complete ReferenceTensorflow.js tf.booleanMaskAsync() FunctionTensorflow.js tf.concat() FunctionTensorFlow.js Tensors Transformations Complete ReferenceTensorFlow.js Slicing and Joining Complete ReferenceTensorflow.js tf.einsum() FunctionTensorflow.js tf.multinomial() FunctionTensorFlow.js Tensor Random Complete ReferenceTensorflow.js IntroductionTensorflow.js ModelsTensorflow.js tf.input() FunctionTensorflow.js tf.loadGraphModel() FunctionTensorflow.js tf.io.http() FunctionTensorFlow.js Models Loading Complete ReferenceTensorflow.js tf.io.copyModel() FunctionTensorflow.js tf.io.listModels() FunctionTensorflow.js tf.io.moveModel() FunctionTensorFlow.js Models Management Complete ReferenceTensorflow.js tf.GraphModel ClassTensorflow.js tf.GraphModel class .save() MethodTensorflow.js tf.GraphModel class .predict() MethodTensorflow.js tf.GraphModel class .execute() MethodTensorFlow.js Models Classes Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.layers.elu() FunctionTensorflow.js LayersTensorflow.js tf.layers.activation() FunctionTensorFlow.js Layers Basic Complete ReferenceTensorflow.js tf.layers.conv1d() FunctionTensorFlow.js Layers Convolutional Complete ReferenceTensorflow.js tf.layers.add() FunctionTensorFlow.js Layers Merge Complete ReferenceTensorflow.js tf.layers.globalAveragePooling1d() FunctionTensorFlow.js Layers Pooling Complete ReferenceTensorFlow.js Layers Noise Complete ReferenceTensorflow.js tf.layers.bidirectional() FunctionTensorflow.js tf.layers.timeDistributed() FunctionTensorFlow.js Layers Classes Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.layers.masking() FunctionTensorflow.js IntroductionTensorFlow.js Operations Arithmetic Complete ReferenceTensorFlow.js Operations Basic Math Complete ReferenceTensorFlow.js Operations Matrices Complete ReferenceTensorflow.js OperationsTensorFlow.js Operations Normalization Complete ReferenceTensorFlow.js Operations Images Complete ReferenceTensorFlow.js Operations Logical Complete ReferenceTensorFlow.js Operations Evaluation Complete ReferenceTensorflow.js tf.cumsum() FunctionTensorFlow.js Operations Slicing and Joining Complete ReferenceTensorFlow.js Operations Spectral Complete ReferenceTensorflow.js tf.unsortedSegmentSum() FunctionTensorflow.js tf.movingAverage() FunctionTensorflow.js tf.dropout() FunctionTensorFlow.js Operations Signal Complete ReferenceTensorflow.js tf.linalg.bandPart() FunctionTensorflow.js tf.linalg.gramSchmidt() FunctionTensorflow.js tf.linalg.qr() FunctionTensorFlow.js Operations Sparse Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.grad() FunctionTensorflow.js tf.grads() FunctionTensorflow.js tf.customGrad() FunctionTensorFlow.js Training Gradients Complete ReferenceTensorflow.js TrainingTensorflow.js tf.train.momentum() FunctionTensorflow.js tf.train.adagrad() FunctionTensorFlow.js Training Optimizers Complete ReferenceTensorflow.js tf.losses.absoluteDifference() FunctionTensorflow.js tf.losses.computeWeightedLoss() FunctionTensorflow.js tf.losses.cosineDistance() FunctionTensorFlow.js Training Losses Complete ReferenceTensorflow.js tf.train.Optimizer ClassTensorflow.js tf.train.Optimizer class .minimize() MethodTensorFlow.js Training Classes Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.time() FunctionTensorflow.js tf.nextFrame() FunctionTensorflow.js tf.profile() FunctionTensorFlow.js Performance Memory Complete ReferenceTensorflow.js PerformanceTensorflow.js tf.disposeVariables() FunctionTensorflow.js tf.enableDebugMode() FunctionTensorflow.js tf.enableProdMode() FunctionTensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js IntroductionTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js IntroductionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js MetricsImprove Article Save Article Like Article Tensorflow.js IntroductionLast Updated : 15 Aug, 2021What is Tensorflow.js?TensorFlow.js is a JavaScript library for training and deploying machine learning models on web applications and in Node.js. You can develop the machine learning models from scratch using tensorflow.js or can use the APIs provided to train your existing models in the browser or on your Node.js server.To learn more you can directly go to this link: https://www.tensorflow.org/resources/learn-ml/basics-of-tensorflow-for-js-development.Prerequisite: Before starting Tensorflow.js, you need to know the following:For browser:HTML: Basics knowledge of HTML is requiredJavaScript: Good knowledge of JS is required For server-side:Node.js: Having a good command of Node.js. Also since Node.js is a JS runtime, so having command over JavaScript would help a lot.Other requirements:NPM or Yarn: These are packages that need to be installed in your system.Setting Up Tensorflow.js:Browser Setup There are two ways to add TensorFlow.js in your browser-based application:Using script tags.Installation from NPM1. Using Script tags: Add the following script tag to your main HTML file.<script src=”https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js”></script>Example:HTMLHTML<!DOCTYPE html><html lang="en"> <head> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js"> </script></head> <body> <script> // Value of a scalar var value = "Hello Geeks! Tensorflow here." // Creating the value of a scalar var tens = tf.scalar(value) document.write(tens) </script></body> </html> Output:2. Using NPM/ yarn: We can either use NPM or Yarn to install tensorflow.js.yarn add @tensorflow/tfjsornpm install @tensorflow/tfjsNode.js Setup:Option 1: Install TensorFlow.js with native C++ bindings.yarn add @tensorflow/tfjs-nodeornpm install @tensorflow/tfjs-nodeOption 2: (Linux Only) If your system has a NVIDIA® GPU with CUDA support, use the GPU package even for higher performance.yarn add @tensorflow/tfjs-node-gpuornpm install @tensorflow/tfjs-node-gpuOption 3: Install the pure JavaScript version. This is the slowest option performance-wise.yarn add @tensorflow/tfjsornpm install @tensorflow/tfjsMy Personal Notes arrow_drop_upSave Like0PreviousTensorFlow.js Browser Complete ReferenceNext Tensorflow.js tf.backend() FunctionRecommended ArticlesPage :Introduction to Apache Maven | A build automation tool for Java projects17, May 18Introduction to React Native07, Jun 17Introduction to Apache POI17, Jul 17Apache Kafka | Introduction28, Aug 17Introduction of Firewall in Computer Network31, Aug 17WordPress Introduction23, Jul 18Introduction to Object Oriented Programming in JavaScript18, Sep 17ReactJS | Introduction to JSX09, Mar 18React.js (Introduction and Working)27, Sep 17Introduction to Web Scraping06, Nov 19PHP | MySQL Database Introduction22, Nov 17jQuery | Introduction29, Jan 18Django Introduction | Set 2 (Creating a Project)01, Feb 18Introduction to JavaScript29, Jan 20Introduction to Xamarin | A Software for Mobile App Development and App Creation16, Mar 18ReactJS | Calculator App ( Introduction )25, Mar 18CSS Introduction10, Apr 18Introduction to Web Development and the Holy Trinity of it27, Apr 18Introduction to Postman for API Development28, May 18Ajax Introduction09, Jul 18XHTML | Introduction31, Aug 18REST API (Introduction)02, Sep 18Introduction to JavaScript Course | Learn how to Build a task tracker using JavaScript24, Apr 19Introduction to Scripting Languages21, Sep 18Article Contributed By :ghoshsuman0129@ghoshsuman0129Vote for difficultyEasy Normal Medium Hard ExpertArticle Tags :Tensorflow.jsJavaScriptWeb TechnologiesImprove ArticleReport IssueWriting code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Load CommentsWhat's NewInterview Series- Prepare, Practice & UpskillView DetailsData Structures & Algorithms- Self Paced CourseView DetailsComplete Interview PreparationView DetailsMost popular in JavaScriptRemove elements from a JavaScript ArrayConvert a string to an integer in JavaScriptDifference between var, let and const keywords in JavaScriptDifferences between Functional Components and Class Components in ReactHow to calculate the number of days between two dates in javascript?Most visited in Web TechnologiesRemove elements from a JavaScript ArrayInstallation of Node.js on LinuxConvert a string to an integer in JavaScriptHow to fetch data from an API in ReactJS ?How to insert spaces/tabs in text using HTML/CSS?Improve your Coding Skills with PracticeTry It! 5th Floor, A-118,Sector-136, Noida, Uttar Pradesh - 201305 [email protected] UsCareersIn MediaContact UsPrivacy PolicyCopyright PolicyLearnAlgorithmsData StructuresSDE Cheat SheetMachine learningCS SubjectsVideo TutorialsNewsTop NewsTechnologyWork & CareerBusinessFinanceLifestyleLanguagesPythonJavaCPPGolangC#SQLWeb DevelopmentWeb TutorialsDjango TutorialHTMLCSSJavaScriptBootstrapContributeWrite an ArticleImprove an ArticlePick Topics to WriteWrite Interview ExperienceInternshipsVideo Internship@geeksforgeeks , Some rights reserved We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy Got It ! Start Your Coding Journey Now!Login Register Tensorflow.js tf.train.momentum() Function Tensorflow.js tf.train.adagrad() Function TensorFlow.js Training Optimizers Complete Reference Tensorflow.js tf.losses.absoluteDifference() Function Tensorflow.js tf.losses.computeWeightedLoss() Function Tensorflow.js tf.losses.cosineDistance() Function TensorFlow.js Training Losses Complete Reference Tensorflow.js tf.train.Optimizer Class Tensorflow.js tf.train.Optimizer class .minimize() Method TensorFlow.js Training Classes Complete Reference Tensorflow.js Introduction Tensorflow.js tf.time() Function Tensorflow.js tf.nextFrame() Function Tensorflow.js tf.profile() Function TensorFlow.js Performance Memory Complete Reference Tensorflow.js tf.disposeVariables() Function Tensorflow.js tf.enableDebugMode() Function Tensorflow.js tf.enableProdMode() Function Tensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js IntroductionTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js IntroductionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js Metrics TensorFlow.js Environment Complete Reference Tensorflow.js Introduction Tensorflow.js tf.metrics.binaryAccuracy() Function Tensorflow.js tf.metrics.binaryCrossentropy() Function Tensorflow.js tf.metrics.categoricalAccuracy() Function Tensorflow.js tf.metrics.categoricalCrossentropy() Function Tensorflow.js tf.metrics.cosineProximity() Function Tensorflow.js tf.metrics.meanSquaredError() Function Tensorflow.js tf.metrics.precision() Function Tensorflow.js tf.metrics.recall() Function Tensorflow.js tf.metrics.sparseCategoricalAccuracy() Function TensorFlow.js Metrics Complete Reference Tensorflow.js Introduction Tensorflow.js tf.initializers.Initializer Class Tensorflow.js tf.initializers.constant() Method Tensorflow.js tf.initializers.glorotNormal() Function Tensorflow.js tf.initializers.glorotUniform() Function Tensorflow.js tf.initializers.heNormal() Function Tensorflow.js tf.initializers.heUniform() Function TensorFlow.js Initializers Complete Reference Tensorflow.js Introduction Tensorflow.js tf.regularizers.l1() Function Tensorflow.js tf.regularizers.l1l2() Function Tensorflow.js tf.regularizers.l2() Function Tensorflow.js Introduction Tensorflow.js tf.data.csv() Function Tensorflow.js tf.data.generator() Function Tensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js IntroductionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js Metrics TensorFlow.js Data Creation Complete Reference Tensorflow.js tf.data.zip() Function Tensorflow.js tf.data.Dataset class .batch() Method TensorFlow.js Data Classes Complete References Tensorflow.js Introduction Tensorflow.js tf.util.assert() Function Tensorflow.js tf.util.createShuffledIndices() Function Tensorflow.js tf.decodeString() Function Tensorflow.js tf.encodeString() Function Tensorflow.js tf.fetch() Function Tensorflow.js tf.util.flatten() Function Tensorflow.js tf.util.now() Function Tensorflow.js tf.util.shuffle() Function Tensorflow.js tf.util.shuffleCombo() Function Tensorflow.js tf.browser.fromPixels() Function Tensorflow.js tf.browser.fromPixelsAsync() Function Tensorflow.js tf.browser.toPixels() Function TensorFlow.js Browser Complete Reference Tensorflow.js Introduction Tensorflow.js tf.backend() Function Tensorflow.js tf.getBackend() Function Tensorflow.js tf.ready() Function Tensorflow.js tf.registerBackend() Function Tensorflow.js tf.removeBackend() Function Tensorflow.js tf.setBackend() Function Tensorflow.js tf.callbacks.earlyStopping() Function TensorFlow.js Tensorflow.js IntroductionTensorflow.js TensorsTensorflow.js tf.tensor() FunctionTensorflow.js tf.scalar() FunctionTenserFlow.js Tensors Creation Complete ReferenceTensorflow.js tf.Tensor class .buffer() MethodTensorflow.js tf.Tensor class .bufferSync() MethodTensorFlow.js Tensors Classes Complete ReferenceTensorflow.js tf.booleanMaskAsync() FunctionTensorflow.js tf.concat() FunctionTensorFlow.js Tensors Transformations Complete ReferenceTensorFlow.js Slicing and Joining Complete ReferenceTensorflow.js tf.einsum() FunctionTensorflow.js tf.multinomial() FunctionTensorFlow.js Tensor Random Complete ReferenceTensorflow.js IntroductionTensorflow.js ModelsTensorflow.js tf.input() FunctionTensorflow.js tf.loadGraphModel() FunctionTensorflow.js tf.io.http() FunctionTensorFlow.js Models Loading Complete ReferenceTensorflow.js tf.io.copyModel() FunctionTensorflow.js tf.io.listModels() FunctionTensorflow.js tf.io.moveModel() FunctionTensorFlow.js Models Management Complete ReferenceTensorflow.js tf.GraphModel ClassTensorflow.js tf.GraphModel class .save() MethodTensorflow.js tf.GraphModel class .predict() MethodTensorflow.js tf.GraphModel class .execute() MethodTensorFlow.js Models Classes Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.layers.elu() FunctionTensorflow.js LayersTensorflow.js tf.layers.activation() FunctionTensorFlow.js Layers Basic Complete ReferenceTensorflow.js tf.layers.conv1d() FunctionTensorFlow.js Layers Convolutional Complete ReferenceTensorflow.js tf.layers.add() FunctionTensorFlow.js Layers Merge Complete ReferenceTensorflow.js tf.layers.globalAveragePooling1d() FunctionTensorFlow.js Layers Pooling Complete ReferenceTensorFlow.js Layers Noise Complete ReferenceTensorflow.js tf.layers.bidirectional() FunctionTensorflow.js tf.layers.timeDistributed() FunctionTensorFlow.js Layers Classes Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.layers.masking() FunctionTensorflow.js IntroductionTensorFlow.js Operations Arithmetic Complete ReferenceTensorFlow.js Operations Basic Math Complete ReferenceTensorFlow.js Operations Matrices Complete ReferenceTensorflow.js OperationsTensorFlow.js Operations Normalization Complete ReferenceTensorFlow.js Operations Images Complete ReferenceTensorFlow.js Operations Logical Complete ReferenceTensorFlow.js Operations Evaluation Complete ReferenceTensorflow.js tf.cumsum() FunctionTensorFlow.js Operations Slicing and Joining Complete ReferenceTensorFlow.js Operations Spectral Complete ReferenceTensorflow.js tf.unsortedSegmentSum() FunctionTensorflow.js tf.movingAverage() FunctionTensorflow.js tf.dropout() FunctionTensorFlow.js Operations Signal Complete ReferenceTensorflow.js tf.linalg.bandPart() FunctionTensorflow.js tf.linalg.gramSchmidt() FunctionTensorflow.js tf.linalg.qr() FunctionTensorFlow.js Operations Sparse Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.grad() FunctionTensorflow.js tf.grads() FunctionTensorflow.js tf.customGrad() FunctionTensorFlow.js Training Gradients Complete ReferenceTensorflow.js TrainingTensorflow.js tf.train.momentum() FunctionTensorflow.js tf.train.adagrad() FunctionTensorFlow.js Training Optimizers Complete ReferenceTensorflow.js tf.losses.absoluteDifference() FunctionTensorflow.js tf.losses.computeWeightedLoss() FunctionTensorflow.js tf.losses.cosineDistance() FunctionTensorFlow.js Training Losses Complete ReferenceTensorflow.js tf.train.Optimizer ClassTensorflow.js tf.train.Optimizer class .minimize() MethodTensorFlow.js Training Classes Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.time() FunctionTensorflow.js tf.nextFrame() FunctionTensorflow.js tf.profile() FunctionTensorFlow.js Performance Memory Complete ReferenceTensorflow.js PerformanceTensorflow.js tf.disposeVariables() FunctionTensorflow.js tf.enableDebugMode() FunctionTensorflow.js tf.enableProdMode() FunctionTensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js IntroductionTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js IntroductionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js MetricsImprove Article Save Article Like Article Tensorflow.js IntroductionLast Updated : 15 Aug, 2021What is Tensorflow.js?TensorFlow.js is a JavaScript library for training and deploying machine learning models on web applications and in Node.js. You can develop the machine learning models from scratch using tensorflow.js or can use the APIs provided to train your existing models in the browser or on your Node.js server.To learn more you can directly go to this link: https://www.tensorflow.org/resources/learn-ml/basics-of-tensorflow-for-js-development.Prerequisite: Before starting Tensorflow.js, you need to know the following:For browser:HTML: Basics knowledge of HTML is requiredJavaScript: Good knowledge of JS is required For server-side:Node.js: Having a good command of Node.js. Also since Node.js is a JS runtime, so having command over JavaScript would help a lot.Other requirements:NPM or Yarn: These are packages that need to be installed in your system.Setting Up Tensorflow.js:Browser Setup There are two ways to add TensorFlow.js in your browser-based application:Using script tags.Installation from NPM1. Using Script tags: Add the following script tag to your main HTML file.<script src=”https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js”></script>Example:HTMLHTML<!DOCTYPE html><html lang="en"> <head> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js"> </script></head> <body> <script> // Value of a scalar var value = "Hello Geeks! Tensorflow here." // Creating the value of a scalar var tens = tf.scalar(value) document.write(tens) </script></body> </html> Output:2. Using NPM/ yarn: We can either use NPM or Yarn to install tensorflow.js.yarn add @tensorflow/tfjsornpm install @tensorflow/tfjsNode.js Setup:Option 1: Install TensorFlow.js with native C++ bindings.yarn add @tensorflow/tfjs-nodeornpm install @tensorflow/tfjs-nodeOption 2: (Linux Only) If your system has a NVIDIA® GPU with CUDA support, use the GPU package even for higher performance.yarn add @tensorflow/tfjs-node-gpuornpm install @tensorflow/tfjs-node-gpuOption 3: Install the pure JavaScript version. This is the slowest option performance-wise.yarn add @tensorflow/tfjsornpm install @tensorflow/tfjsMy Personal Notes arrow_drop_upSave Like0PreviousTensorFlow.js Browser Complete ReferenceNext Tensorflow.js tf.backend() FunctionRecommended ArticlesPage :Introduction to Apache Maven | A build automation tool for Java projects17, May 18Introduction to React Native07, Jun 17Introduction to Apache POI17, Jul 17Apache Kafka | Introduction28, Aug 17Introduction of Firewall in Computer Network31, Aug 17WordPress Introduction23, Jul 18Introduction to Object Oriented Programming in JavaScript18, Sep 17ReactJS | Introduction to JSX09, Mar 18React.js (Introduction and Working)27, Sep 17Introduction to Web Scraping06, Nov 19PHP | MySQL Database Introduction22, Nov 17jQuery | Introduction29, Jan 18Django Introduction | Set 2 (Creating a Project)01, Feb 18Introduction to JavaScript29, Jan 20Introduction to Xamarin | A Software for Mobile App Development and App Creation16, Mar 18ReactJS | Calculator App ( Introduction )25, Mar 18CSS Introduction10, Apr 18Introduction to Web Development and the Holy Trinity of it27, Apr 18Introduction to Postman for API Development28, May 18Ajax Introduction09, Jul 18XHTML | Introduction31, Aug 18REST API (Introduction)02, Sep 18Introduction to JavaScript Course | Learn how to Build a task tracker using JavaScript24, Apr 19Introduction to Scripting Languages21, Sep 18Article Contributed By :ghoshsuman0129@ghoshsuman0129Vote for difficultyEasy Normal Medium Hard ExpertArticle Tags :Tensorflow.jsJavaScriptWeb TechnologiesImprove ArticleReport IssueWriting code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Load CommentsWhat's NewInterview Series- Prepare, Practice & UpskillView DetailsData Structures & Algorithms- Self Paced CourseView DetailsComplete Interview PreparationView DetailsMost popular in JavaScriptRemove elements from a JavaScript ArrayConvert a string to an integer in JavaScriptDifference between var, let and const keywords in JavaScriptDifferences between Functional Components and Class Components in ReactHow to calculate the number of days between two dates in javascript?Most visited in Web TechnologiesRemove elements from a JavaScript ArrayInstallation of Node.js on LinuxConvert a string to an integer in JavaScriptHow to fetch data from an API in ReactJS ?How to insert spaces/tabs in text using HTML/CSS? Tensorflow.js tf.tensor() Function Tensorflow.js tf.scalar() Function TenserFlow.js Tensors Creation Complete Reference Tensorflow.js tf.Tensor class .buffer() Method Tensorflow.js tf.Tensor class .bufferSync() Method TensorFlow.js Tensors Classes Complete Reference Tensorflow.js tf.booleanMaskAsync() Function Tensorflow.js tf.concat() Function TensorFlow.js Tensors Transformations Complete Reference TensorFlow.js Slicing and Joining Complete Reference Tensorflow.js tf.einsum() Function Tensorflow.js tf.multinomial() Function TensorFlow.js Tensor Random Complete Reference Tensorflow.js Introduction Tensorflow.js tf.input() Function Tensorflow.js tf.loadGraphModel() Function Tensorflow.js tf.io.http() Function TensorFlow.js Models Loading Complete Reference Tensorflow.js tf.io.copyModel() Function Tensorflow.js tf.io.listModels() Function Tensorflow.js tf.io.moveModel() Function TensorFlow.js Models Management Complete Reference Tensorflow.js tf.GraphModel Class Tensorflow.js tf.GraphModel class .save() Method Tensorflow.js tf.GraphModel class .predict() Method Tensorflow.js tf.GraphModel class .execute() Method TensorFlow.js Models Classes Complete Reference Tensorflow.js Introduction Tensorflow.js tf.layers.elu() Function Tensorflow.js tf.layers.activation() Function TensorFlow.js Layers Basic Complete Reference Tensorflow.js tf.layers.conv1d() Function TensorFlow.js Layers Convolutional Complete Reference Tensorflow.js tf.layers.add() Function TensorFlow.js Layers Merge Complete Reference Tensorflow.js tf.layers.globalAveragePooling1d() Function TensorFlow.js Layers Pooling Complete Reference TensorFlow.js Layers Noise Complete Reference Tensorflow.js tf.layers.bidirectional() Function Tensorflow.js tf.layers.timeDistributed() Function TensorFlow.js Layers Classes Complete Reference Tensorflow.js tf.layers.zeroPadding2d() Function Tensorflow.js tf.layers.masking() Function Tensorflow.js Introduction TensorFlow.js Operations Arithmetic Complete Reference TensorFlow.js Operations Basic Math Complete Reference TensorFlow.js Operations Matrices Complete Reference TensorFlow.js Operations Normalization Complete Reference TensorFlow.js Operations Images Complete Reference TensorFlow.js Operations Logical Complete Reference TensorFlow.js Operations Evaluation Complete Reference Tensorflow.js tf.cumsum() Function TensorFlow.js Operations Slicing and Joining Complete Reference TensorFlow.js Operations Spectral Complete Reference Tensorflow.js tf.unsortedSegmentSum() Function Tensorflow.js tf.movingAverage() Function Tensorflow.js tf.dropout() Function TensorFlow.js Operations Signal Complete Reference Tensorflow.js tf.linalg.bandPart() Function Tensorflow.js tf.linalg.gramSchmidt() Function Tensorflow.js tf.linalg.qr() Function TensorFlow.js Operations Sparse Complete Reference Tensorflow.js Introduction Tensorflow.js tf.grad() Function Tensorflow.js tf.grads() Function Tensorflow.js tf.customGrad() Function TensorFlow.js Training Gradients Complete ReferenceTensorflow.js TrainingTensorflow.js tf.train.momentum() FunctionTensorflow.js tf.train.adagrad() FunctionTensorFlow.js Training Optimizers Complete ReferenceTensorflow.js tf.losses.absoluteDifference() FunctionTensorflow.js tf.losses.computeWeightedLoss() FunctionTensorflow.js tf.losses.cosineDistance() FunctionTensorFlow.js Training Losses Complete ReferenceTensorflow.js tf.train.Optimizer ClassTensorflow.js tf.train.Optimizer class .minimize() MethodTensorFlow.js Training Classes Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.time() FunctionTensorflow.js tf.nextFrame() FunctionTensorflow.js tf.profile() FunctionTensorFlow.js Performance Memory Complete ReferenceTensorflow.js PerformanceTensorflow.js tf.disposeVariables() FunctionTensorflow.js tf.enableDebugMode() FunctionTensorflow.js tf.enableProdMode() FunctionTensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js IntroductionTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js IntroductionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js MetricsImprove Article Save Article Like Article Tensorflow.js IntroductionLast Updated : 15 Aug, 2021What is Tensorflow.js?TensorFlow.js is a JavaScript library for training and deploying machine learning models on web applications and in Node.js. You can develop the machine learning models from scratch using tensorflow.js or can use the APIs provided to train your existing models in the browser or on your Node.js server.To learn more you can directly go to this link: https://www.tensorflow.org/resources/learn-ml/basics-of-tensorflow-for-js-development.Prerequisite: Before starting Tensorflow.js, you need to know the following:For browser:HTML: Basics knowledge of HTML is requiredJavaScript: Good knowledge of JS is required For server-side:Node.js: Having a good command of Node.js. Also since Node.js is a JS runtime, so having command over JavaScript would help a lot.Other requirements:NPM or Yarn: These are packages that need to be installed in your system.Setting Up Tensorflow.js:Browser Setup There are two ways to add TensorFlow.js in your browser-based application:Using script tags.Installation from NPM1. Using Script tags: Add the following script tag to your main HTML file.<script src=”https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js”></script>Example:HTMLHTML<!DOCTYPE html><html lang="en"> <head> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js"> </script></head> <body> <script> // Value of a scalar var value = "Hello Geeks! Tensorflow here." // Creating the value of a scalar var tens = tf.scalar(value) document.write(tens) </script></body> </html> Output:2. Using NPM/ yarn: We can either use NPM or Yarn to install tensorflow.js.yarn add @tensorflow/tfjsornpm install @tensorflow/tfjsNode.js Setup:Option 1: Install TensorFlow.js with native C++ bindings.yarn add @tensorflow/tfjs-nodeornpm install @tensorflow/tfjs-nodeOption 2: (Linux Only) If your system has a NVIDIA® GPU with CUDA support, use the GPU package even for higher performance.yarn add @tensorflow/tfjs-node-gpuornpm install @tensorflow/tfjs-node-gpuOption 3: Install the pure JavaScript version. This is the slowest option performance-wise.yarn add @tensorflow/tfjsornpm install @tensorflow/tfjsMy Personal Notes arrow_drop_upSave Like0PreviousTensorFlow.js Browser Complete ReferenceNext Tensorflow.js tf.backend() FunctionRecommended ArticlesPage :Introduction to Apache Maven | A build automation tool for Java projects17, May 18Introduction to React Native07, Jun 17Introduction to Apache POI17, Jul 17Apache Kafka | Introduction28, Aug 17Introduction of Firewall in Computer Network31, Aug 17WordPress Introduction23, Jul 18Introduction to Object Oriented Programming in JavaScript18, Sep 17ReactJS | Introduction to JSX09, Mar 18React.js (Introduction and Working)27, Sep 17Introduction to Web Scraping06, Nov 19PHP | MySQL Database Introduction22, Nov 17jQuery | Introduction29, Jan 18Django Introduction | Set 2 (Creating a Project)01, Feb 18Introduction to JavaScript29, Jan 20Introduction to Xamarin | A Software for Mobile App Development and App Creation16, Mar 18ReactJS | Calculator App ( Introduction )25, Mar 18CSS Introduction10, Apr 18Introduction to Web Development and the Holy Trinity of it27, Apr 18Introduction to Postman for API Development28, May 18Ajax Introduction09, Jul 18XHTML | Introduction31, Aug 18REST API (Introduction)02, Sep 18Introduction to JavaScript Course | Learn how to Build a task tracker using JavaScript24, Apr 19Introduction to Scripting Languages21, Sep 18Article Contributed By :ghoshsuman0129@ghoshsuman0129Vote for difficultyEasy Normal Medium Hard ExpertArticle Tags :Tensorflow.jsJavaScriptWeb TechnologiesImprove ArticleReport IssueWriting code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Load CommentsWhat's NewInterview Series- Prepare, Practice & UpskillView DetailsData Structures & Algorithms- Self Paced CourseView DetailsComplete Interview PreparationView DetailsMost popular in JavaScriptRemove elements from a JavaScript ArrayConvert a string to an integer in JavaScriptDifference between var, let and const keywords in JavaScriptDifferences between Functional Components and Class Components in ReactHow to calculate the number of days between two dates in javascript?Most visited in Web TechnologiesRemove elements from a JavaScript ArrayInstallation of Node.js on LinuxConvert a string to an integer in JavaScriptHow to fetch data from an API in ReactJS ?How to insert spaces/tabs in text using HTML/CSS? Tensorflow.js tf.train.momentum() Function Tensorflow.js tf.train.adagrad() Function TensorFlow.js Training Optimizers Complete Reference Tensorflow.js tf.losses.absoluteDifference() Function Tensorflow.js tf.losses.computeWeightedLoss() Function Tensorflow.js tf.losses.cosineDistance() Function TensorFlow.js Training Losses Complete Reference Tensorflow.js tf.train.Optimizer Class Tensorflow.js tf.train.Optimizer class .minimize() Method TensorFlow.js Training Classes Complete Reference Tensorflow.js Introduction Tensorflow.js tf.time() Function Tensorflow.js tf.nextFrame() Function Tensorflow.js tf.profile() Function TensorFlow.js Performance Memory Complete Reference Tensorflow.js tf.disposeVariables() Function Tensorflow.js tf.enableDebugMode() Function Tensorflow.js tf.enableProdMode() Function Tensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js IntroductionTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js IntroductionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js Metrics TensorFlow.js Environment Complete Reference Tensorflow.js Introduction Tensorflow.js tf.metrics.binaryAccuracy() Function Tensorflow.js tf.metrics.binaryCrossentropy() Function Tensorflow.js tf.metrics.categoricalAccuracy() Function Tensorflow.js tf.metrics.categoricalCrossentropy() Function Tensorflow.js tf.metrics.cosineProximity() Function Tensorflow.js tf.metrics.meanSquaredError() Function Tensorflow.js tf.metrics.precision() Function Tensorflow.js tf.metrics.recall() Function Tensorflow.js tf.metrics.sparseCategoricalAccuracy() Function TensorFlow.js Metrics Complete Reference Tensorflow.js Introduction Tensorflow.js tf.initializers.Initializer Class Tensorflow.js tf.initializers.constant() Method Tensorflow.js tf.initializers.glorotNormal() Function Tensorflow.js tf.initializers.glorotUniform() Function Tensorflow.js tf.initializers.heNormal() Function Tensorflow.js tf.initializers.heUniform() Function TensorFlow.js Initializers Complete Reference Tensorflow.js Introduction Tensorflow.js tf.regularizers.l1() Function Tensorflow.js tf.regularizers.l1l2() Function Tensorflow.js tf.regularizers.l2() Function Tensorflow.js Introduction Tensorflow.js tf.data.csv() Function Tensorflow.js tf.data.generator() Function Tensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js IntroductionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js Metrics TensorFlow.js Data Creation Complete Reference Tensorflow.js tf.data.zip() Function Tensorflow.js tf.data.Dataset class .batch() Method TensorFlow.js Data Classes Complete References Tensorflow.js Introduction Tensorflow.js tf.util.assert() Function Tensorflow.js tf.util.createShuffledIndices() Function Tensorflow.js tf.decodeString() Function Tensorflow.js tf.encodeString() Function Tensorflow.js tf.fetch() Function Tensorflow.js tf.util.flatten() Function Tensorflow.js tf.util.now() Function Tensorflow.js tf.util.shuffle() Function Tensorflow.js tf.util.shuffleCombo() Function Tensorflow.js tf.browser.fromPixels() Function Tensorflow.js tf.browser.fromPixelsAsync() Function Tensorflow.js tf.browser.toPixels() Function TensorFlow.js Browser Complete Reference Tensorflow.js Introduction Tensorflow.js tf.backend() Function Tensorflow.js tf.getBackend() Function Tensorflow.js tf.ready() Function Tensorflow.js tf.registerBackend() Function Tensorflow.js tf.removeBackend() Function Tensorflow.js tf.setBackend() Function Tensorflow.js tf.callbacks.earlyStopping() Function Last Updated : 15 Aug, 2021 TensorFlow.js is a JavaScript library for training and deploying machine learning models on web applications and in Node.js. You can develop the machine learning models from scratch using tensorflow.js or can use the APIs provided to train your existing models in the browser or on your Node.js server. To learn more you can directly go to this link: https://www.tensorflow.org/resources/learn-ml/basics-of-tensorflow-for-js-development. Prerequisite: Before starting Tensorflow.js, you need to know the following: For browser: HTML: Basics knowledge of HTML is required JavaScript: Good knowledge of JS is required For server-side: Node.js: Having a good command of Node.js. Also since Node.js is a JS runtime, so having command over JavaScript would help a lot. Other requirements: NPM or Yarn: These are packages that need to be installed in your system. Setting Up Tensorflow.js: Browser Setup There are two ways to add TensorFlow.js in your browser-based application: Using script tags. Installation from NPM 1. Using Script tags: Add the following script tag to your main HTML file. <script src=”https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js”></script> Example: HTML <!DOCTYPE html><html lang="en"> <head> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js"> </script></head> <body> <script> // Value of a scalar var value = "Hello Geeks! Tensorflow here." // Creating the value of a scalar var tens = tf.scalar(value) document.write(tens) </script></body> </html> Output: 2. Using NPM/ yarn: We can either use NPM or Yarn to install tensorflow.js. yarn add @tensorflow/tfjs or npm install @tensorflow/tfjs Node.js Setup: Option 1: Install TensorFlow.js with native C++ bindings. yarn add @tensorflow/tfjs-node or npm install @tensorflow/tfjs-node Option 2: (Linux Only) If your system has a NVIDIA® GPU with CUDA support, use the GPU package even for higher performance. yarn add @tensorflow/tfjs-node-gpu or npm install @tensorflow/tfjs-node-gpu Option 3: Install the pure JavaScript version. This is the slowest option performance-wise. yarn add @tensorflow/tfjs or npm install @tensorflow/tfjs Tensorflow.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in 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": 41879, "s": 23503, "text": "\n15 Aug, 2021What is Tensorflow.js?TensorFlow.js is a JavaScript library for training and deploying machine learning models on web applications and in Node.js. You can develop the machine learning models from scratch using tensorflow.js or can use the APIs provided to train your existing models in the browser or on your Node.js server.To learn more you can directly go to this link: https://www.tensorflow.org/resources/learn-ml/basics-of-tensorflow-for-js-development.Prerequisite: Before starting Tensorflow.js, you need to know the following:For browser:HTML: Basics knowledge of HTML is requiredJavaScript: Good knowledge of JS is required For server-side:Node.js: Having a good command of Node.js. Also since Node.js is a JS runtime, so having command over JavaScript would help a lot.Other requirements:NPM or Yarn: These are packages that need to be installed in your system.Setting Up Tensorflow.js:Browser Setup There are two ways to add TensorFlow.js in your browser-based application:Using script tags.Installation from NPM1. Using Script tags: Add the following script tag to your main HTML file.<script src=”https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js”></script>Example:HTMLHTML<!DOCTYPE html><html lang=\"en\"> <head> <script src=\"https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js\"> </script></head> <body> <script> // Value of a scalar var value = \"Hello Geeks! Tensorflow here.\" // Creating the value of a scalar var tens = tf.scalar(value) document.write(tens) </script></body> </html> Output:2. Using NPM/ yarn: We can either use NPM or Yarn to install tensorflow.js.yarn add @tensorflow/tfjsornpm install @tensorflow/tfjsNode.js Setup:Option 1: Install TensorFlow.js with native C++ bindings.yarn add @tensorflow/tfjs-nodeornpm install @tensorflow/tfjs-nodeOption 2: (Linux Only) If your system has a NVIDIA® GPU with CUDA support, use the GPU package even for higher performance.yarn add @tensorflow/tfjs-node-gpuornpm install @tensorflow/tfjs-node-gpuOption 3: Install the pure JavaScript version. This is the slowest option performance-wise.yarn add @tensorflow/tfjsornpm install @tensorflow/tfjsMy Personal Notes\narrow_drop_upSave\n\nLike0PreviousTensorFlow.js Browser Complete ReferenceNext\nTensorflow.js tf.backend() FunctionRecommended ArticlesPage :Introduction to Apache Maven | A build automation tool for Java projects17, May 18Introduction to React Native07, Jun 17Introduction to Apache POI17, Jul 17Apache Kafka | Introduction28, Aug 17Introduction of Firewall in Computer Network31, Aug 17WordPress Introduction23, Jul 18Introduction to Object Oriented Programming in JavaScript18, Sep 17ReactJS | Introduction to JSX09, Mar 18React.js (Introduction and Working)27, Sep 17Introduction to Web Scraping06, Nov 19PHP | MySQL Database Introduction22, Nov 17jQuery | Introduction29, Jan 18Django Introduction | Set 2 (Creating a Project)01, Feb 18Introduction to JavaScript29, Jan 20Introduction to Xamarin | A Software for Mobile App Development and App Creation16, Mar 18ReactJS | Calculator App ( Introduction )25, Mar 18CSS Introduction10, Apr 18Introduction to Web Development and the Holy Trinity of it27, Apr 18Introduction to Postman for API Development28, May 18Ajax Introduction09, Jul 18XHTML | Introduction31, Aug 18REST API (Introduction)02, Sep 18Introduction to JavaScript Course | Learn how to Build a task tracker using JavaScript24, Apr 19Introduction to Scripting Languages21, Sep 18Article Contributed By :ghoshsuman0129@ghoshsuman0129Vote for difficultyEasy\nNormal\nMedium\nHard\nExpertArticle Tags :Tensorflow.jsJavaScriptWeb TechnologiesImprove ArticleReport IssueWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nLoad CommentsWhat's NewInterview Series- Prepare, Practice & UpskillView DetailsData Structures & Algorithms- Self Paced CourseView DetailsComplete Interview PreparationView DetailsMost popular in JavaScriptRemove elements from a JavaScript ArrayConvert a string to an integer in JavaScriptDifference between var, let and const keywords in JavaScriptDifferences between Functional Components and Class Components in ReactHow to calculate the number of days between two dates in javascript?Most visited in Web TechnologiesRemove elements from a JavaScript ArrayInstallation of Node.js on LinuxConvert a string to an integer in JavaScriptHow to fetch data from an API in ReactJS ?How to insert spaces/tabs in text using HTML/CSS?Improve your Coding Skills with PracticeTry It!\n5th Floor, A-118,Sector-136, Noida, Uttar Pradesh - 201305\[email protected] UsCareersIn MediaContact UsPrivacy PolicyCopyright PolicyLearnAlgorithmsData StructuresSDE Cheat SheetMachine learningCS SubjectsVideo TutorialsNewsTop NewsTechnologyWork & CareerBusinessFinanceLifestyleLanguagesPythonJavaCPPGolangC#SQLWeb DevelopmentWeb TutorialsDjango TutorialHTMLCSSJavaScriptBootstrapContributeWrite an ArticleImprove an ArticlePick Topics to WriteWrite Interview ExperienceInternshipsVideo Internship@geeksforgeeks\n, Some rights reserved \nWe use cookies to ensure you have the best browsing experience on our website. By using our site, you\nacknowledge that you have read and understood our\nCookie Policy &\n Privacy Policy\n\nGot It !\nStart Your Coding Journey Now!Login\nRegister" }, { "code": null, "e": 41914, "s": 41879, "text": "Tensorflow.js tf.tensor() Function" }, { "code": null, "e": 41949, "s": 41914, "text": "Tensorflow.js tf.scalar() Function" }, { "code": null, "e": 41999, "s": 41949, "text": "TenserFlow.js Tensors Creation Complete Reference" }, { "code": null, "e": 42046, "s": 41999, "text": "Tensorflow.js tf.Tensor class .buffer() Method" }, { "code": null, "e": 42097, "s": 42046, "text": "Tensorflow.js tf.Tensor class .bufferSync() Method" }, { "code": null, "e": 42146, "s": 42097, "text": "TensorFlow.js Tensors Classes Complete Reference" }, { "code": null, "e": 42191, "s": 42146, "text": "Tensorflow.js tf.booleanMaskAsync() Function" }, { "code": null, "e": 42226, "s": 42191, "text": "Tensorflow.js tf.concat() Function" }, { "code": null, "e": 42283, "s": 42226, "text": "TensorFlow.js Tensors Transformations Complete Reference" }, { "code": null, "e": 42336, "s": 42283, "text": "TensorFlow.js Slicing and Joining Complete Reference" }, { "code": null, "e": 42371, "s": 42336, "text": "Tensorflow.js tf.einsum() Function" }, { "code": null, "e": 42411, "s": 42371, "text": "Tensorflow.js tf.multinomial() Function" }, { "code": null, "e": 42458, "s": 42411, "text": "TensorFlow.js Tensor Random Complete Reference" }, { "code": null, "e": 42485, "s": 42458, "text": "Tensorflow.js Introduction" }, { "code": null, "e": 42519, "s": 42485, "text": "Tensorflow.js tf.input() Function" }, { "code": null, "e": 42562, "s": 42519, "text": "Tensorflow.js tf.loadGraphModel() Function" }, { "code": null, "e": 42598, "s": 42562, "text": "Tensorflow.js tf.io.http() Function" }, { "code": null, "e": 42646, "s": 42598, "text": "TensorFlow.js Models Loading Complete Reference" }, { "code": null, "e": 42687, "s": 42646, "text": "Tensorflow.js tf.io.copyModel() Function" }, { "code": null, "e": 42729, "s": 42687, "text": "Tensorflow.js tf.io.listModels() Function" }, { "code": null, "e": 42770, "s": 42729, "text": "Tensorflow.js tf.io.moveModel() Function" }, { "code": null, "e": 42821, "s": 42770, "text": "TensorFlow.js Models Management Complete Reference" }, { "code": null, "e": 42855, "s": 42821, "text": "Tensorflow.js tf.GraphModel Class" }, { "code": null, "e": 42904, "s": 42855, "text": "Tensorflow.js tf.GraphModel class .save() Method" }, { "code": null, "e": 42956, "s": 42904, "text": "Tensorflow.js tf.GraphModel class .predict() Method" }, { "code": null, "e": 43008, "s": 42956, "text": "Tensorflow.js tf.GraphModel class .execute() Method" }, { "code": null, "e": 43056, "s": 43008, "text": "TensorFlow.js Models Classes Complete Reference" }, { "code": null, "e": 43083, "s": 43056, "text": "Tensorflow.js Introduction" }, { "code": null, "e": 43122, "s": 43083, "text": "Tensorflow.js tf.layers.elu() Function" }, { "code": null, "e": 43168, "s": 43122, "text": "Tensorflow.js tf.layers.activation() Function" }, { "code": null, "e": 43214, "s": 43168, "text": "TensorFlow.js Layers Basic Complete Reference" }, { "code": null, "e": 43256, "s": 43214, "text": "Tensorflow.js tf.layers.conv1d() Function" }, { "code": null, "e": 43310, "s": 43256, "text": "TensorFlow.js Layers Convolutional Complete Reference" }, { "code": null, "e": 43349, "s": 43310, "text": "Tensorflow.js tf.layers.add() Function" }, { "code": null, "e": 43395, "s": 43349, "text": "TensorFlow.js Layers Merge Complete Reference" }, { "code": null, "e": 43453, "s": 43395, "text": "Tensorflow.js tf.layers.globalAveragePooling1d() Function" }, { "code": null, "e": 43501, "s": 43453, "text": "TensorFlow.js Layers Pooling Complete Reference" }, { "code": null, "e": 43547, "s": 43501, "text": "TensorFlow.js Layers Noise Complete Reference" }, { "code": null, "e": 43596, "s": 43547, "text": "Tensorflow.js tf.layers.bidirectional() Function" }, { "code": null, "e": 43647, "s": 43596, "text": "Tensorflow.js tf.layers.timeDistributed() Function" }, { "code": null, "e": 43695, "s": 43647, "text": "TensorFlow.js Layers Classes Complete Reference" }, { "code": null, "e": 43744, "s": 43695, "text": "Tensorflow.js tf.layers.zeroPadding2d() Function" }, { "code": null, "e": 43787, "s": 43744, "text": "Tensorflow.js tf.layers.masking() Function" }, { "code": null, "e": 43814, "s": 43787, "text": "Tensorflow.js Introduction" }, { "code": null, "e": 43869, "s": 43814, "text": "TensorFlow.js Operations Arithmetic Complete Reference" }, { "code": null, "e": 43924, "s": 43869, "text": "TensorFlow.js Operations Basic Math Complete Reference" }, { "code": null, "e": 43977, "s": 43924, "text": "TensorFlow.js Operations Matrices Complete Reference" }, { "code": null, "e": 44035, "s": 43977, "text": "TensorFlow.js Operations Normalization Complete Reference" }, { "code": null, "e": 44086, "s": 44035, "text": "TensorFlow.js Operations Images Complete Reference" }, { "code": null, "e": 44138, "s": 44086, "text": "TensorFlow.js Operations Logical Complete Reference" }, { "code": null, "e": 44193, "s": 44138, "text": "TensorFlow.js Operations Evaluation Complete Reference" }, { "code": null, "e": 44228, "s": 44193, "text": "Tensorflow.js tf.cumsum() Function" }, { "code": null, "e": 44292, "s": 44228, "text": "TensorFlow.js Operations Slicing and Joining Complete Reference" }, { "code": null, "e": 44345, "s": 44292, "text": "TensorFlow.js Operations Spectral Complete Reference" }, { "code": null, "e": 44392, "s": 44345, "text": "Tensorflow.js tf.unsortedSegmentSum() Function" }, { "code": null, "e": 44434, "s": 44392, "text": "Tensorflow.js tf.movingAverage() Function" }, { "code": null, "e": 44470, "s": 44434, "text": "Tensorflow.js tf.dropout() Function" }, { "code": null, "e": 44521, "s": 44470, "text": "TensorFlow.js Operations Signal Complete Reference" }, { "code": null, "e": 44565, "s": 44521, "text": "Tensorflow.js tf.linalg.bandPart() Function" }, { "code": null, "e": 44612, "s": 44565, "text": "Tensorflow.js tf.linalg.gramSchmidt() Function" }, { "code": null, "e": 44650, "s": 44612, "text": "Tensorflow.js tf.linalg.qr() Function" }, { "code": null, "e": 44701, "s": 44650, "text": "TensorFlow.js Operations Sparse Complete Reference" }, { "code": null, "e": 44728, "s": 44701, "text": "Tensorflow.js Introduction" }, { "code": null, "e": 44761, "s": 44728, "text": "Tensorflow.js tf.grad() Function" }, { "code": null, "e": 44795, "s": 44761, "text": "Tensorflow.js tf.grads() Function" }, { "code": null, "e": 44834, "s": 44795, "text": "Tensorflow.js tf.customGrad() Function" }, { "code": null, "e": 60210, "s": 44834, "text": "TensorFlow.js Training Gradients Complete ReferenceTensorflow.js TrainingTensorflow.js tf.train.momentum() FunctionTensorflow.js tf.train.adagrad() FunctionTensorFlow.js Training Optimizers Complete ReferenceTensorflow.js tf.losses.absoluteDifference() FunctionTensorflow.js tf.losses.computeWeightedLoss() FunctionTensorflow.js tf.losses.cosineDistance() FunctionTensorFlow.js Training Losses Complete ReferenceTensorflow.js tf.train.Optimizer ClassTensorflow.js tf.train.Optimizer class .minimize() MethodTensorFlow.js Training Classes Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.time() FunctionTensorflow.js tf.nextFrame() FunctionTensorflow.js tf.profile() FunctionTensorFlow.js Performance Memory Complete ReferenceTensorflow.js PerformanceTensorflow.js tf.disposeVariables() FunctionTensorflow.js tf.enableDebugMode() FunctionTensorflow.js tf.enableProdMode() FunctionTensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js IntroductionTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js IntroductionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js MetricsTable of ContentsTensorFlow.jsTensorflow.js IntroductionTensorflow.js TensorsTensorflow.js tf.tensor() FunctionTensorflow.js tf.scalar() FunctionTenserFlow.js Tensors Creation Complete ReferenceTensorflow.js tf.Tensor class .buffer() MethodTensorflow.js tf.Tensor class .bufferSync() MethodTensorFlow.js Tensors Classes Complete ReferenceTensorflow.js tf.booleanMaskAsync() FunctionTensorflow.js tf.concat() FunctionTensorFlow.js Tensors Transformations Complete ReferenceTensorFlow.js Slicing and Joining Complete ReferenceTensorflow.js tf.einsum() FunctionTensorflow.js tf.multinomial() FunctionTensorFlow.js Tensor Random Complete ReferenceTensorflow.js IntroductionTensorflow.js ModelsTensorflow.js tf.input() FunctionTensorflow.js tf.loadGraphModel() FunctionTensorflow.js tf.io.http() FunctionTensorFlow.js Models Loading Complete ReferenceTensorflow.js tf.io.copyModel() FunctionTensorflow.js tf.io.listModels() FunctionTensorflow.js tf.io.moveModel() FunctionTensorFlow.js Models Management Complete ReferenceTensorflow.js tf.GraphModel ClassTensorflow.js tf.GraphModel class .save() MethodTensorflow.js tf.GraphModel class .predict() MethodTensorflow.js tf.GraphModel class .execute() MethodTensorFlow.js Models Classes Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.layers.elu() FunctionTensorflow.js LayersTensorflow.js tf.layers.activation() FunctionTensorFlow.js Layers Basic Complete ReferenceTensorflow.js tf.layers.conv1d() FunctionTensorFlow.js Layers Convolutional Complete ReferenceTensorflow.js tf.layers.add() FunctionTensorFlow.js Layers Merge Complete ReferenceTensorflow.js tf.layers.globalAveragePooling1d() FunctionTensorFlow.js Layers Pooling Complete ReferenceTensorFlow.js Layers Noise Complete ReferenceTensorflow.js tf.layers.bidirectional() FunctionTensorflow.js tf.layers.timeDistributed() FunctionTensorFlow.js Layers Classes Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.layers.masking() FunctionTensorflow.js IntroductionTensorFlow.js Operations Arithmetic Complete ReferenceTensorFlow.js Operations Basic Math Complete ReferenceTensorFlow.js Operations Matrices Complete ReferenceTensorflow.js OperationsTensorFlow.js Operations Normalization Complete ReferenceTensorFlow.js Operations Images Complete ReferenceTensorFlow.js Operations Logical Complete ReferenceTensorFlow.js Operations Evaluation Complete ReferenceTensorflow.js tf.cumsum() FunctionTensorFlow.js Operations Slicing and Joining Complete ReferenceTensorFlow.js Operations Spectral Complete ReferenceTensorflow.js tf.unsortedSegmentSum() FunctionTensorflow.js tf.movingAverage() FunctionTensorflow.js tf.dropout() FunctionTensorFlow.js Operations Signal Complete ReferenceTensorflow.js tf.linalg.bandPart() FunctionTensorflow.js tf.linalg.gramSchmidt() FunctionTensorflow.js tf.linalg.qr() FunctionTensorFlow.js Operations Sparse Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.grad() FunctionTensorflow.js tf.grads() FunctionTensorflow.js tf.customGrad() FunctionTensorFlow.js Training Gradients Complete ReferenceTensorflow.js TrainingTensorflow.js tf.train.momentum() FunctionTensorflow.js tf.train.adagrad() FunctionTensorFlow.js Training Optimizers Complete ReferenceTensorflow.js tf.losses.absoluteDifference() FunctionTensorflow.js tf.losses.computeWeightedLoss() FunctionTensorflow.js tf.losses.cosineDistance() FunctionTensorFlow.js Training Losses Complete ReferenceTensorflow.js tf.train.Optimizer ClassTensorflow.js tf.train.Optimizer class .minimize() MethodTensorFlow.js Training Classes Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.time() FunctionTensorflow.js tf.nextFrame() FunctionTensorflow.js tf.profile() FunctionTensorFlow.js Performance Memory Complete ReferenceTensorflow.js PerformanceTensorflow.js tf.disposeVariables() FunctionTensorflow.js tf.enableDebugMode() FunctionTensorflow.js tf.enableProdMode() FunctionTensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js IntroductionTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js IntroductionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js MetricsImprove Article\n\nSave Article\n\nLike Article\n\nTensorflow.js IntroductionLast Updated :\n15 Aug, 2021What is Tensorflow.js?TensorFlow.js is a JavaScript library for training and deploying machine learning models on web applications and in Node.js. You can develop the machine learning models from scratch using tensorflow.js or can use the APIs provided to train your existing models in the browser or on your Node.js server.To learn more you can directly go to this link: https://www.tensorflow.org/resources/learn-ml/basics-of-tensorflow-for-js-development.Prerequisite: Before starting Tensorflow.js, you need to know the following:For browser:HTML: Basics knowledge of HTML is requiredJavaScript: Good knowledge of JS is required For server-side:Node.js: Having a good command of Node.js. Also since Node.js is a JS runtime, so having command over JavaScript would help a lot.Other requirements:NPM or Yarn: These are packages that need to be installed in your system.Setting Up Tensorflow.js:Browser Setup There are two ways to add TensorFlow.js in your browser-based application:Using script tags.Installation from NPM1. Using Script tags: Add the following script tag to your main HTML file.<script src=”https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js”></script>Example:HTMLHTML<!DOCTYPE html><html lang=\"en\"> <head> <script src=\"https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js\"> </script></head> <body> <script> // Value of a scalar var value = \"Hello Geeks! Tensorflow here.\" // Creating the value of a scalar var tens = tf.scalar(value) document.write(tens) </script></body> </html> Output:2. Using NPM/ yarn: We can either use NPM or Yarn to install tensorflow.js.yarn add @tensorflow/tfjsornpm install @tensorflow/tfjsNode.js Setup:Option 1: Install TensorFlow.js with native C++ bindings.yarn add @tensorflow/tfjs-nodeornpm install @tensorflow/tfjs-nodeOption 2: (Linux Only) If your system has a NVIDIA® GPU with CUDA support, use the GPU package even for higher performance.yarn add @tensorflow/tfjs-node-gpuornpm install @tensorflow/tfjs-node-gpuOption 3: Install the pure JavaScript version. This is the slowest option performance-wise.yarn add @tensorflow/tfjsornpm install @tensorflow/tfjsMy Personal Notes\narrow_drop_upSave\n\nLike0PreviousTensorFlow.js Browser Complete ReferenceNext\nTensorflow.js tf.backend() FunctionRecommended ArticlesPage :Introduction to Apache Maven | A build automation tool for Java projects17, May 18Introduction to React Native07, Jun 17Introduction to Apache POI17, Jul 17Apache Kafka | Introduction28, Aug 17Introduction of Firewall in Computer Network31, Aug 17WordPress Introduction23, Jul 18Introduction to Object Oriented Programming in JavaScript18, Sep 17ReactJS | Introduction to JSX09, Mar 18React.js (Introduction and Working)27, Sep 17Introduction to Web Scraping06, Nov 19PHP | MySQL Database Introduction22, Nov 17jQuery | Introduction29, Jan 18Django Introduction | Set 2 (Creating a Project)01, Feb 18Introduction to JavaScript29, Jan 20Introduction to Xamarin | A Software for Mobile App Development and App Creation16, Mar 18ReactJS | Calculator App ( Introduction )25, Mar 18CSS Introduction10, Apr 18Introduction to Web Development and the Holy Trinity of it27, Apr 18Introduction to Postman for API Development28, May 18Ajax Introduction09, Jul 18XHTML | Introduction31, Aug 18REST API (Introduction)02, Sep 18Introduction to JavaScript Course | Learn how to Build a task tracker using JavaScript24, Apr 19Introduction to Scripting Languages21, Sep 18Article Contributed By :ghoshsuman0129@ghoshsuman0129Vote for difficultyEasy\nNormal\nMedium\nHard\nExpertArticle Tags :Tensorflow.jsJavaScriptWeb TechnologiesImprove ArticleReport IssueWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nLoad CommentsWhat's NewInterview Series- Prepare, Practice & UpskillView DetailsData Structures & Algorithms- Self Paced CourseView DetailsComplete Interview PreparationView DetailsMost popular in JavaScriptRemove elements from a JavaScript ArrayConvert a string to an integer in JavaScriptDifference between var, let and const keywords in JavaScriptDifferences between Functional Components and Class Components in ReactHow to calculate the number of days between two dates in javascript?Most visited in Web TechnologiesRemove elements from a JavaScript ArrayInstallation of Node.js on LinuxConvert a string to an integer in JavaScriptHow to fetch data from an API in ReactJS ?How to insert spaces/tabs in text using HTML/CSS?Improve your Coding Skills with PracticeTry It!\n5th Floor, A-118,Sector-136, Noida, Uttar Pradesh - 201305\[email protected] UsCareersIn MediaContact UsPrivacy PolicyCopyright PolicyLearnAlgorithmsData StructuresSDE Cheat SheetMachine learningCS SubjectsVideo TutorialsNewsTop NewsTechnologyWork & CareerBusinessFinanceLifestyleLanguagesPythonJavaCPPGolangC#SQLWeb DevelopmentWeb TutorialsDjango TutorialHTMLCSSJavaScriptBootstrapContributeWrite an ArticleImprove an ArticlePick Topics to WriteWrite Interview ExperienceInternshipsVideo Internship@geeksforgeeks\n, Some rights reserved \nWe use cookies to ensure you have the best browsing experience on our website. By using our site, you\nacknowledge that you have read and understood our\nCookie Policy &\n Privacy Policy\n\nGot It !\nStart Your Coding Journey Now!Login\nRegister" }, { "code": null, "e": 60253, "s": 60210, "text": "Tensorflow.js tf.train.momentum() Function" }, { "code": null, "e": 60295, "s": 60253, "text": "Tensorflow.js tf.train.adagrad() Function" }, { "code": null, "e": 60348, "s": 60295, "text": "TensorFlow.js Training Optimizers Complete Reference" }, { "code": null, "e": 60402, "s": 60348, "text": "Tensorflow.js tf.losses.absoluteDifference() Function" }, { "code": null, "e": 60457, "s": 60402, "text": "Tensorflow.js tf.losses.computeWeightedLoss() Function" }, { "code": null, "e": 60507, "s": 60457, "text": "Tensorflow.js tf.losses.cosineDistance() Function" }, { "code": null, "e": 60556, "s": 60507, "text": "TensorFlow.js Training Losses Complete Reference" }, { "code": null, "e": 60595, "s": 60556, "text": "Tensorflow.js tf.train.Optimizer Class" }, { "code": null, "e": 60653, "s": 60595, "text": "Tensorflow.js tf.train.Optimizer class .minimize() Method" }, { "code": null, "e": 60703, "s": 60653, "text": "TensorFlow.js Training Classes Complete Reference" }, { "code": null, "e": 60730, "s": 60703, "text": "Tensorflow.js Introduction" }, { "code": null, "e": 60763, "s": 60730, "text": "Tensorflow.js tf.time() Function" }, { "code": null, "e": 60801, "s": 60763, "text": "Tensorflow.js tf.nextFrame() Function" }, { "code": null, "e": 60837, "s": 60801, "text": "Tensorflow.js tf.profile() Function" }, { "code": null, "e": 60889, "s": 60837, "text": "TensorFlow.js Performance Memory Complete Reference" }, { "code": null, "e": 60934, "s": 60889, "text": "Tensorflow.js tf.disposeVariables() Function" }, { "code": null, "e": 60978, "s": 60934, "text": "Tensorflow.js tf.enableDebugMode() Function" }, { "code": null, "e": 61021, "s": 60978, "text": "Tensorflow.js tf.enableProdMode() Function" }, { "code": null, "e": 63569, "s": 61021, "text": "Tensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js IntroductionTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js IntroductionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js Metrics" }, { "code": null, "e": 63614, "s": 63569, "text": "TensorFlow.js Environment Complete Reference" }, { "code": null, "e": 63641, "s": 63614, "text": "Tensorflow.js Introduction" }, { "code": null, "e": 63692, "s": 63641, "text": "Tensorflow.js tf.metrics.binaryAccuracy() Function" }, { "code": null, "e": 63747, "s": 63692, "text": "Tensorflow.js tf.metrics.binaryCrossentropy() Function" }, { "code": null, "e": 63803, "s": 63747, "text": "Tensorflow.js tf.metrics.categoricalAccuracy() Function" }, { "code": null, "e": 63863, "s": 63803, "text": "Tensorflow.js tf.metrics.categoricalCrossentropy() Function" }, { "code": null, "e": 63915, "s": 63863, "text": "Tensorflow.js tf.metrics.cosineProximity() Function" }, { "code": null, "e": 63968, "s": 63915, "text": "Tensorflow.js tf.metrics.meanSquaredError() Function" }, { "code": null, "e": 64014, "s": 63968, "text": "Tensorflow.js tf.metrics.precision() Function" }, { "code": null, "e": 64057, "s": 64014, "text": "Tensorflow.js tf.metrics.recall() Function" }, { "code": null, "e": 64119, "s": 64057, "text": "Tensorflow.js tf.metrics.sparseCategoricalAccuracy() Function" }, { "code": null, "e": 64160, "s": 64119, "text": "TensorFlow.js Metrics Complete Reference" }, { "code": null, "e": 64187, "s": 64160, "text": "Tensorflow.js Introduction" }, { "code": null, "e": 64235, "s": 64187, "text": "Tensorflow.js tf.initializers.Initializer Class" }, { "code": null, "e": 64283, "s": 64235, "text": "Tensorflow.js tf.initializers.constant() Method" }, { "code": null, "e": 64337, "s": 64283, "text": "Tensorflow.js tf.initializers.glorotNormal() Function" }, { "code": null, "e": 64392, "s": 64337, "text": "Tensorflow.js tf.initializers.glorotUniform() Function" }, { "code": null, "e": 64442, "s": 64392, "text": "Tensorflow.js tf.initializers.heNormal() Function" }, { "code": null, "e": 64493, "s": 64442, "text": "Tensorflow.js tf.initializers.heUniform() Function" }, { "code": null, "e": 64539, "s": 64493, "text": "TensorFlow.js Initializers Complete Reference" }, { "code": null, "e": 64566, "s": 64539, "text": "Tensorflow.js Introduction" }, { "code": null, "e": 64610, "s": 64566, "text": "Tensorflow.js tf.regularizers.l1() Function" }, { "code": null, "e": 64656, "s": 64610, "text": "Tensorflow.js tf.regularizers.l1l2() Function" }, { "code": null, "e": 64700, "s": 64656, "text": "Tensorflow.js tf.regularizers.l2() Function" }, { "code": null, "e": 64727, "s": 64700, "text": "Tensorflow.js Introduction" }, { "code": null, "e": 64764, "s": 64727, "text": "Tensorflow.js tf.data.csv() Function" }, { "code": null, "e": 64807, "s": 64764, "text": "Tensorflow.js tf.data.generator() Function" }, { "code": null, "e": 66034, "s": 64807, "text": "Tensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js IntroductionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js Metrics" }, { "code": null, "e": 66081, "s": 66034, "text": "TensorFlow.js Data Creation Complete Reference" }, { "code": null, "e": 66118, "s": 66081, "text": "Tensorflow.js tf.data.zip() Function" }, { "code": null, "e": 66170, "s": 66118, "text": "Tensorflow.js tf.data.Dataset class .batch() Method" }, { "code": null, "e": 66217, "s": 66170, "text": "TensorFlow.js Data Classes Complete References" }, { "code": null, "e": 66244, "s": 66217, "text": "Tensorflow.js Introduction" }, { "code": null, "e": 66284, "s": 66244, "text": "Tensorflow.js tf.util.assert() Function" }, { "code": null, "e": 66339, "s": 66284, "text": "Tensorflow.js tf.util.createShuffledIndices() Function" }, { "code": null, "e": 66380, "s": 66339, "text": "Tensorflow.js tf.decodeString() Function" }, { "code": null, "e": 66421, "s": 66380, "text": "Tensorflow.js tf.encodeString() Function" }, { "code": null, "e": 66455, "s": 66421, "text": "Tensorflow.js tf.fetch() Function" }, { "code": null, "e": 66496, "s": 66455, "text": "Tensorflow.js tf.util.flatten() Function" }, { "code": null, "e": 66533, "s": 66496, "text": "Tensorflow.js tf.util.now() Function" }, { "code": null, "e": 66574, "s": 66533, "text": "Tensorflow.js tf.util.shuffle() Function" }, { "code": null, "e": 66620, "s": 66574, "text": "Tensorflow.js tf.util.shuffleCombo() Function" }, { "code": null, "e": 66667, "s": 66620, "text": "Tensorflow.js tf.browser.fromPixels() Function" }, { "code": null, "e": 66719, "s": 66667, "text": "Tensorflow.js tf.browser.fromPixelsAsync() Function" }, { "code": null, "e": 66764, "s": 66719, "text": "Tensorflow.js tf.browser.toPixels() Function" }, { "code": null, "e": 66805, "s": 66764, "text": "TensorFlow.js Browser Complete Reference" }, { "code": null, "e": 66832, "s": 66805, "text": "Tensorflow.js Introduction" }, { "code": null, "e": 66868, "s": 66832, "text": "Tensorflow.js tf.backend() Function" }, { "code": null, "e": 66907, "s": 66868, "text": "Tensorflow.js tf.getBackend() Function" }, { "code": null, "e": 66941, "s": 66907, "text": "Tensorflow.js tf.ready() Function" }, { "code": null, "e": 66985, "s": 66941, "text": "Tensorflow.js tf.registerBackend() Function" }, { "code": null, "e": 67027, "s": 66985, "text": "Tensorflow.js tf.removeBackend() Function" }, { "code": null, "e": 67066, "s": 67027, "text": "Tensorflow.js tf.setBackend() Function" }, { "code": null, "e": 67118, "s": 67066, "text": "Tensorflow.js tf.callbacks.earlyStopping() Function" }, { "code": null, "e": 67132, "s": 67118, "text": "TensorFlow.js" }, { "code": null, "e": 78188, "s": 67132, "text": "Tensorflow.js IntroductionTensorflow.js TensorsTensorflow.js tf.tensor() FunctionTensorflow.js tf.scalar() FunctionTenserFlow.js Tensors Creation Complete ReferenceTensorflow.js tf.Tensor class .buffer() MethodTensorflow.js tf.Tensor class .bufferSync() MethodTensorFlow.js Tensors Classes Complete ReferenceTensorflow.js tf.booleanMaskAsync() FunctionTensorflow.js tf.concat() FunctionTensorFlow.js Tensors Transformations Complete ReferenceTensorFlow.js Slicing and Joining Complete ReferenceTensorflow.js tf.einsum() FunctionTensorflow.js tf.multinomial() FunctionTensorFlow.js Tensor Random Complete ReferenceTensorflow.js IntroductionTensorflow.js ModelsTensorflow.js tf.input() FunctionTensorflow.js tf.loadGraphModel() FunctionTensorflow.js tf.io.http() FunctionTensorFlow.js Models Loading Complete ReferenceTensorflow.js tf.io.copyModel() FunctionTensorflow.js tf.io.listModels() FunctionTensorflow.js tf.io.moveModel() FunctionTensorFlow.js Models Management Complete ReferenceTensorflow.js tf.GraphModel ClassTensorflow.js tf.GraphModel class .save() MethodTensorflow.js tf.GraphModel class .predict() MethodTensorflow.js tf.GraphModel class .execute() MethodTensorFlow.js Models Classes Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.layers.elu() FunctionTensorflow.js LayersTensorflow.js tf.layers.activation() FunctionTensorFlow.js Layers Basic Complete ReferenceTensorflow.js tf.layers.conv1d() FunctionTensorFlow.js Layers Convolutional Complete ReferenceTensorflow.js tf.layers.add() FunctionTensorFlow.js Layers Merge Complete ReferenceTensorflow.js tf.layers.globalAveragePooling1d() FunctionTensorFlow.js Layers Pooling Complete ReferenceTensorFlow.js Layers Noise Complete ReferenceTensorflow.js tf.layers.bidirectional() FunctionTensorflow.js tf.layers.timeDistributed() FunctionTensorFlow.js Layers Classes Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.layers.masking() FunctionTensorflow.js IntroductionTensorFlow.js Operations Arithmetic Complete ReferenceTensorFlow.js Operations Basic Math Complete ReferenceTensorFlow.js Operations Matrices Complete ReferenceTensorflow.js OperationsTensorFlow.js Operations Normalization Complete ReferenceTensorFlow.js Operations Images Complete ReferenceTensorFlow.js Operations Logical Complete ReferenceTensorFlow.js Operations Evaluation Complete ReferenceTensorflow.js tf.cumsum() FunctionTensorFlow.js Operations Slicing and Joining Complete ReferenceTensorFlow.js Operations Spectral Complete ReferenceTensorflow.js tf.unsortedSegmentSum() FunctionTensorflow.js tf.movingAverage() FunctionTensorflow.js tf.dropout() FunctionTensorFlow.js Operations Signal Complete ReferenceTensorflow.js tf.linalg.bandPart() FunctionTensorflow.js tf.linalg.gramSchmidt() FunctionTensorflow.js tf.linalg.qr() FunctionTensorFlow.js Operations Sparse Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.grad() FunctionTensorflow.js tf.grads() FunctionTensorflow.js tf.customGrad() FunctionTensorFlow.js Training Gradients Complete ReferenceTensorflow.js TrainingTensorflow.js tf.train.momentum() FunctionTensorflow.js tf.train.adagrad() FunctionTensorFlow.js Training Optimizers Complete ReferenceTensorflow.js tf.losses.absoluteDifference() FunctionTensorflow.js tf.losses.computeWeightedLoss() FunctionTensorflow.js tf.losses.cosineDistance() FunctionTensorFlow.js Training Losses Complete ReferenceTensorflow.js tf.train.Optimizer ClassTensorflow.js tf.train.Optimizer class .minimize() MethodTensorFlow.js Training Classes Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.time() FunctionTensorflow.js tf.nextFrame() FunctionTensorflow.js tf.profile() FunctionTensorFlow.js Performance Memory Complete ReferenceTensorflow.js PerformanceTensorflow.js tf.disposeVariables() FunctionTensorflow.js tf.enableDebugMode() FunctionTensorflow.js tf.enableProdMode() FunctionTensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js IntroductionTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js IntroductionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js MetricsImprove Article\n\nSave Article\n\nLike Article\n\nTensorflow.js IntroductionLast Updated :\n15 Aug, 2021What is Tensorflow.js?TensorFlow.js is a JavaScript library for training and deploying machine learning models on web applications and in Node.js. You can develop the machine learning models from scratch using tensorflow.js or can use the APIs provided to train your existing models in the browser or on your Node.js server.To learn more you can directly go to this link: https://www.tensorflow.org/resources/learn-ml/basics-of-tensorflow-for-js-development.Prerequisite: Before starting Tensorflow.js, you need to know the following:For browser:HTML: Basics knowledge of HTML is requiredJavaScript: Good knowledge of JS is required For server-side:Node.js: Having a good command of Node.js. Also since Node.js is a JS runtime, so having command over JavaScript would help a lot.Other requirements:NPM or Yarn: These are packages that need to be installed in your system.Setting Up Tensorflow.js:Browser Setup There are two ways to add TensorFlow.js in your browser-based application:Using script tags.Installation from NPM1. Using Script tags: Add the following script tag to your main HTML file.<script src=”https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js”></script>Example:HTMLHTML<!DOCTYPE html><html lang=\"en\"> <head> <script src=\"https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js\"> </script></head> <body> <script> // Value of a scalar var value = \"Hello Geeks! Tensorflow here.\" // Creating the value of a scalar var tens = tf.scalar(value) document.write(tens) </script></body> </html> Output:2. Using NPM/ yarn: We can either use NPM or Yarn to install tensorflow.js.yarn add @tensorflow/tfjsornpm install @tensorflow/tfjsNode.js Setup:Option 1: Install TensorFlow.js with native C++ bindings.yarn add @tensorflow/tfjs-nodeornpm install @tensorflow/tfjs-nodeOption 2: (Linux Only) If your system has a NVIDIA® GPU with CUDA support, use the GPU package even for higher performance.yarn add @tensorflow/tfjs-node-gpuornpm install @tensorflow/tfjs-node-gpuOption 3: Install the pure JavaScript version. This is the slowest option performance-wise.yarn add @tensorflow/tfjsornpm install @tensorflow/tfjsMy Personal Notes\narrow_drop_upSave\n\nLike0PreviousTensorFlow.js Browser Complete ReferenceNext\nTensorflow.js tf.backend() FunctionRecommended ArticlesPage :Introduction to Apache Maven | A build automation tool for Java projects17, May 18Introduction to React Native07, Jun 17Introduction to Apache POI17, Jul 17Apache Kafka | Introduction28, Aug 17Introduction of Firewall in Computer Network31, Aug 17WordPress Introduction23, Jul 18Introduction to Object Oriented Programming in JavaScript18, Sep 17ReactJS | Introduction to JSX09, Mar 18React.js (Introduction and Working)27, Sep 17Introduction to Web Scraping06, Nov 19PHP | MySQL Database Introduction22, Nov 17jQuery | Introduction29, Jan 18Django Introduction | Set 2 (Creating a Project)01, Feb 18Introduction to JavaScript29, Jan 20Introduction to Xamarin | A Software for Mobile App Development and App Creation16, Mar 18ReactJS | Calculator App ( Introduction )25, Mar 18CSS Introduction10, Apr 18Introduction to Web Development and the Holy Trinity of it27, Apr 18Introduction to Postman for API Development28, May 18Ajax Introduction09, Jul 18XHTML | Introduction31, Aug 18REST API (Introduction)02, Sep 18Introduction to JavaScript Course | Learn how to Build a task tracker using JavaScript24, Apr 19Introduction to Scripting Languages21, Sep 18Article Contributed By :ghoshsuman0129@ghoshsuman0129Vote for difficultyEasy\nNormal\nMedium\nHard\nExpertArticle Tags :Tensorflow.jsJavaScriptWeb TechnologiesImprove ArticleReport IssueWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nLoad CommentsWhat's NewInterview Series- Prepare, Practice & UpskillView DetailsData Structures & Algorithms- Self Paced CourseView DetailsComplete Interview PreparationView DetailsMost popular in JavaScriptRemove elements from a JavaScript ArrayConvert a string to an integer in JavaScriptDifference between var, let and const keywords in JavaScriptDifferences between Functional Components and Class Components in ReactHow to calculate the number of days between two dates in javascript?Most visited in Web TechnologiesRemove elements from a JavaScript ArrayInstallation of Node.js on LinuxConvert a string to an integer in JavaScriptHow to fetch data from an API in ReactJS ?How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 78223, "s": 78188, "text": "Tensorflow.js tf.tensor() Function" }, { "code": null, "e": 78258, "s": 78223, "text": "Tensorflow.js tf.scalar() Function" }, { "code": null, "e": 78308, "s": 78258, "text": "TenserFlow.js Tensors Creation Complete Reference" }, { "code": null, "e": 78355, "s": 78308, "text": "Tensorflow.js tf.Tensor class .buffer() Method" }, { "code": null, "e": 78406, "s": 78355, "text": "Tensorflow.js tf.Tensor class .bufferSync() Method" }, { "code": null, "e": 78455, "s": 78406, "text": "TensorFlow.js Tensors Classes Complete Reference" }, { "code": null, "e": 78500, "s": 78455, "text": "Tensorflow.js tf.booleanMaskAsync() Function" }, { "code": null, "e": 78535, "s": 78500, "text": "Tensorflow.js tf.concat() Function" }, { "code": null, "e": 78592, "s": 78535, "text": "TensorFlow.js Tensors Transformations Complete Reference" }, { "code": null, "e": 78645, "s": 78592, "text": "TensorFlow.js Slicing and Joining Complete Reference" }, { "code": null, "e": 78680, "s": 78645, "text": "Tensorflow.js tf.einsum() Function" }, { "code": null, "e": 78720, "s": 78680, "text": "Tensorflow.js tf.multinomial() Function" }, { "code": null, "e": 78767, "s": 78720, "text": "TensorFlow.js Tensor Random Complete Reference" }, { "code": null, "e": 78794, "s": 78767, "text": "Tensorflow.js Introduction" }, { "code": null, "e": 78828, "s": 78794, "text": "Tensorflow.js tf.input() Function" }, { "code": null, "e": 78871, "s": 78828, "text": "Tensorflow.js tf.loadGraphModel() Function" }, { "code": null, "e": 78907, "s": 78871, "text": "Tensorflow.js tf.io.http() Function" }, { "code": null, "e": 78955, "s": 78907, "text": "TensorFlow.js Models Loading Complete Reference" }, { "code": null, "e": 78996, "s": 78955, "text": "Tensorflow.js tf.io.copyModel() Function" }, { "code": null, "e": 79038, "s": 78996, "text": "Tensorflow.js tf.io.listModels() Function" }, { "code": null, "e": 79079, "s": 79038, "text": "Tensorflow.js tf.io.moveModel() Function" }, { "code": null, "e": 79130, "s": 79079, "text": "TensorFlow.js Models Management Complete Reference" }, { "code": null, "e": 79164, "s": 79130, "text": "Tensorflow.js tf.GraphModel Class" }, { "code": null, "e": 79213, "s": 79164, "text": "Tensorflow.js tf.GraphModel class .save() Method" }, { "code": null, "e": 79265, "s": 79213, "text": "Tensorflow.js tf.GraphModel class .predict() Method" }, { "code": null, "e": 79317, "s": 79265, "text": "Tensorflow.js tf.GraphModel class .execute() Method" }, { "code": null, "e": 79365, "s": 79317, "text": "TensorFlow.js Models Classes Complete Reference" }, { "code": null, "e": 79392, "s": 79365, "text": "Tensorflow.js Introduction" }, { "code": null, "e": 79431, "s": 79392, "text": "Tensorflow.js tf.layers.elu() Function" }, { "code": null, "e": 79477, "s": 79431, "text": "Tensorflow.js tf.layers.activation() Function" }, { "code": null, "e": 79523, "s": 79477, "text": "TensorFlow.js Layers Basic Complete Reference" }, { "code": null, "e": 79565, "s": 79523, "text": "Tensorflow.js tf.layers.conv1d() Function" }, { "code": null, "e": 79619, "s": 79565, "text": "TensorFlow.js Layers Convolutional Complete Reference" }, { "code": null, "e": 79658, "s": 79619, "text": "Tensorflow.js tf.layers.add() Function" }, { "code": null, "e": 79704, "s": 79658, "text": "TensorFlow.js Layers Merge Complete Reference" }, { "code": null, "e": 79762, "s": 79704, "text": "Tensorflow.js tf.layers.globalAveragePooling1d() Function" }, { "code": null, "e": 79810, "s": 79762, "text": "TensorFlow.js Layers Pooling Complete Reference" }, { "code": null, "e": 79856, "s": 79810, "text": "TensorFlow.js Layers Noise Complete Reference" }, { "code": null, "e": 79905, "s": 79856, "text": "Tensorflow.js tf.layers.bidirectional() Function" }, { "code": null, "e": 79956, "s": 79905, "text": "Tensorflow.js tf.layers.timeDistributed() Function" }, { "code": null, "e": 80004, "s": 79956, "text": "TensorFlow.js Layers Classes Complete Reference" }, { "code": null, "e": 80053, "s": 80004, "text": "Tensorflow.js tf.layers.zeroPadding2d() Function" }, { "code": null, "e": 80096, "s": 80053, "text": "Tensorflow.js tf.layers.masking() Function" }, { "code": null, "e": 80123, "s": 80096, "text": "Tensorflow.js Introduction" }, { "code": null, "e": 80178, "s": 80123, "text": "TensorFlow.js Operations Arithmetic Complete Reference" }, { "code": null, "e": 80233, "s": 80178, "text": "TensorFlow.js Operations Basic Math Complete Reference" }, { "code": null, "e": 80286, "s": 80233, "text": "TensorFlow.js Operations Matrices Complete Reference" }, { "code": null, "e": 80344, "s": 80286, "text": "TensorFlow.js Operations Normalization Complete Reference" }, { "code": null, "e": 80395, "s": 80344, "text": "TensorFlow.js Operations Images Complete Reference" }, { "code": null, "e": 80447, "s": 80395, "text": "TensorFlow.js Operations Logical Complete Reference" }, { "code": null, "e": 80502, "s": 80447, "text": "TensorFlow.js Operations Evaluation Complete Reference" }, { "code": null, "e": 80537, "s": 80502, "text": "Tensorflow.js tf.cumsum() Function" }, { "code": null, "e": 80601, "s": 80537, "text": "TensorFlow.js Operations Slicing and Joining Complete Reference" }, { "code": null, "e": 80654, "s": 80601, "text": "TensorFlow.js Operations Spectral Complete Reference" }, { "code": null, "e": 80701, "s": 80654, "text": "Tensorflow.js tf.unsortedSegmentSum() Function" }, { "code": null, "e": 80743, "s": 80701, "text": "Tensorflow.js tf.movingAverage() Function" }, { "code": null, "e": 80779, "s": 80743, "text": "Tensorflow.js tf.dropout() Function" }, { "code": null, "e": 80830, "s": 80779, "text": "TensorFlow.js Operations Signal Complete Reference" }, { "code": null, "e": 80874, "s": 80830, "text": "Tensorflow.js tf.linalg.bandPart() Function" }, { "code": null, "e": 80921, "s": 80874, "text": "Tensorflow.js tf.linalg.gramSchmidt() Function" }, { "code": null, "e": 80959, "s": 80921, "text": "Tensorflow.js tf.linalg.qr() Function" }, { "code": null, "e": 81010, "s": 80959, "text": "TensorFlow.js Operations Sparse Complete Reference" }, { "code": null, "e": 81037, "s": 81010, "text": "Tensorflow.js Introduction" }, { "code": null, "e": 81070, "s": 81037, "text": "Tensorflow.js tf.grad() Function" }, { "code": null, "e": 81104, "s": 81070, "text": "Tensorflow.js tf.grads() Function" }, { "code": null, "e": 81143, "s": 81104, "text": "Tensorflow.js tf.customGrad() Function" }, { "code": null, "e": 89199, "s": 81143, "text": "TensorFlow.js Training Gradients Complete ReferenceTensorflow.js TrainingTensorflow.js tf.train.momentum() FunctionTensorflow.js tf.train.adagrad() FunctionTensorFlow.js Training Optimizers Complete ReferenceTensorflow.js tf.losses.absoluteDifference() FunctionTensorflow.js tf.losses.computeWeightedLoss() FunctionTensorflow.js tf.losses.cosineDistance() FunctionTensorFlow.js Training Losses Complete ReferenceTensorflow.js tf.train.Optimizer ClassTensorflow.js tf.train.Optimizer class .minimize() MethodTensorFlow.js Training Classes Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.time() FunctionTensorflow.js tf.nextFrame() FunctionTensorflow.js tf.profile() FunctionTensorFlow.js Performance Memory Complete ReferenceTensorflow.js PerformanceTensorflow.js tf.disposeVariables() FunctionTensorflow.js tf.enableDebugMode() FunctionTensorflow.js tf.enableProdMode() FunctionTensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js IntroductionTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js IntroductionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js MetricsImprove Article\n\nSave Article\n\nLike Article\n\nTensorflow.js IntroductionLast Updated :\n15 Aug, 2021What is Tensorflow.js?TensorFlow.js is a JavaScript library for training and deploying machine learning models on web applications and in Node.js. You can develop the machine learning models from scratch using tensorflow.js or can use the APIs provided to train your existing models in the browser or on your Node.js server.To learn more you can directly go to this link: https://www.tensorflow.org/resources/learn-ml/basics-of-tensorflow-for-js-development.Prerequisite: Before starting Tensorflow.js, you need to know the following:For browser:HTML: Basics knowledge of HTML is requiredJavaScript: Good knowledge of JS is required For server-side:Node.js: Having a good command of Node.js. Also since Node.js is a JS runtime, so having command over JavaScript would help a lot.Other requirements:NPM or Yarn: These are packages that need to be installed in your system.Setting Up Tensorflow.js:Browser Setup There are two ways to add TensorFlow.js in your browser-based application:Using script tags.Installation from NPM1. Using Script tags: Add the following script tag to your main HTML file.<script src=”https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js”></script>Example:HTMLHTML<!DOCTYPE html><html lang=\"en\"> <head> <script src=\"https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js\"> </script></head> <body> <script> // Value of a scalar var value = \"Hello Geeks! Tensorflow here.\" // Creating the value of a scalar var tens = tf.scalar(value) document.write(tens) </script></body> </html> Output:2. Using NPM/ yarn: We can either use NPM or Yarn to install tensorflow.js.yarn add @tensorflow/tfjsornpm install @tensorflow/tfjsNode.js Setup:Option 1: Install TensorFlow.js with native C++ bindings.yarn add @tensorflow/tfjs-nodeornpm install @tensorflow/tfjs-nodeOption 2: (Linux Only) If your system has a NVIDIA® GPU with CUDA support, use the GPU package even for higher performance.yarn add @tensorflow/tfjs-node-gpuornpm install @tensorflow/tfjs-node-gpuOption 3: Install the pure JavaScript version. This is the slowest option performance-wise.yarn add @tensorflow/tfjsornpm install @tensorflow/tfjsMy Personal Notes\narrow_drop_upSave\n\nLike0PreviousTensorFlow.js Browser Complete ReferenceNext\nTensorflow.js tf.backend() FunctionRecommended ArticlesPage :Introduction to Apache Maven | A build automation tool for Java projects17, May 18Introduction to React Native07, Jun 17Introduction to Apache POI17, Jul 17Apache Kafka | Introduction28, Aug 17Introduction of Firewall in Computer Network31, Aug 17WordPress Introduction23, Jul 18Introduction to Object Oriented Programming in JavaScript18, Sep 17ReactJS | Introduction to JSX09, Mar 18React.js (Introduction and Working)27, Sep 17Introduction to Web Scraping06, Nov 19PHP | MySQL Database Introduction22, Nov 17jQuery | Introduction29, Jan 18Django Introduction | Set 2 (Creating a Project)01, Feb 18Introduction to JavaScript29, Jan 20Introduction to Xamarin | A Software for Mobile App Development and App Creation16, Mar 18ReactJS | Calculator App ( Introduction )25, Mar 18CSS Introduction10, Apr 18Introduction to Web Development and the Holy Trinity of it27, Apr 18Introduction to Postman for API Development28, May 18Ajax Introduction09, Jul 18XHTML | Introduction31, Aug 18REST API (Introduction)02, Sep 18Introduction to JavaScript Course | Learn how to Build a task tracker using JavaScript24, Apr 19Introduction to Scripting Languages21, Sep 18Article Contributed By :ghoshsuman0129@ghoshsuman0129Vote for difficultyEasy\nNormal\nMedium\nHard\nExpertArticle Tags :Tensorflow.jsJavaScriptWeb TechnologiesImprove ArticleReport IssueWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nLoad CommentsWhat's NewInterview Series- Prepare, Practice & UpskillView DetailsData Structures & Algorithms- Self Paced CourseView DetailsComplete Interview PreparationView DetailsMost popular in JavaScriptRemove elements from a JavaScript ArrayConvert a string to an integer in JavaScriptDifference between var, let and const keywords in JavaScriptDifferences between Functional Components and Class Components in ReactHow to calculate the number of days between two dates in javascript?Most visited in Web TechnologiesRemove elements from a JavaScript ArrayInstallation of Node.js on LinuxConvert a string to an integer in JavaScriptHow to fetch data from an API in ReactJS ?How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 89242, "s": 89199, "text": "Tensorflow.js tf.train.momentum() Function" }, { "code": null, "e": 89284, "s": 89242, "text": "Tensorflow.js tf.train.adagrad() Function" }, { "code": null, "e": 89337, "s": 89284, "text": "TensorFlow.js Training Optimizers Complete Reference" }, { "code": null, "e": 89391, "s": 89337, "text": "Tensorflow.js tf.losses.absoluteDifference() Function" }, { "code": null, "e": 89446, "s": 89391, "text": "Tensorflow.js tf.losses.computeWeightedLoss() Function" }, { "code": null, "e": 89496, "s": 89446, "text": "Tensorflow.js tf.losses.cosineDistance() Function" }, { "code": null, "e": 89545, "s": 89496, "text": "TensorFlow.js Training Losses Complete Reference" }, { "code": null, "e": 89584, "s": 89545, "text": "Tensorflow.js tf.train.Optimizer Class" }, { "code": null, "e": 89642, "s": 89584, "text": "Tensorflow.js tf.train.Optimizer class .minimize() Method" }, { "code": null, "e": 89692, "s": 89642, "text": "TensorFlow.js Training Classes Complete Reference" }, { "code": null, "e": 89719, "s": 89692, "text": "Tensorflow.js Introduction" }, { "code": null, "e": 89752, "s": 89719, "text": "Tensorflow.js tf.time() Function" }, { "code": null, "e": 89790, "s": 89752, "text": "Tensorflow.js tf.nextFrame() Function" }, { "code": null, "e": 89826, "s": 89790, "text": "Tensorflow.js tf.profile() Function" }, { "code": null, "e": 89878, "s": 89826, "text": "TensorFlow.js Performance Memory Complete Reference" }, { "code": null, "e": 89923, "s": 89878, "text": "Tensorflow.js tf.disposeVariables() Function" }, { "code": null, "e": 89967, "s": 89923, "text": "Tensorflow.js tf.enableDebugMode() Function" }, { "code": null, "e": 90010, "s": 89967, "text": "Tensorflow.js tf.enableProdMode() Function" }, { "code": null, "e": 92558, "s": 90010, "text": "Tensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js IntroductionTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js IntroductionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js Metrics" }, { "code": null, "e": 92603, "s": 92558, "text": "TensorFlow.js Environment Complete Reference" }, { "code": null, "e": 92630, "s": 92603, "text": "Tensorflow.js Introduction" }, { "code": null, "e": 92681, "s": 92630, "text": "Tensorflow.js tf.metrics.binaryAccuracy() Function" }, { "code": null, "e": 92736, "s": 92681, "text": "Tensorflow.js tf.metrics.binaryCrossentropy() Function" }, { "code": null, "e": 92792, "s": 92736, "text": "Tensorflow.js tf.metrics.categoricalAccuracy() Function" }, { "code": null, "e": 92852, "s": 92792, "text": "Tensorflow.js tf.metrics.categoricalCrossentropy() Function" }, { "code": null, "e": 92904, "s": 92852, "text": "Tensorflow.js tf.metrics.cosineProximity() Function" }, { "code": null, "e": 92957, "s": 92904, "text": "Tensorflow.js tf.metrics.meanSquaredError() Function" }, { "code": null, "e": 93003, "s": 92957, "text": "Tensorflow.js tf.metrics.precision() Function" }, { "code": null, "e": 93046, "s": 93003, "text": "Tensorflow.js tf.metrics.recall() Function" }, { "code": null, "e": 93108, "s": 93046, "text": "Tensorflow.js tf.metrics.sparseCategoricalAccuracy() Function" }, { "code": null, "e": 93149, "s": 93108, "text": "TensorFlow.js Metrics Complete Reference" }, { "code": null, "e": 93176, "s": 93149, "text": "Tensorflow.js Introduction" }, { "code": null, "e": 93224, "s": 93176, "text": "Tensorflow.js tf.initializers.Initializer Class" }, { "code": null, "e": 93272, "s": 93224, "text": "Tensorflow.js tf.initializers.constant() Method" }, { "code": null, "e": 93326, "s": 93272, "text": "Tensorflow.js tf.initializers.glorotNormal() Function" }, { "code": null, "e": 93381, "s": 93326, "text": "Tensorflow.js tf.initializers.glorotUniform() Function" }, { "code": null, "e": 93431, "s": 93381, "text": "Tensorflow.js tf.initializers.heNormal() Function" }, { "code": null, "e": 93482, "s": 93431, "text": "Tensorflow.js tf.initializers.heUniform() Function" }, { "code": null, "e": 93528, "s": 93482, "text": "TensorFlow.js Initializers Complete Reference" }, { "code": null, "e": 93555, "s": 93528, "text": "Tensorflow.js Introduction" }, { "code": null, "e": 93599, "s": 93555, "text": "Tensorflow.js tf.regularizers.l1() Function" }, { "code": null, "e": 93645, "s": 93599, "text": "Tensorflow.js tf.regularizers.l1l2() Function" }, { "code": null, "e": 93689, "s": 93645, "text": "Tensorflow.js tf.regularizers.l2() Function" }, { "code": null, "e": 93716, "s": 93689, "text": "Tensorflow.js Introduction" }, { "code": null, "e": 93753, "s": 93716, "text": "Tensorflow.js tf.data.csv() Function" }, { "code": null, "e": 93796, "s": 93753, "text": "Tensorflow.js tf.data.generator() Function" }, { "code": null, "e": 95023, "s": 93796, "text": "Tensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js IntroductionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js IntroductionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js Metrics" }, { "code": null, "e": 95070, "s": 95023, "text": "TensorFlow.js Data Creation Complete Reference" }, { "code": null, "e": 95107, "s": 95070, "text": "Tensorflow.js tf.data.zip() Function" }, { "code": null, "e": 95159, "s": 95107, "text": "Tensorflow.js tf.data.Dataset class .batch() Method" }, { "code": null, "e": 95206, "s": 95159, "text": "TensorFlow.js Data Classes Complete References" }, { "code": null, "e": 95233, "s": 95206, "text": "Tensorflow.js Introduction" }, { "code": null, "e": 95273, "s": 95233, "text": "Tensorflow.js tf.util.assert() Function" }, { "code": null, "e": 95328, "s": 95273, "text": "Tensorflow.js tf.util.createShuffledIndices() Function" }, { "code": null, "e": 95369, "s": 95328, "text": "Tensorflow.js tf.decodeString() Function" }, { "code": null, "e": 95410, "s": 95369, "text": "Tensorflow.js tf.encodeString() Function" }, { "code": null, "e": 95444, "s": 95410, "text": "Tensorflow.js tf.fetch() Function" }, { "code": null, "e": 95485, "s": 95444, "text": "Tensorflow.js tf.util.flatten() Function" }, { "code": null, "e": 95522, "s": 95485, "text": "Tensorflow.js tf.util.now() Function" }, { "code": null, "e": 95563, "s": 95522, "text": "Tensorflow.js tf.util.shuffle() Function" }, { "code": null, "e": 95609, "s": 95563, "text": "Tensorflow.js tf.util.shuffleCombo() Function" }, { "code": null, "e": 95656, "s": 95609, "text": "Tensorflow.js tf.browser.fromPixels() Function" }, { "code": null, "e": 95708, "s": 95656, "text": "Tensorflow.js tf.browser.fromPixelsAsync() Function" }, { "code": null, "e": 95753, "s": 95708, "text": "Tensorflow.js tf.browser.toPixels() Function" }, { "code": null, "e": 95794, "s": 95753, "text": "TensorFlow.js Browser Complete Reference" }, { "code": null, "e": 95821, "s": 95794, "text": "Tensorflow.js Introduction" }, { "code": null, "e": 95857, "s": 95821, "text": "Tensorflow.js tf.backend() Function" }, { "code": null, "e": 95896, "s": 95857, "text": "Tensorflow.js tf.getBackend() Function" }, { "code": null, "e": 95930, "s": 95896, "text": "Tensorflow.js tf.ready() Function" }, { "code": null, "e": 95974, "s": 95930, "text": "Tensorflow.js tf.registerBackend() Function" }, { "code": null, "e": 96016, "s": 95974, "text": "Tensorflow.js tf.removeBackend() Function" }, { "code": null, "e": 96055, "s": 96016, "text": "Tensorflow.js tf.setBackend() Function" }, { "code": null, "e": 96107, "s": 96055, "text": "Tensorflow.js tf.callbacks.earlyStopping() Function" }, { "code": null, "e": 96135, "s": 96107, "text": "Last Updated :\n15 Aug, 2021" }, { "code": null, "e": 96438, "s": 96135, "text": "TensorFlow.js is a JavaScript library for training and deploying machine learning models on web applications and in Node.js. You can develop the machine learning models from scratch using tensorflow.js or can use the APIs provided to train your existing models in the browser or on your Node.js server." }, { "code": null, "e": 96573, "s": 96438, "text": "To learn more you can directly go to this link: https://www.tensorflow.org/resources/learn-ml/basics-of-tensorflow-for-js-development." }, { "code": null, "e": 96650, "s": 96573, "text": "Prerequisite: Before starting Tensorflow.js, you need to know the following:" }, { "code": null, "e": 96663, "s": 96650, "text": "For browser:" }, { "code": null, "e": 96706, "s": 96663, "text": "HTML: Basics knowledge of HTML is required" }, { "code": null, "e": 96751, "s": 96706, "text": "JavaScript: Good knowledge of JS is required" }, { "code": null, "e": 96770, "s": 96753, "text": "For server-side:" }, { "code": null, "e": 96901, "s": 96770, "text": "Node.js: Having a good command of Node.js. Also since Node.js is a JS runtime, so having command over JavaScript would help a lot." }, { "code": null, "e": 96921, "s": 96901, "text": "Other requirements:" }, { "code": null, "e": 96995, "s": 96921, "text": "NPM or Yarn: These are packages that need to be installed in your system." }, { "code": null, "e": 97021, "s": 96995, "text": "Setting Up Tensorflow.js:" }, { "code": null, "e": 97110, "s": 97021, "text": "Browser Setup There are two ways to add TensorFlow.js in your browser-based application:" }, { "code": null, "e": 97129, "s": 97110, "text": "Using script tags." }, { "code": null, "e": 97151, "s": 97129, "text": "Installation from NPM" }, { "code": null, "e": 97226, "s": 97151, "text": "1. Using Script tags: Add the following script tag to your main HTML file." }, { "code": null, "e": 97317, "s": 97226, "text": "<script src=”https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js”></script>" }, { "code": null, "e": 97326, "s": 97317, "text": "Example:" }, { "code": null, "e": 97331, "s": 97326, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <script src=\"https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js\"> </script></head> <body> <script> // Value of a scalar var value = \"Hello Geeks! Tensorflow here.\" // Creating the value of a scalar var tens = tf.scalar(value) document.write(tens) </script></body> </html>", "e": 97714, "s": 97331, "text": null }, { "code": null, "e": 97722, "s": 97714, "text": "Output:" }, { "code": null, "e": 97798, "s": 97722, "text": "2. Using NPM/ yarn: We can either use NPM or Yarn to install tensorflow.js." }, { "code": null, "e": 97824, "s": 97798, "text": "yarn add @tensorflow/tfjs" }, { "code": null, "e": 97827, "s": 97824, "text": "or" }, { "code": null, "e": 97856, "s": 97827, "text": "npm install @tensorflow/tfjs" }, { "code": null, "e": 97871, "s": 97856, "text": "Node.js Setup:" }, { "code": null, "e": 97929, "s": 97871, "text": "Option 1: Install TensorFlow.js with native C++ bindings." }, { "code": null, "e": 97960, "s": 97929, "text": "yarn add @tensorflow/tfjs-node" }, { "code": null, "e": 97963, "s": 97960, "text": "or" }, { "code": null, "e": 97997, "s": 97963, "text": "npm install @tensorflow/tfjs-node" }, { "code": null, "e": 98121, "s": 97997, "text": "Option 2: (Linux Only) If your system has a NVIDIA® GPU with CUDA support, use the GPU package even for higher performance." }, { "code": null, "e": 98156, "s": 98121, "text": "yarn add @tensorflow/tfjs-node-gpu" }, { "code": null, "e": 98159, "s": 98156, "text": "or" }, { "code": null, "e": 98197, "s": 98159, "text": "npm install @tensorflow/tfjs-node-gpu" }, { "code": null, "e": 98289, "s": 98197, "text": "Option 3: Install the pure JavaScript version. This is the slowest option performance-wise." }, { "code": null, "e": 98315, "s": 98289, "text": "yarn add @tensorflow/tfjs" }, { "code": null, "e": 98318, "s": 98315, "text": "or" }, { "code": null, "e": 98347, "s": 98318, "text": "npm install @tensorflow/tfjs" }, { "code": null, "e": 98361, "s": 98347, "text": "Tensorflow.js" }, { "code": null, "e": 98372, "s": 98361, "text": "JavaScript" }, { "code": null, "e": 98389, "s": 98372, "text": "Web Technologies" }, { "code": null, "e": 98487, "s": 98389, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 98527, "s": 98487, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 98572, "s": 98527, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 98633, "s": 98572, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 98705, "s": 98633, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 98774, "s": 98705, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 98814, "s": 98774, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 98847, "s": 98814, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 98892, "s": 98847, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 98935, "s": 98892, "text": "How to fetch data from an API in ReactJS ?" } ]
Python Regex to extract maximum numeric value from a string - GeeksforGeeks
29 Dec, 2020 Given an alphanumeric string, extract maximum numeric value from that string. Alphabets will only be in lower case. Examples: Input : 100klh564abc365bg Output : 564 Maximum numeric value among 100, 564 and 365 is 564. Input : abchsd0sdhs Output : 0 This problem has existing solution please refer Extract maximum numeric value from a given string | Set 1 (General approach) link. We will solve this problem quickly in python using Regex. Approach is very simple, Find list of all integer numbers in string separated by lower case characters using re.findall(expression,string) method.Convert each number in form of string into decimal number and then find max of it. Find list of all integer numbers in string separated by lower case characters using re.findall(expression,string) method. Convert each number in form of string into decimal number and then find max of it. # Function to extract maximum numeric value from # a given stringimport re def extractMax(input): # get a list of all numbers separated by # lower case characters # \d+ is a regular expression which means # one or more digit # output will be like ['100','564','365'] numbers = re.findall('\d+',input) # now we need to convert each number into integer # int(string) converts string into integer # we will map int() function onto all elements # of numbers list numbers = map(int,numbers) print max(numbers) # Driver programif __name__ == "__main__": input = '100klh564abc365bg' extractMax(input) Output: 564 Python Regex-programs python-regex python-string Python Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Longest Common Subsequence | DP-4
[ { "code": null, "e": 25561, "s": 25533, "text": "\n29 Dec, 2020" }, { "code": null, "e": 25677, "s": 25561, "text": "Given an alphanumeric string, extract maximum numeric value from that string. Alphabets will only be in lower case." }, { "code": null, "e": 25687, "s": 25677, "text": "Examples:" }, { "code": null, "e": 25813, "s": 25687, "text": "Input : 100klh564abc365bg\nOutput : 564\nMaximum numeric value among 100, 564 \nand 365 is 564.\n\nInput : abchsd0sdhs\nOutput : 0\n" }, { "code": null, "e": 26027, "s": 25813, "text": "This problem has existing solution please refer Extract maximum numeric value from a given string | Set 1 (General approach) link. We will solve this problem quickly in python using Regex. Approach is very simple," }, { "code": null, "e": 26231, "s": 26027, "text": "Find list of all integer numbers in string separated by lower case characters using re.findall(expression,string) method.Convert each number in form of string into decimal number and then find max of it." }, { "code": null, "e": 26353, "s": 26231, "text": "Find list of all integer numbers in string separated by lower case characters using re.findall(expression,string) method." }, { "code": null, "e": 26436, "s": 26353, "text": "Convert each number in form of string into decimal number and then find max of it." }, { "code": "# Function to extract maximum numeric value from # a given stringimport re def extractMax(input): # get a list of all numbers separated by # lower case characters # \\d+ is a regular expression which means # one or more digit # output will be like ['100','564','365'] numbers = re.findall('\\d+',input) # now we need to convert each number into integer # int(string) converts string into integer # we will map int() function onto all elements # of numbers list numbers = map(int,numbers) print max(numbers) # Driver programif __name__ == \"__main__\": input = '100klh564abc365bg' extractMax(input)", "e": 27095, "s": 26436, "text": null }, { "code": null, "e": 27103, "s": 27095, "text": "Output:" }, { "code": null, "e": 27108, "s": 27103, "text": "564\n" }, { "code": null, "e": 27130, "s": 27108, "text": "Python Regex-programs" }, { "code": null, "e": 27143, "s": 27130, "text": "python-regex" }, { "code": null, "e": 27157, "s": 27143, "text": "python-string" }, { "code": null, "e": 27164, "s": 27157, "text": "Python" }, { "code": null, "e": 27172, "s": 27164, "text": "Strings" }, { "code": null, "e": 27180, "s": 27172, "text": "Strings" }, { "code": null, "e": 27278, "s": 27180, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27310, "s": 27278, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27352, "s": 27310, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27394, "s": 27352, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27421, "s": 27394, "text": "Python Classes and Objects" }, { "code": null, "e": 27477, "s": 27421, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27523, "s": 27477, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 27548, "s": 27523, "text": "Reverse a string in Java" }, { "code": null, "e": 27608, "s": 27548, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 27623, "s": 27608, "text": "C++ Data Types" } ]
Grouping Rows in pandas - GeeksforGeeks
14 Jan, 2019 Pandas is the most popular Python library that is used for data analysis. It provides highly optimized performance with back-end source code is purely written in C or Python. Let’s see how to group rows in Pandas Dataframe with help of multiple examples. Example 1: For grouping rows in Pandas, we will start with creating a pandas dataframe first. # importing Pandasimport pandas as pd # example dataframeexample = {'Team':['Arsenal', 'Manchester United', 'Arsenal', 'Arsenal', 'Chelsea', 'Manchester United', 'Manchester United', 'Chelsea', 'Chelsea', 'Chelsea'], 'Player':['Ozil', 'Pogba', 'Lucas', 'Aubameyang', 'Hazard', 'Mata', 'Lukaku', 'Morata', 'Giroud', 'Kante'], 'Goals':[5, 3, 6, 4, 9, 2, 0, 5, 2, 3] } df = pd.DataFrame(example) print(df) Now, create a grouping object, means an object that represents that particular grouping. total_goals = df['Goals'].groupby(df['Team']) # printing the means valueprint(total_goals.mean()) Output: Example 2: import pandas as pd # example dataframeexample = {'Team':['Australia', 'England', 'South Africa', 'Australia', 'England', 'India', 'India', 'South Africa', 'England', 'India'], 'Player':['Ricky Ponting', 'Joe Root', 'Hashim Amla', 'David Warner', 'Jos Buttler', 'Virat Kohli', 'Rohit Sharma', 'David Miller', 'Eoin Morgan', 'Dinesh Karthik'], 'Runs':[345, 336, 689, 490, 989, 672, 560, 455, 342, 376], 'Salary':[34500, 33600, 68900, 49000, 98899, 67562, 56760, 45675, 34542, 31176] } df = pd.DataFrame(example) total_salary = df['Salary'].groupby(df['Team']) # printing the means valueprint(total_salary.mean()) Output: pandas-dataframe-program Picked Python pandas-dataFrame Python-pandas Technical Scripter 2018 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25562, "s": 25534, "text": "\n14 Jan, 2019" }, { "code": null, "e": 25737, "s": 25562, "text": "Pandas is the most popular Python library that is used for data analysis. It provides highly optimized performance with back-end source code is purely written in C or Python." }, { "code": null, "e": 25817, "s": 25737, "text": "Let’s see how to group rows in Pandas Dataframe with help of multiple examples." }, { "code": null, "e": 25828, "s": 25817, "text": "Example 1:" }, { "code": null, "e": 25911, "s": 25828, "text": "For grouping rows in Pandas, we will start with creating a pandas dataframe first." }, { "code": "# importing Pandasimport pandas as pd # example dataframeexample = {'Team':['Arsenal', 'Manchester United', 'Arsenal', 'Arsenal', 'Chelsea', 'Manchester United', 'Manchester United', 'Chelsea', 'Chelsea', 'Chelsea'], 'Player':['Ozil', 'Pogba', 'Lucas', 'Aubameyang', 'Hazard', 'Mata', 'Lukaku', 'Morata', 'Giroud', 'Kante'], 'Goals':[5, 3, 6, 4, 9, 2, 0, 5, 2, 3] } df = pd.DataFrame(example) print(df)", "e": 26500, "s": 25911, "text": null }, { "code": null, "e": 26589, "s": 26500, "text": "Now, create a grouping object, means an object that represents that particular grouping." }, { "code": "total_goals = df['Goals'].groupby(df['Team']) # printing the means valueprint(total_goals.mean()) ", "e": 26692, "s": 26589, "text": null }, { "code": null, "e": 26700, "s": 26692, "text": "Output:" }, { "code": null, "e": 26712, "s": 26700, "text": " Example 2:" }, { "code": "import pandas as pd # example dataframeexample = {'Team':['Australia', 'England', 'South Africa', 'Australia', 'England', 'India', 'India', 'South Africa', 'England', 'India'], 'Player':['Ricky Ponting', 'Joe Root', 'Hashim Amla', 'David Warner', 'Jos Buttler', 'Virat Kohli', 'Rohit Sharma', 'David Miller', 'Eoin Morgan', 'Dinesh Karthik'], 'Runs':[345, 336, 689, 490, 989, 672, 560, 455, 342, 376], 'Salary':[34500, 33600, 68900, 49000, 98899, 67562, 56760, 45675, 34542, 31176] } df = pd.DataFrame(example) total_salary = df['Salary'].groupby(df['Team']) # printing the means valueprint(total_salary.mean()) ", "e": 27598, "s": 26712, "text": null }, { "code": null, "e": 27606, "s": 27598, "text": "Output:" }, { "code": null, "e": 27631, "s": 27606, "text": "pandas-dataframe-program" }, { "code": null, "e": 27638, "s": 27631, "text": "Picked" }, { "code": null, "e": 27662, "s": 27638, "text": "Python pandas-dataFrame" }, { "code": null, "e": 27676, "s": 27662, "text": "Python-pandas" }, { "code": null, "e": 27700, "s": 27676, "text": "Technical Scripter 2018" }, { "code": null, "e": 27707, "s": 27700, "text": "Python" }, { "code": null, "e": 27726, "s": 27707, "text": "Technical Scripter" }, { "code": null, "e": 27824, "s": 27726, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27856, "s": 27824, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27898, "s": 27856, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27940, "s": 27898, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27996, "s": 27940, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28023, "s": 27996, "text": "Python Classes and Objects" }, { "code": null, "e": 28062, "s": 28023, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28093, "s": 28062, "text": "Python | os.path.join() method" }, { "code": null, "e": 28122, "s": 28093, "text": "Create a directory in Python" }, { "code": null, "e": 28144, "s": 28122, "text": "Defaultdict in Python" } ]
Program to build a DFA to accept strings that start and end with same character - GeeksforGeeks
21 May, 2021 Given a string consisting of characters a and b, check if the string starts and ends with the same character or not. If it does, print ‘Yes’ else print ‘No’.Examples: Input: str = “abbaaba” Output: Yes Explanation: The given input string starts and ends with same character ‘a’ So the states of the below DFA Machine will be q0->q1->q2->q2->q1->q1->q2->q1 and q1 is a final state, Hence the output will be Yes.Input: str = “ababab” Output: No Explanation: The given input string starts and ends with different character ‘a’ and ‘b’, So the states of the below DFA Machine will be q0->q1->q2->q1->q2->q1->q2 and q2 is not a final state, Hence the output will be No. Approach: DFA or Deterministic Finite Automata is a finite state machine which accepts a string(under some specific condition) if it reaches a final state, otherwise rejects it.In DFA, there is no concept of memory, therefore we have to check the string character by character, beginning with the 0th character. The input set of characters for the problem is {a, b}. For a DFA to be valid, there must a transition rule defined for each symbol of the input set at every state to a valid state.DFA Machine that accepts all strings that start and end with same character For the above problem statement, we must first build a DFA machine. DFA machine is similar to a flowchart with various states and transitions. DFA machine corresponding to the above problem is shown below, Q1 and Q3 are the final states: How does this DFA Machine works: The working of the machine depends on whether the first character is ‘a’ or ‘b’. Case 1: String starts with ‘a’ Suppose the first character in the input string is ‘a’, then on reading ‘a’, the control will shift to the upper branch of the machine.Now, it is defined at the string must end with an ‘a’ to be accepted.At state Q1, if again ‘a’ comes, it keeps circling at the same state because for the machine the last read character might be the last character of the string.If it gets a ‘b’, then it has to leave the final state since a string ending in ‘b’ is not acceptable. So it moves to state Q2.Here, if it gets an ‘a’, it again enters the final state Q1 else for consecutive ‘b’s, it keeps circling. Suppose the first character in the input string is ‘a’, then on reading ‘a’, the control will shift to the upper branch of the machine.Now, it is defined at the string must end with an ‘a’ to be accepted.At state Q1, if again ‘a’ comes, it keeps circling at the same state because for the machine the last read character might be the last character of the string.If it gets a ‘b’, then it has to leave the final state since a string ending in ‘b’ is not acceptable. So it moves to state Q2.Here, if it gets an ‘a’, it again enters the final state Q1 else for consecutive ‘b’s, it keeps circling. Suppose the first character in the input string is ‘a’, then on reading ‘a’, the control will shift to the upper branch of the machine. Now, it is defined at the string must end with an ‘a’ to be accepted. At state Q1, if again ‘a’ comes, it keeps circling at the same state because for the machine the last read character might be the last character of the string. If it gets a ‘b’, then it has to leave the final state since a string ending in ‘b’ is not acceptable. So it moves to state Q2. Here, if it gets an ‘a’, it again enters the final state Q1 else for consecutive ‘b’s, it keeps circling. Case 2: String starts with ‘b’ Suppose the first character in the input string is ‘b’, then on reading ‘b’, the control will shift to the upper branch of the machine.Now, it is defined at the string must end with an ‘b’ to be accepted.At state Q3, if again ‘b’ comes, it keeps circling at the same state because for the machine the last read character might be the last character of the string.If it gets a ‘a’, then it has to leave the final state since a string ending in ‘a’ is not acceptable. So it moves to state Q4.Here, if it gets an ‘b’, it again enters the final state Q3 else for consecutive ‘a’s, it keeps circling. Suppose the first character in the input string is ‘b’, then on reading ‘b’, the control will shift to the upper branch of the machine.Now, it is defined at the string must end with an ‘b’ to be accepted.At state Q3, if again ‘b’ comes, it keeps circling at the same state because for the machine the last read character might be the last character of the string.If it gets a ‘a’, then it has to leave the final state since a string ending in ‘a’ is not acceptable. So it moves to state Q4.Here, if it gets an ‘b’, it again enters the final state Q3 else for consecutive ‘a’s, it keeps circling. Suppose the first character in the input string is ‘b’, then on reading ‘b’, the control will shift to the upper branch of the machine. Now, it is defined at the string must end with an ‘b’ to be accepted. At state Q3, if again ‘b’ comes, it keeps circling at the same state because for the machine the last read character might be the last character of the string. If it gets a ‘a’, then it has to leave the final state since a string ending in ‘a’ is not acceptable. So it moves to state Q4. Here, if it gets an ‘b’, it again enters the final state Q3 else for consecutive ‘a’s, it keeps circling. Approach for designing the DFA machine: Define the minimum number of states required to make the state diagram. Here Q0, Q1, Q2, Q3, Q4 are the defined states. Use functions for various states.List all the valid transitions. Here ‘a’ and ‘b’ are valid symbols. Each state must have a transition for every valid symbol.Define the final states by applying the base condition. Q1 and Q3 are defined as the final state. If the string input ends at any of these states, it is accepted else rejected.Define all the state transitions using state function calls.Define a returning condition for the end of the string. If by following the process, the program reaches the end of the string, the output is made according to the state the program is at. Define the minimum number of states required to make the state diagram. Here Q0, Q1, Q2, Q3, Q4 are the defined states. Use functions for various states. List all the valid transitions. Here ‘a’ and ‘b’ are valid symbols. Each state must have a transition for every valid symbol. Define the final states by applying the base condition. Q1 and Q3 are defined as the final state. If the string input ends at any of these states, it is accepted else rejected. Define all the state transitions using state function calls. Define a returning condition for the end of the string. If by following the process, the program reaches the end of the string, the output is made according to the state the program is at. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ Program for DFA that accepts string// if it starts and ends with same character #include <bits/stdc++.h>using namespace std; // States of DFAvoid q1(string, int);void q2(string, int);void q3(string, int);void q4(string, int); // Function for the state Q1void q1(string s, int i){ // Condition to check end of string if (i == s.length()) { cout << "Yes \n"; return; } // State transitions // 'a' takes to q1, and // 'b' takes to q2 if (s[i] == 'a') q1(s, i + 1); else q2(s, i + 1);} // Function for the state Q2void q2(string s, int i){ // Condition to check end of string if (i == s.length()) { cout << "No \n"; return; } // State transitions // 'a' takes to q1, and // 'b' takes to q2 if (s[i] == 'a') q1(s, i + 1); else q2(s, i + 1);} // Function for the state Q3void q3(string s, int i){ // Condition to check end of string if (i == s.length()) { cout << "Yes \n"; return; } // State transitions // 'a' takes to q4, and // 'b' takes to q3 if (s[i] == 'a') q4(s, i + 1); else q3(s, i + 1);} // Function for the state Q4void q4(string s, int i){ // Condition to check end of string if (i == s.length()) { cout << "No \n"; return; } // State transitions // 'a' takes to q4, and // 'b' takes to q3 if (s[i] == 'a') q4(s, i + 1); else q3(s, i + 1);} // Function for the state Q0void q0(string s, int i){ // Condition to check end of string if (i == s.length()) { cout << "No \n"; return; } // State transitions // 'a' takes to q1, and // 'b' takes to q3 if (s[i] == 'a') q1(s, i + 1); else q3(s, i + 1);} // Driver Codeint main(){ string s = "abbaabb"; // Since q0 is the starting state // Send the string to q0 q0(s, 0);} // Java Program for DFA that accepts string// if it starts and ends with same characterclass GFG{ // Function for the state Q1 static void q1(String s, int i) { // Condition to check end of string if (i == s.length()) { System.out.println("Yes"); return; } // State transitions // 'a' takes to q1, and // 'b' takes to q2 if (s.charAt(i) == 'a') q1(s, i + 1); else q2(s, i + 1); } // Function for the state Q2 static void q2(String s, int i) { // Condition to check end of string if (i == s.length()) { System.out.println("No"); return; } // State transitions // 'a' takes to q1, and // 'b' takes to q2 if (s.charAt(i) == 'a') q1(s, i + 1); else q2(s, i + 1); } // Function for the state Q3 static void q3(String s, int i) { // Condition to check end of string if (i == s.length()) { System.out.println("Yes"); return; } // State transitions // 'a' takes to q4, and // 'b' takes to q3 if (s.charAt(i) == 'a') q4(s, i + 1); else q3(s, i + 1); } // Function for the state Q4 static void q4(String s, int i) { // Condition to check end of string if (i == s.length()) { System.out.println("No"); return; } // State transitions // 'a' takes to q4, and // 'b' takes to q3 if (s.charAt(i) == 'a') q4(s, i + 1); else q3(s, i + 1); } // Function for the state Q0 static void q0(String s, int i) { // Condition to check end of string if (i == s.length()) { System.out.println("No"); return; } // State transitions // 'a' takes to q1, and // 'b' takes to q3 if (s.charAt(i) == 'a') q1(s, i + 1); else q3(s, i + 1); } // Driver Code public static void main (String[] args) { String s = "abbaabb"; // Since q0 is the starting state // Send the string to q0 q0(s, 0); }} // This code is contributed by AnkitRai01 # Python3 Program for DFA that accepts string# if it starts and ends with same character # Function for the state Q1def q1(s, i): # Condition to check end of string if (i == len(s)): print("Yes"); return; # State transitions # 'a' takes to q1, and # 'b' takes to q2 if (s[i] == 'a'): q1(s, i + 1); else: q2(s, i + 1); # Function for the state Q2def q2(s, i): # Condition to check end of string if (i == len(s)): print("No"); return; # State transitions # 'a' takes to q1, and # 'b' takes to q2 if (s[i] == 'a'): q1(s, i + 1); else: q2(s, i + 1); # Function for the state Q3def q3(s, i): # Condition to check end of string if (i == len(s)): print("Yes"); return; # State transitions # 'a' takes to q4, and # 'b' takes to q3 if (s[i] == 'a'): q4(s, i + 1); else: q3(s, i + 1); # Function for the state Q4def q4(s, i): # Condition to check end of string if (i == s.length()): print("No"); return; # State transitions # 'a' takes to q4, and # 'b' takes to q3 if (s[i] == 'a'): q4(s, i + 1); else: q3(s, i + 1); # Function for the state Q0def q0(s, i): # Condition to check end of string if (i == len(s)): print("No"); return; # State transitions # 'a' takes to q1, and # 'b' takes to q3 if (s[i] == 'a'): q1(s, i + 1); else: q3(s, i + 1); # Driver Codeif __name__ == '__main__': s = "abbaabb"; # Since q0 is the starting state # Send the string to q0 q0(s, 0); # This code is contributed by Rajput-Ji // C# Program for DFA that accepts string// if it starts and ends with same characterusing System; class GFG{ // Function for the state Q1 static void q1(string s, int i) { // Condition to check end of string if (i == s.Length) { Console.WriteLine("Yes"); return; } // State transitions // 'a' takes to q1, and // 'b' takes to q2 if (s[i] == 'a') q1(s, i + 1); else q2(s, i + 1); } // Function for the state Q2 static void q2(string s, int i) { // Condition to check end of string if (i == s.Length) { Console.WriteLine("No"); return; } // State transitions // 'a' takes to q1, and // 'b' takes to q2 if (s[i] == 'a') q1(s, i + 1); else q2(s, i + 1); } // Function for the state Q3 static void q3(string s, int i) { // Condition to check end of string if (i == s.Length) { Console.WriteLine("Yes"); return; } // State transitions // 'a' takes to q4, and // 'b' takes to q3 if (s[i] == 'a') q4(s, i + 1); else q3(s, i + 1); } // Function for the state Q4 static void q4(string s, int i) { // Condition to check end of string if (i == s.Length) { Console.WriteLine("No"); return; } // State transitions // 'a' takes to q4, and // 'b' takes to q3 if (s[i] == 'a') q4(s, i + 1); else q3(s, i + 1); } // Function for the state Q0 static void q0(string s, int i) { // Condition to check end of string if (i == s.Length) { Console.WriteLine("No"); return; } // State transitions // 'a' takes to q1, and // 'b' takes to q3 if (s[i] == 'a') q1(s, i + 1); else q3(s, i + 1); } // Driver Code public static void Main () { string s = "abbaabb"; // Since q0 is the starting state // Send the string to q0 q0(s, 0); }} // This code is contributed by AnkitRai01 <script> // Javascript Program for DFA that accepts string// if it starts and ends with same character // Function for the state Q1function q1( s, i){ // Condition to check end of string if (i == s.length) { document.write( "Yes<br>"); return; } // State transitions // 'a' takes to q1, and // 'b' takes to q2 if (s[i] == 'a') q1(s, i + 1); else q2(s, i + 1);} // Function for the state Q2function q2( s, i){ // Condition to check end of string if (i == s.length) { document.write( "No"); return; } // State transitions // 'a' takes to q1, and // 'b' takes to q2 if (s[i] == 'a') q1(s, i + 1); else q2(s, i + 1);} // Function for the state Q3function q3( s, i){ // Condition to check end of string if (i == s.length) { document.write( "Yes"); return; } // State transitions // 'a' takes to q4, and // 'b' takes to q3 if (s[i] == 'a') q4(s, i + 1); else q3(s, i + 1);} // Function for the state Q4function q4( s, i){ // Condition to check end of string if (i == s.length) { document.write( "No"); return; } // State transitions // 'a' takes to q4, and // 'b' takes to q3 if (s[i] == 'a') q4(s, i + 1); else q3(s, i + 1);} // Function for the state Q0function q0( s, i){ // Condition to check end of string if (i == s.length) { document.write( "No"); return; } // State transitions // 'a' takes to q1, and // 'b' takes to q3 if (s[i] == 'a') q1(s, i + 1); else q3(s, i + 1);} // Driver Codevar s = "abbaabb"; // Since q0 is the starting state// Send the string to q0q0(s, 0); // This code is contributed by importantly. </script> No Time Complexity: O(N) ankthon Rajput-Ji importantly DFA Pattern Searching Strings Theory of Computation & Automata Strings Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check if an URL is valid or not using Regular Expression Search a Word in a 2D Grid of characters Wildcard Pattern Matching How to check if string contains only digits in Java Check if a string contains uppercase, lowercase, special characters and numeric values Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Longest Common Subsequence | DP-4
[ { "code": null, "e": 26313, "s": 26285, "text": "\n21 May, 2021" }, { "code": null, "e": 26482, "s": 26313, "text": "Given a string consisting of characters a and b, check if the string starts and ends with the same character or not. If it does, print ‘Yes’ else print ‘No’.Examples: " }, { "code": null, "e": 26982, "s": 26482, "text": "Input: str = “abbaaba” Output: Yes Explanation: The given input string starts and ends with same character ‘a’ So the states of the below DFA Machine will be q0->q1->q2->q2->q1->q1->q2->q1 and q1 is a final state, Hence the output will be Yes.Input: str = “ababab” Output: No Explanation: The given input string starts and ends with different character ‘a’ and ‘b’, So the states of the below DFA Machine will be q0->q1->q2->q1->q2->q1->q2 and q2 is not a final state, Hence the output will be No. " }, { "code": null, "e": 27791, "s": 26984, "text": "Approach: DFA or Deterministic Finite Automata is a finite state machine which accepts a string(under some specific condition) if it reaches a final state, otherwise rejects it.In DFA, there is no concept of memory, therefore we have to check the string character by character, beginning with the 0th character. The input set of characters for the problem is {a, b}. For a DFA to be valid, there must a transition rule defined for each symbol of the input set at every state to a valid state.DFA Machine that accepts all strings that start and end with same character For the above problem statement, we must first build a DFA machine. DFA machine is similar to a flowchart with various states and transitions. DFA machine corresponding to the above problem is shown below, Q1 and Q3 are the final states: " }, { "code": null, "e": 27907, "s": 27791, "text": "How does this DFA Machine works: The working of the machine depends on whether the first character is ‘a’ or ‘b’. " }, { "code": null, "e": 28534, "s": 27907, "text": "Case 1: String starts with ‘a’ Suppose the first character in the input string is ‘a’, then on reading ‘a’, the control will shift to the upper branch of the machine.Now, it is defined at the string must end with an ‘a’ to be accepted.At state Q1, if again ‘a’ comes, it keeps circling at the same state because for the machine the last read character might be the last character of the string.If it gets a ‘b’, then it has to leave the final state since a string ending in ‘b’ is not acceptable. So it moves to state Q2.Here, if it gets an ‘a’, it again enters the final state Q1 else for consecutive ‘b’s, it keeps circling." }, { "code": null, "e": 29130, "s": 28534, "text": "Suppose the first character in the input string is ‘a’, then on reading ‘a’, the control will shift to the upper branch of the machine.Now, it is defined at the string must end with an ‘a’ to be accepted.At state Q1, if again ‘a’ comes, it keeps circling at the same state because for the machine the last read character might be the last character of the string.If it gets a ‘b’, then it has to leave the final state since a string ending in ‘b’ is not acceptable. So it moves to state Q2.Here, if it gets an ‘a’, it again enters the final state Q1 else for consecutive ‘b’s, it keeps circling." }, { "code": null, "e": 29266, "s": 29130, "text": "Suppose the first character in the input string is ‘a’, then on reading ‘a’, the control will shift to the upper branch of the machine." }, { "code": null, "e": 29336, "s": 29266, "text": "Now, it is defined at the string must end with an ‘a’ to be accepted." }, { "code": null, "e": 29496, "s": 29336, "text": "At state Q1, if again ‘a’ comes, it keeps circling at the same state because for the machine the last read character might be the last character of the string." }, { "code": null, "e": 29624, "s": 29496, "text": "If it gets a ‘b’, then it has to leave the final state since a string ending in ‘b’ is not acceptable. So it moves to state Q2." }, { "code": null, "e": 29730, "s": 29624, "text": "Here, if it gets an ‘a’, it again enters the final state Q1 else for consecutive ‘b’s, it keeps circling." }, { "code": null, "e": 30357, "s": 29730, "text": "Case 2: String starts with ‘b’ Suppose the first character in the input string is ‘b’, then on reading ‘b’, the control will shift to the upper branch of the machine.Now, it is defined at the string must end with an ‘b’ to be accepted.At state Q3, if again ‘b’ comes, it keeps circling at the same state because for the machine the last read character might be the last character of the string.If it gets a ‘a’, then it has to leave the final state since a string ending in ‘a’ is not acceptable. So it moves to state Q4.Here, if it gets an ‘b’, it again enters the final state Q3 else for consecutive ‘a’s, it keeps circling." }, { "code": null, "e": 30953, "s": 30357, "text": "Suppose the first character in the input string is ‘b’, then on reading ‘b’, the control will shift to the upper branch of the machine.Now, it is defined at the string must end with an ‘b’ to be accepted.At state Q3, if again ‘b’ comes, it keeps circling at the same state because for the machine the last read character might be the last character of the string.If it gets a ‘a’, then it has to leave the final state since a string ending in ‘a’ is not acceptable. So it moves to state Q4.Here, if it gets an ‘b’, it again enters the final state Q3 else for consecutive ‘a’s, it keeps circling." }, { "code": null, "e": 31089, "s": 30953, "text": "Suppose the first character in the input string is ‘b’, then on reading ‘b’, the control will shift to the upper branch of the machine." }, { "code": null, "e": 31159, "s": 31089, "text": "Now, it is defined at the string must end with an ‘b’ to be accepted." }, { "code": null, "e": 31319, "s": 31159, "text": "At state Q3, if again ‘b’ comes, it keeps circling at the same state because for the machine the last read character might be the last character of the string." }, { "code": null, "e": 31447, "s": 31319, "text": "If it gets a ‘a’, then it has to leave the final state since a string ending in ‘a’ is not acceptable. So it moves to state Q4." }, { "code": null, "e": 31553, "s": 31447, "text": "Here, if it gets an ‘b’, it again enters the final state Q3 else for consecutive ‘a’s, it keeps circling." }, { "code": null, "e": 31595, "s": 31553, "text": "Approach for designing the DFA machine: " }, { "code": null, "e": 32298, "s": 31595, "text": "Define the minimum number of states required to make the state diagram. Here Q0, Q1, Q2, Q3, Q4 are the defined states. Use functions for various states.List all the valid transitions. Here ‘a’ and ‘b’ are valid symbols. Each state must have a transition for every valid symbol.Define the final states by applying the base condition. Q1 and Q3 are defined as the final state. If the string input ends at any of these states, it is accepted else rejected.Define all the state transitions using state function calls.Define a returning condition for the end of the string. If by following the process, the program reaches the end of the string, the output is made according to the state the program is at." }, { "code": null, "e": 32452, "s": 32298, "text": "Define the minimum number of states required to make the state diagram. Here Q0, Q1, Q2, Q3, Q4 are the defined states. Use functions for various states." }, { "code": null, "e": 32578, "s": 32452, "text": "List all the valid transitions. Here ‘a’ and ‘b’ are valid symbols. Each state must have a transition for every valid symbol." }, { "code": null, "e": 32755, "s": 32578, "text": "Define the final states by applying the base condition. Q1 and Q3 are defined as the final state. If the string input ends at any of these states, it is accepted else rejected." }, { "code": null, "e": 32816, "s": 32755, "text": "Define all the state transitions using state function calls." }, { "code": null, "e": 33005, "s": 32816, "text": "Define a returning condition for the end of the string. If by following the process, the program reaches the end of the string, the output is made according to the state the program is at." }, { "code": null, "e": 33057, "s": 33005, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 33061, "s": 33057, "text": "C++" }, { "code": null, "e": 33066, "s": 33061, "text": "Java" }, { "code": null, "e": 33074, "s": 33066, "text": "Python3" }, { "code": null, "e": 33077, "s": 33074, "text": "C#" }, { "code": null, "e": 33088, "s": 33077, "text": "Javascript" }, { "code": "// C++ Program for DFA that accepts string// if it starts and ends with same character #include <bits/stdc++.h>using namespace std; // States of DFAvoid q1(string, int);void q2(string, int);void q3(string, int);void q4(string, int); // Function for the state Q1void q1(string s, int i){ // Condition to check end of string if (i == s.length()) { cout << \"Yes \\n\"; return; } // State transitions // 'a' takes to q1, and // 'b' takes to q2 if (s[i] == 'a') q1(s, i + 1); else q2(s, i + 1);} // Function for the state Q2void q2(string s, int i){ // Condition to check end of string if (i == s.length()) { cout << \"No \\n\"; return; } // State transitions // 'a' takes to q1, and // 'b' takes to q2 if (s[i] == 'a') q1(s, i + 1); else q2(s, i + 1);} // Function for the state Q3void q3(string s, int i){ // Condition to check end of string if (i == s.length()) { cout << \"Yes \\n\"; return; } // State transitions // 'a' takes to q4, and // 'b' takes to q3 if (s[i] == 'a') q4(s, i + 1); else q3(s, i + 1);} // Function for the state Q4void q4(string s, int i){ // Condition to check end of string if (i == s.length()) { cout << \"No \\n\"; return; } // State transitions // 'a' takes to q4, and // 'b' takes to q3 if (s[i] == 'a') q4(s, i + 1); else q3(s, i + 1);} // Function for the state Q0void q0(string s, int i){ // Condition to check end of string if (i == s.length()) { cout << \"No \\n\"; return; } // State transitions // 'a' takes to q1, and // 'b' takes to q3 if (s[i] == 'a') q1(s, i + 1); else q3(s, i + 1);} // Driver Codeint main(){ string s = \"abbaabb\"; // Since q0 is the starting state // Send the string to q0 q0(s, 0);}", "e": 34996, "s": 33088, "text": null }, { "code": "// Java Program for DFA that accepts string// if it starts and ends with same characterclass GFG{ // Function for the state Q1 static void q1(String s, int i) { // Condition to check end of string if (i == s.length()) { System.out.println(\"Yes\"); return; } // State transitions // 'a' takes to q1, and // 'b' takes to q2 if (s.charAt(i) == 'a') q1(s, i + 1); else q2(s, i + 1); } // Function for the state Q2 static void q2(String s, int i) { // Condition to check end of string if (i == s.length()) { System.out.println(\"No\"); return; } // State transitions // 'a' takes to q1, and // 'b' takes to q2 if (s.charAt(i) == 'a') q1(s, i + 1); else q2(s, i + 1); } // Function for the state Q3 static void q3(String s, int i) { // Condition to check end of string if (i == s.length()) { System.out.println(\"Yes\"); return; } // State transitions // 'a' takes to q4, and // 'b' takes to q3 if (s.charAt(i) == 'a') q4(s, i + 1); else q3(s, i + 1); } // Function for the state Q4 static void q4(String s, int i) { // Condition to check end of string if (i == s.length()) { System.out.println(\"No\"); return; } // State transitions // 'a' takes to q4, and // 'b' takes to q3 if (s.charAt(i) == 'a') q4(s, i + 1); else q3(s, i + 1); } // Function for the state Q0 static void q0(String s, int i) { // Condition to check end of string if (i == s.length()) { System.out.println(\"No\"); return; } // State transitions // 'a' takes to q1, and // 'b' takes to q3 if (s.charAt(i) == 'a') q1(s, i + 1); else q3(s, i + 1); } // Driver Code public static void main (String[] args) { String s = \"abbaabb\"; // Since q0 is the starting state // Send the string to q0 q0(s, 0); }} // This code is contributed by AnkitRai01", "e": 37399, "s": 34996, "text": null }, { "code": "# Python3 Program for DFA that accepts string# if it starts and ends with same character # Function for the state Q1def q1(s, i): # Condition to check end of string if (i == len(s)): print(\"Yes\"); return; # State transitions # 'a' takes to q1, and # 'b' takes to q2 if (s[i] == 'a'): q1(s, i + 1); else: q2(s, i + 1); # Function for the state Q2def q2(s, i): # Condition to check end of string if (i == len(s)): print(\"No\"); return; # State transitions # 'a' takes to q1, and # 'b' takes to q2 if (s[i] == 'a'): q1(s, i + 1); else: q2(s, i + 1); # Function for the state Q3def q3(s, i): # Condition to check end of string if (i == len(s)): print(\"Yes\"); return; # State transitions # 'a' takes to q4, and # 'b' takes to q3 if (s[i] == 'a'): q4(s, i + 1); else: q3(s, i + 1); # Function for the state Q4def q4(s, i): # Condition to check end of string if (i == s.length()): print(\"No\"); return; # State transitions # 'a' takes to q4, and # 'b' takes to q3 if (s[i] == 'a'): q4(s, i + 1); else: q3(s, i + 1); # Function for the state Q0def q0(s, i): # Condition to check end of string if (i == len(s)): print(\"No\"); return; # State transitions # 'a' takes to q1, and # 'b' takes to q3 if (s[i] == 'a'): q1(s, i + 1); else: q3(s, i + 1); # Driver Codeif __name__ == '__main__': s = \"abbaabb\"; # Since q0 is the starting state # Send the string to q0 q0(s, 0); # This code is contributed by Rajput-Ji", "e": 39100, "s": 37399, "text": null }, { "code": "// C# Program for DFA that accepts string// if it starts and ends with same characterusing System; class GFG{ // Function for the state Q1 static void q1(string s, int i) { // Condition to check end of string if (i == s.Length) { Console.WriteLine(\"Yes\"); return; } // State transitions // 'a' takes to q1, and // 'b' takes to q2 if (s[i] == 'a') q1(s, i + 1); else q2(s, i + 1); } // Function for the state Q2 static void q2(string s, int i) { // Condition to check end of string if (i == s.Length) { Console.WriteLine(\"No\"); return; } // State transitions // 'a' takes to q1, and // 'b' takes to q2 if (s[i] == 'a') q1(s, i + 1); else q2(s, i + 1); } // Function for the state Q3 static void q3(string s, int i) { // Condition to check end of string if (i == s.Length) { Console.WriteLine(\"Yes\"); return; } // State transitions // 'a' takes to q4, and // 'b' takes to q3 if (s[i] == 'a') q4(s, i + 1); else q3(s, i + 1); } // Function for the state Q4 static void q4(string s, int i) { // Condition to check end of string if (i == s.Length) { Console.WriteLine(\"No\"); return; } // State transitions // 'a' takes to q4, and // 'b' takes to q3 if (s[i] == 'a') q4(s, i + 1); else q3(s, i + 1); } // Function for the state Q0 static void q0(string s, int i) { // Condition to check end of string if (i == s.Length) { Console.WriteLine(\"No\"); return; } // State transitions // 'a' takes to q1, and // 'b' takes to q3 if (s[i] == 'a') q1(s, i + 1); else q3(s, i + 1); } // Driver Code public static void Main () { string s = \"abbaabb\"; // Since q0 is the starting state // Send the string to q0 q0(s, 0); }} // This code is contributed by AnkitRai01", "e": 41452, "s": 39100, "text": null }, { "code": "<script> // Javascript Program for DFA that accepts string// if it starts and ends with same character // Function for the state Q1function q1( s, i){ // Condition to check end of string if (i == s.length) { document.write( \"Yes<br>\"); return; } // State transitions // 'a' takes to q1, and // 'b' takes to q2 if (s[i] == 'a') q1(s, i + 1); else q2(s, i + 1);} // Function for the state Q2function q2( s, i){ // Condition to check end of string if (i == s.length) { document.write( \"No\"); return; } // State transitions // 'a' takes to q1, and // 'b' takes to q2 if (s[i] == 'a') q1(s, i + 1); else q2(s, i + 1);} // Function for the state Q3function q3( s, i){ // Condition to check end of string if (i == s.length) { document.write( \"Yes\"); return; } // State transitions // 'a' takes to q4, and // 'b' takes to q3 if (s[i] == 'a') q4(s, i + 1); else q3(s, i + 1);} // Function for the state Q4function q4( s, i){ // Condition to check end of string if (i == s.length) { document.write( \"No\"); return; } // State transitions // 'a' takes to q4, and // 'b' takes to q3 if (s[i] == 'a') q4(s, i + 1); else q3(s, i + 1);} // Function for the state Q0function q0( s, i){ // Condition to check end of string if (i == s.length) { document.write( \"No\"); return; } // State transitions // 'a' takes to q1, and // 'b' takes to q3 if (s[i] == 'a') q1(s, i + 1); else q3(s, i + 1);} // Driver Codevar s = \"abbaabb\"; // Since q0 is the starting state// Send the string to q0q0(s, 0); // This code is contributed by importantly. </script>", "e": 43252, "s": 41452, "text": null }, { "code": null, "e": 43255, "s": 43252, "text": "No" }, { "code": null, "e": 43280, "s": 43257, "text": "Time Complexity: O(N) " }, { "code": null, "e": 43288, "s": 43280, "text": "ankthon" }, { "code": null, "e": 43298, "s": 43288, "text": "Rajput-Ji" }, { "code": null, "e": 43310, "s": 43298, "text": "importantly" }, { "code": null, "e": 43314, "s": 43310, "text": "DFA" }, { "code": null, "e": 43332, "s": 43314, "text": "Pattern Searching" }, { "code": null, "e": 43340, "s": 43332, "text": "Strings" }, { "code": null, "e": 43373, "s": 43340, "text": "Theory of Computation & Automata" }, { "code": null, "e": 43381, "s": 43373, "text": "Strings" }, { "code": null, "e": 43399, "s": 43381, "text": "Pattern Searching" }, { "code": null, "e": 43497, "s": 43399, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 43554, "s": 43497, "text": "Check if an URL is valid or not using Regular Expression" }, { "code": null, "e": 43595, "s": 43554, "text": "Search a Word in a 2D Grid of characters" }, { "code": null, "e": 43621, "s": 43595, "text": "Wildcard Pattern Matching" }, { "code": null, "e": 43673, "s": 43621, "text": "How to check if string contains only digits in Java" }, { "code": null, "e": 43760, "s": 43673, "text": "Check if a string contains uppercase, lowercase, special characters and numeric values" }, { "code": null, "e": 43806, "s": 43760, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 43831, "s": 43806, "text": "Reverse a string in Java" }, { "code": null, "e": 43891, "s": 43831, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 43906, "s": 43891, "text": "C++ Data Types" } ]
Python | Sort a Dictionary - GeeksforGeeks
29 Aug, 2020 Python, Given a dictionary, perform sort, basis on keys or values. [ applicable Python >=3.6v ]. Input : test_dict = {“Gfg” : 5, “is” : 7, “Best” : 2}Output : {‘Best’: 2, ‘Gfg’: 5, ‘is’: 7}, {‘is’: 7, ‘Gfg’: 5, ‘Best’: 2}Explanation : Sorted by keys, in ascending and reverse order. Input : test_dict = {“Best” : 2, “for” : 9, “geeks” : 8}Output : {‘Best’: 2, ‘Gfg’: 5, ‘for’: 9}, {‘for’: 9, ‘geeks’: 8, ‘Best’: 2}Explanation : Sorted by values, in ascending and reverse order. Case 1 : Sort by Keys This task is performed using sorted(), in this, we extract the keys using 1st index of items of dictionary extracted by items(), and pass it in key as custom lambda function to get sorted by keys. The “reverse=True” is added to perform reverse sort. Python3 # Python3 code to demonstrate working of # Sort a Dictionary# Sort by Keys # initializing dictionarytest_dict = {"Gfg" : 5, "is" : 7, "Best" : 2, "for" : 9, "geeks" : 8} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # using items() to get all items # lambda function is passed in key to perform sort by key res = {key: val for key, val in sorted(test_dict.items(), key = lambda ele: ele[0])} # printing result print("Result dictionary sorted by keys : " + str(res)) # using items() to get all items # lambda function is passed in key to perform sort by key # adding "reversed = True" for reversed orderres = {key: val for key, val in sorted(test_dict.items(), key = lambda ele: ele[0], reverse = True)} # printing result print("Result dictionary sorted by keys ( in reversed order ) : " + str(res)) The original dictionary is : {'Gfg': 5, 'is': 7, 'Best': 2, 'for': 9, 'geeks': 8} Result dictionary sorted by keys : {'Best': 2, 'Gfg': 5, 'for': 9, 'geeks': 8, 'is': 7} Result dictionary sorted by keys ( in reversed order ) : {'is': 7, 'geeks': 8, 'for': 9, 'Gfg': 5, 'Best': 2} Case 2 : Sort by Values This task can be performed in similar way as above, the only difference being for extracting values, 2nd element of items() is passed as comparator. Python3 # Python3 code to demonstrate working of # Sort a Dictionary# Sort by Values # initializing dictionarytest_dict = {"Gfg" : 5, "is" : 7, "Best" : 2, "for" : 9, "geeks" : 8} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # using items() to get all items # lambda function is passed in key to perform sort by key # passing 2nd element of items()res = {key: val for key, val in sorted(test_dict.items(), key = lambda ele: ele[1])} # printing result print("Result dictionary sorted by values : " + str(res)) # using items() to get all items # lambda function is passed in key to perform sort by key # passing 2nd element of items()# adding "reversed = True" for reversed orderres = {key: val for key, val in sorted(test_dict.items(), key = lambda ele: ele[1], reverse = True)} # printing result print("Result dictionary sorted by values ( in reversed order ) : " + str(res)) The original dictionary is : {'Gfg': 5, 'is': 7, 'Best': 2, 'for': 9, 'geeks': 8} Result dictionary sorted by values : {'Best': 2, 'Gfg': 5, 'is': 7, 'geeks': 8, 'for': 9} Result dictionary sorted by values ( in reversed order ) : {'for': 9, 'geeks': 8, 'is': 7, 'Gfg': 5, 'Best': 2} Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 26143, "s": 26115, "text": "\n29 Aug, 2020" }, { "code": null, "e": 26240, "s": 26143, "text": "Python, Given a dictionary, perform sort, basis on keys or values. [ applicable Python >=3.6v ]." }, { "code": null, "e": 26426, "s": 26240, "text": "Input : test_dict = {“Gfg” : 5, “is” : 7, “Best” : 2}Output : {‘Best’: 2, ‘Gfg’: 5, ‘is’: 7}, {‘is’: 7, ‘Gfg’: 5, ‘Best’: 2}Explanation : Sorted by keys, in ascending and reverse order." }, { "code": null, "e": 26621, "s": 26426, "text": "Input : test_dict = {“Best” : 2, “for” : 9, “geeks” : 8}Output : {‘Best’: 2, ‘Gfg’: 5, ‘for’: 9}, {‘for’: 9, ‘geeks’: 8, ‘Best’: 2}Explanation : Sorted by values, in ascending and reverse order." }, { "code": null, "e": 26643, "s": 26621, "text": "Case 1 : Sort by Keys" }, { "code": null, "e": 26893, "s": 26643, "text": "This task is performed using sorted(), in this, we extract the keys using 1st index of items of dictionary extracted by items(), and pass it in key as custom lambda function to get sorted by keys. The “reverse=True” is added to perform reverse sort." }, { "code": null, "e": 26901, "s": 26893, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Sort a Dictionary# Sort by Keys # initializing dictionarytest_dict = {\"Gfg\" : 5, \"is\" : 7, \"Best\" : 2, \"for\" : 9, \"geeks\" : 8} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # using items() to get all items # lambda function is passed in key to perform sort by key res = {key: val for key, val in sorted(test_dict.items(), key = lambda ele: ele[0])} # printing result print(\"Result dictionary sorted by keys : \" + str(res)) # using items() to get all items # lambda function is passed in key to perform sort by key # adding \"reversed = True\" for reversed orderres = {key: val for key, val in sorted(test_dict.items(), key = lambda ele: ele[0], reverse = True)} # printing result print(\"Result dictionary sorted by keys ( in reversed order ) : \" + str(res)) ", "e": 27748, "s": 26901, "text": null }, { "code": null, "e": 28029, "s": 27748, "text": "The original dictionary is : {'Gfg': 5, 'is': 7, 'Best': 2, 'for': 9, 'geeks': 8}\nResult dictionary sorted by keys : {'Best': 2, 'Gfg': 5, 'for': 9, 'geeks': 8, 'is': 7}\nResult dictionary sorted by keys ( in reversed order ) : {'is': 7, 'geeks': 8, 'for': 9, 'Gfg': 5, 'Best': 2}\n" }, { "code": null, "e": 28054, "s": 28029, "text": "Case 2 : Sort by Values " }, { "code": null, "e": 28204, "s": 28054, "text": "This task can be performed in similar way as above, the only difference being for extracting values, 2nd element of items() is passed as comparator. " }, { "code": null, "e": 28212, "s": 28204, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Sort a Dictionary# Sort by Values # initializing dictionarytest_dict = {\"Gfg\" : 5, \"is\" : 7, \"Best\" : 2, \"for\" : 9, \"geeks\" : 8} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # using items() to get all items # lambda function is passed in key to perform sort by key # passing 2nd element of items()res = {key: val for key, val in sorted(test_dict.items(), key = lambda ele: ele[1])} # printing result print(\"Result dictionary sorted by values : \" + str(res)) # using items() to get all items # lambda function is passed in key to perform sort by key # passing 2nd element of items()# adding \"reversed = True\" for reversed orderres = {key: val for key, val in sorted(test_dict.items(), key = lambda ele: ele[1], reverse = True)} # printing result print(\"Result dictionary sorted by values ( in reversed order ) : \" + str(res))", "e": 29129, "s": 28212, "text": null }, { "code": null, "e": 29414, "s": 29129, "text": "The original dictionary is : {'Gfg': 5, 'is': 7, 'Best': 2, 'for': 9, 'geeks': 8}\nResult dictionary sorted by values : {'Best': 2, 'Gfg': 5, 'is': 7, 'geeks': 8, 'for': 9}\nResult dictionary sorted by values ( in reversed order ) : {'for': 9, 'geeks': 8, 'is': 7, 'Gfg': 5, 'Best': 2}\n" }, { "code": null, "e": 29441, "s": 29414, "text": "Python dictionary-programs" }, { "code": null, "e": 29448, "s": 29441, "text": "Python" }, { "code": null, "e": 29464, "s": 29448, "text": "Python Programs" }, { "code": null, "e": 29562, "s": 29464, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29580, "s": 29562, "text": "Python Dictionary" }, { "code": null, "e": 29615, "s": 29580, "text": "Read a file line by line in Python" }, { "code": null, "e": 29647, "s": 29615, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29669, "s": 29647, "text": "Enumerate() in Python" }, { "code": null, "e": 29711, "s": 29669, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29754, "s": 29711, "text": "Python program to convert a list to string" }, { "code": null, "e": 29776, "s": 29754, "text": "Defaultdict in Python" }, { "code": null, "e": 29815, "s": 29776, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 29861, "s": 29815, "text": "Python | Split string into list of characters" } ]
LocalTime now() method in Java with Examples - GeeksforGeeks
12 May, 2020 The now() method of the LocalTime class in Java is used to get the current time from the system clock in the default time-zone. Syntax: public static LocalTime now() Parameters: This method does not accept any parameter. Return value: This method returns the current time using the system clock and default time-zone. Below programs illustrate the now() method of LocalTime in Java: Program 1: // Java program to demonstrate// LocalTime.now() method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // apply now() method // of LocalTime class LocalTime time = LocalTime.now(); // print time System.out.println("Time: " + time); }} Time: 20:43:41.453 Program 2: // Java program to demonstrate// LocalTime.now() method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // apply now() method // of LocalTime class LocalTime time = LocalTime.now(); // print time System.out.println("Time: " + time); }} Time: 20:44:06.567 Above two examples show how the output changes for same program as the time progresses.References: https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#now() Java-Functions Java-LocalTime Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java Set in Java
[ { "code": null, "e": 25505, "s": 25477, "text": "\n12 May, 2020" }, { "code": null, "e": 25633, "s": 25505, "text": "The now() method of the LocalTime class in Java is used to get the current time from the system clock in the default time-zone." }, { "code": null, "e": 25641, "s": 25633, "text": "Syntax:" }, { "code": null, "e": 25671, "s": 25641, "text": "public static LocalTime now()" }, { "code": null, "e": 25726, "s": 25671, "text": "Parameters: This method does not accept any parameter." }, { "code": null, "e": 25823, "s": 25726, "text": "Return value: This method returns the current time using the system clock and default time-zone." }, { "code": null, "e": 25888, "s": 25823, "text": "Below programs illustrate the now() method of LocalTime in Java:" }, { "code": null, "e": 25899, "s": 25888, "text": "Program 1:" }, { "code": "// Java program to demonstrate// LocalTime.now() method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // apply now() method // of LocalTime class LocalTime time = LocalTime.now(); // print time System.out.println(\"Time: \" + time); }}", "e": 26271, "s": 25899, "text": null }, { "code": null, "e": 26291, "s": 26271, "text": "Time: 20:43:41.453\n" }, { "code": null, "e": 26302, "s": 26291, "text": "Program 2:" }, { "code": "// Java program to demonstrate// LocalTime.now() method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // apply now() method // of LocalTime class LocalTime time = LocalTime.now(); // print time System.out.println(\"Time: \" + time); }}", "e": 26674, "s": 26302, "text": null }, { "code": null, "e": 26694, "s": 26674, "text": "Time: 20:44:06.567\n" }, { "code": null, "e": 26867, "s": 26694, "text": "Above two examples show how the output changes for same program as the time progresses.References: https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#now()" }, { "code": null, "e": 26882, "s": 26867, "text": "Java-Functions" }, { "code": null, "e": 26897, "s": 26882, "text": "Java-LocalTime" }, { "code": null, "e": 26902, "s": 26897, "text": "Java" }, { "code": null, "e": 26907, "s": 26902, "text": "Java" }, { "code": null, "e": 27005, "s": 26907, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27035, "s": 27005, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27050, "s": 27035, "text": "Stream In Java" }, { "code": null, "e": 27069, "s": 27050, "text": "Interfaces in Java" }, { "code": null, "e": 27100, "s": 27069, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27118, "s": 27100, "text": "ArrayList in Java" }, { "code": null, "e": 27150, "s": 27118, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27170, "s": 27150, "text": "Stack Class in Java" }, { "code": null, "e": 27202, "s": 27170, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 27226, "s": 27202, "text": "Singleton Class in Java" } ]
Matrix Multiplication | Recursive - GeeksforGeeks
27 Apr, 2021 Given two matrices A and B. The task is to multiply matrix A and matrix B recursively. If matrix A and matrix B are not multiplicative compatible, then generate output “Not Possible”.Examples : Input: A = 12 56 45 78 B = 2 6 5 8 Output: 304 520 480 894 Input: A = 1 2 3 4 5 6 7 8 9 B = 1 2 3 4 5 6 7 8 9 Output: 30 36 42 66 81 96 102 126 150 It is recommended to first refer Iterative Matrix Multiplication.First check if multiplication between matrices is possible or not. For this, check if number of columns of first matrix is equal to number of rows of second matrix or not. If both are equal than proceed further otherwise generate output “Not Possible”.In Recursive Matrix Multiplication, we implement three loops of Iteration through recursive calls. The inner most Recursive call of multiplyMatrix() is to iterate k (col1 or row2). The second recursive call of multiplyMatrix() is to change the columns and the outermost recursive call is to change rows.Below is Recursive Matrix Multiplication code. C/C++ // Recursive code for Matrix Multiplication #include <stdio.h> const int MAX = 100; void multiplyMatrixRec(int row1, int col1, int A[][MAX], int row2, int col2, int B[][MAX], int C[][MAX]) { // Note that below variables are static // i and j are used to know current cell of // result matrix C[][]. k is used to know // current column number of A[][] and row // number of B[][] to be multiplied static int i = 0, j = 0, k = 0; // If all rows traversed. if (i >= row1) return; // If i < row1 if (j < col2) { if (k < col1) { C[i][j] += A[i][k] * B[k][j]; k++; multiplyMatrixRec(row1, col1, A, row2, col2, B, C); } k = 0; j++; multiplyMatrixRec(row1, col1, A, row2, col2, B, C); } j = 0; i++; multiplyMatrixRec(row1, col1, A, row2, col2, B, C); } // Function to multiply two matrices A[][] and B[][] void multiplyMatrix(int row1, int col1, int A[][MAX], int row2, int col2, int B[][MAX]) { if (row2 != col1) { printf("Not Possible\n"); return; } int C[MAX][MAX] = {0}; multiplyMatrixRec(row1, col1, A, row2, col2, B, C); // Print the result for (int i = 0; i < row1; i++) { for (int j = 0; j < col2; j++) printf("%d ", C[i][j]); printf("\n"); } } // Driven Program int main() { int A[][MAX] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int B[][MAX] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int row1 = 3, col1 = 3, row2 = 3, col2 = 3; multiplyMatrix(row1, col1, A, row2, col2, B); return 0; } Java Python3 C# Javascript // Java recursive code for Matrix Multiplication class GFG{ public static int MAX = 100; // Note that below variables are static // i and j are used to know current cell of // result matrix C[][]. k is used to know // current column number of A[][] and row // number of B[][] to be multiplied public static int i = 0, j = 0, k = 0; static void multiplyMatrixRec(int row1, int col1, int A[][], int row2, int col2, int B[][], int C[][]) { // If all rows traversed if (i >= row1) return; // If i < row1 if (j < col2) { if (k < col1) { C[i][j] += A[i][k] * B[k][j]; k++; multiplyMatrixRec(row1, col1, A, row2, col2, B, C); } k = 0; j++; multiplyMatrixRec(row1, col1, A, row2, col2, B, C); } j = 0; i++; multiplyMatrixRec(row1, col1, A, row2, col2, B, C); } // Function to multiply two matrices A[][] and B[][] static void multiplyMatrix(int row1, int col1, int A[][], int row2, int col2, int B[][]) { if (row2 != col1) { System.out.println("Not Possible\n"); return; } int[][] C = new int[MAX][MAX]; multiplyMatrixRec(row1, col1, A, row2, col2, B, C); // Print the result for (int i = 0; i < row1; i++) { for (int j = 0; j < col2; j++) System.out.print(C[i][j]+" "); System.out.println(); } } // driver program public static void main (String[] args) { int row1 = 3, col1 = 3, row2 = 3, col2 = 3; int A[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int B[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; multiplyMatrix(row1, col1, A, row2, col2, B); }} // Contributed by Pramod Kumar # Recursive code for Matrix MultiplicationMAX = 100i = 0j = 0k = 0 def multiplyMatrixRec(row1, col1, A, row2, col2, B, C): # Note that below variables are static # i and j are used to know current cell of # result matrix C[][]. k is used to know # current column number of A[][] and row # number of B[][] to be multiplied global i global j global k # If all rows traversed. if (i >= row1): return # If i < row1 if (j < col2): if (k < col1): C[i][j] += A[i][k] * B[k][j] k += 1 multiplyMatrixRec(row1, col1, A, row2, col2,B, C) k = 0 j += 1 multiplyMatrixRec(row1, col1, A, row2, col2, B, C) j = 0 i += 1 multiplyMatrixRec(row1, col1, A, row2, col2, B, C) # Function to multiply two matrices# A[][] and B[][]def multiplyMatrix(row1, col1, A, row2, col2, B): if (row2 != col1): print("Not Possible") return C = [[0 for i in range(MAX)] for i in range(MAX)] multiplyMatrixRec(row1, col1, A, row2, col2, B, C) # Print the result for i in range(row1): for j in range(col2): print( C[i][j], end = " ") print() # Driver CodeA = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]B = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] row1 = 3col1 = 3row2 = 3col2 = 3multiplyMatrix(row1, col1, A, row2, col2, B) # This code is contributed by sahilshelangia // C# recursive code for// Matrix Multiplicationusing System; class GFG{ public static int MAX = 100; // Note that below variables // are static i and j are used // to know current cell of result // matrix C[][]. k is used to // know current column number of // A[][] and row number of B[][] // to be multiplied public static int i = 0, j = 0, k = 0; static void multiplyMatrixRec(int row1, int col1, int [,]A, int row2, int col2, int [,]B, int [,]C) { // If all rows traversed if (i >= row1) return; // If i < row1 if (j < col2) { if (k < col1) { C[i, j] += A[i, k] * B[k, j]; k++; multiplyMatrixRec(row1, col1, A, row2, col2, B, C); } k = 0; j++; multiplyMatrixRec(row1, col1, A, row2, col2, B, C); } j = 0; i++; multiplyMatrixRec(row1, col1, A, row2, col2, B, C); } // Function to multiply two // matrices A[][] and B[][] static void multiplyMatrix(int row1, int col1, int [,]A, int row2, int col2, int [,]B) { if (row2 != col1) { Console.WriteLine("Not Possible\n"); return; } int[,]C = new int[MAX, MAX]; multiplyMatrixRec(row1, col1, A, row2, col2, B, C); // Print the result for (int i = 0; i < row1; i++) { for (int j = 0; j < col2; j++) Console.Write(C[i, j] + " "); Console.WriteLine(); } } // Driver Code static public void Main () { int row1 = 3, col1 = 3, row2 = 3, col2 = 3; int [,]A = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int [,]B = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; multiplyMatrix(row1, col1, A, row2, col2, B); }} // This code is contributed by m_kit <script> // Javascript recursive code for Matrix Multiplication let MAX = 100; // Note that below variables are static // i and j are used to know current cell of // result matrix C[][]. k is used to know // current column number of A[][] and row // number of B[][] to be multiplied let i = 0, j = 0, k = 0; function multiplyMatrixRec(row1, col1, A, row2, col2, B, C) { // If all rows traversed if (i >= row1) return; // If i < row1 if (j < col2) { if (k < col1) { C[i][j] += A[i][k] * B[k][j]; k++; multiplyMatrixRec(row1, col1, A, row2, col2, B, C); } k = 0; j++; multiplyMatrixRec(row1, col1, A, row2, col2, B, C); } j = 0; i++; multiplyMatrixRec(row1, col1, A, row2, col2, B, C); } // Function to multiply two matrices A[][] and B[][] function multiplyMatrix(row1, col1, A, row2, col2, B) { if (row2 != col1) { document.write("Not Possible" + "</br>"); return; } let C = new Array(MAX); for(let i = 0; i < MAX; i++) { C[i] = new Array(MAX); for(let j = 0; j < MAX; j++) { C[i][j] = 0; } } multiplyMatrixRec(row1, col1, A, row2, col2, B, C); // Print the result for (let i = 0; i < row1; i++) { for (let j = 0; j < col2; j++) document.write(C[i][j]+" "); document.write("</br>"); } } let row1 = 3, col1 = 3, row2 = 3, col2 = 3; let A = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; let B = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; multiplyMatrix(row1, col1, A, row2, col2, B); </script> Output : 30 36 42 66 81 96 102 126 150 This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t sahilshelangia decode2207 Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum size square sub-matrix with all 1s Sudoku | Backtracking-7 Count all possible paths from top left to bottom right of a mXn matrix Maximum size rectangle binary sub-matrix with all 1s Inplace rotate square matrix by 90 degrees | Set 1 Min Cost Path | DP-6 Printing all solutions in N-Queen Problem Rotate a matrix by 90 degree in clockwise direction without using any extra space The Celebrity Problem Python program to multiply two matrices
[ { "code": null, "e": 26553, "s": 26525, "text": "\n27 Apr, 2021" }, { "code": null, "e": 26749, "s": 26553, "text": "Given two matrices A and B. The task is to multiply matrix A and matrix B recursively. If matrix A and matrix B are not multiplicative compatible, then generate output “Not Possible”.Examples : " }, { "code": null, "e": 27012, "s": 26749, "text": "Input: A = 12 56\n 45 78\n B = 2 6\n 5 8\nOutput: 304 520\n 480 894\n\nInput: A = 1 2 3\n 4 5 6\n 7 8 9\n B = 1 2 3\n 4 5 6\n 7 8 9\n\nOutput: 30 36 42 \n 66 81 96 \n 102 126 150 " }, { "code": null, "e": 27683, "s": 27014, "text": "It is recommended to first refer Iterative Matrix Multiplication.First check if multiplication between matrices is possible or not. For this, check if number of columns of first matrix is equal to number of rows of second matrix or not. If both are equal than proceed further otherwise generate output “Not Possible”.In Recursive Matrix Multiplication, we implement three loops of Iteration through recursive calls. The inner most Recursive call of multiplyMatrix() is to iterate k (col1 or row2). The second recursive call of multiplyMatrix() is to change the columns and the outermost recursive call is to change rows.Below is Recursive Matrix Multiplication code. " }, { "code": null, "e": 27689, "s": 27683, "text": "C/C++" }, { "code": null, "e": 29512, "s": 27689, "text": "\n// Recursive code for Matrix Multiplication\n#include <stdio.h>\n\nconst int MAX = 100;\n\nvoid multiplyMatrixRec(int row1, int col1, int A[][MAX],\n int row2, int col2, int B[][MAX],\n int C[][MAX])\n{\n // Note that below variables are static\n // i and j are used to know current cell of\n // result matrix C[][]. k is used to know\n // current column number of A[][] and row\n // number of B[][] to be multiplied\n static int i = 0, j = 0, k = 0;\n\n // If all rows traversed.\n if (i >= row1)\n return;\n\n // If i < row1\n if (j < col2)\n {\n if (k < col1)\n {\n C[i][j] += A[i][k] * B[k][j];\n k++;\n\n multiplyMatrixRec(row1, col1, A, row2, col2,\n B, C);\n }\n\n k = 0;\n j++;\n multiplyMatrixRec(row1, col1, A, row2, col2, B, C);\n }\n\n j = 0;\n i++;\n multiplyMatrixRec(row1, col1, A, row2, col2, B, C);\n}\n\n// Function to multiply two matrices A[][] and B[][]\nvoid multiplyMatrix(int row1, int col1, int A[][MAX],\n int row2, int col2, int B[][MAX])\n{\n if (row2 != col1)\n {\n printf(\"Not Possible\\n\");\n return;\n }\n\n int C[MAX][MAX] = {0};\n\n multiplyMatrixRec(row1, col1, A, row2, col2, B, C);\n\n // Print the result\n for (int i = 0; i < row1; i++)\n {\n for (int j = 0; j < col2; j++)\n printf(\"%d \", C[i][j]);\n\n printf(\"\\n\");\n }\n}\n\n// Driven Program\nint main()\n{\n int A[][MAX] = { {1, 2, 3},\n {4, 5, 6},\n {7, 8, 9}};\n\n int B[][MAX] = { {1, 2, 3},\n {4, 5, 6},\n {7, 8, 9} };\n\n int row1 = 3, col1 = 3, row2 = 3, col2 = 3;\n multiplyMatrix(row1, col1, A, row2, col2, B);\n\n return 0;\n}\n" }, { "code": null, "e": 29517, "s": 29512, "text": "Java" }, { "code": null, "e": 29525, "s": 29517, "text": "Python3" }, { "code": null, "e": 29528, "s": 29525, "text": "C#" }, { "code": null, "e": 29539, "s": 29528, "text": "Javascript" }, { "code": "// Java recursive code for Matrix Multiplication class GFG{ public static int MAX = 100; // Note that below variables are static // i and j are used to know current cell of // result matrix C[][]. k is used to know // current column number of A[][] and row // number of B[][] to be multiplied public static int i = 0, j = 0, k = 0; static void multiplyMatrixRec(int row1, int col1, int A[][], int row2, int col2, int B[][], int C[][]) { // If all rows traversed if (i >= row1) return; // If i < row1 if (j < col2) { if (k < col1) { C[i][j] += A[i][k] * B[k][j]; k++; multiplyMatrixRec(row1, col1, A, row2, col2, B, C); } k = 0; j++; multiplyMatrixRec(row1, col1, A, row2, col2, B, C); } j = 0; i++; multiplyMatrixRec(row1, col1, A, row2, col2, B, C); } // Function to multiply two matrices A[][] and B[][] static void multiplyMatrix(int row1, int col1, int A[][], int row2, int col2, int B[][]) { if (row2 != col1) { System.out.println(\"Not Possible\\n\"); return; } int[][] C = new int[MAX][MAX]; multiplyMatrixRec(row1, col1, A, row2, col2, B, C); // Print the result for (int i = 0; i < row1; i++) { for (int j = 0; j < col2; j++) System.out.print(C[i][j]+\" \"); System.out.println(); } } // driver program public static void main (String[] args) { int row1 = 3, col1 = 3, row2 = 3, col2 = 3; int A[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int B[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; multiplyMatrix(row1, col1, A, row2, col2, B); }} // Contributed by Pramod Kumar", "e": 31582, "s": 29539, "text": null }, { "code": "# Recursive code for Matrix MultiplicationMAX = 100i = 0j = 0k = 0 def multiplyMatrixRec(row1, col1, A, row2, col2, B, C): # Note that below variables are static # i and j are used to know current cell of # result matrix C[][]. k is used to know # current column number of A[][] and row # number of B[][] to be multiplied global i global j global k # If all rows traversed. if (i >= row1): return # If i < row1 if (j < col2): if (k < col1): C[i][j] += A[i][k] * B[k][j] k += 1 multiplyMatrixRec(row1, col1, A, row2, col2,B, C) k = 0 j += 1 multiplyMatrixRec(row1, col1, A, row2, col2, B, C) j = 0 i += 1 multiplyMatrixRec(row1, col1, A, row2, col2, B, C) # Function to multiply two matrices# A[][] and B[][]def multiplyMatrix(row1, col1, A, row2, col2, B): if (row2 != col1): print(\"Not Possible\") return C = [[0 for i in range(MAX)] for i in range(MAX)] multiplyMatrixRec(row1, col1, A, row2, col2, B, C) # Print the result for i in range(row1): for j in range(col2): print( C[i][j], end = \" \") print() # Driver CodeA = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]B = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] row1 = 3col1 = 3row2 = 3col2 = 3multiplyMatrix(row1, col1, A, row2, col2, B) # This code is contributed by sahilshelangia", "e": 33156, "s": 31582, "text": null }, { "code": "// C# recursive code for// Matrix Multiplicationusing System; class GFG{ public static int MAX = 100; // Note that below variables // are static i and j are used // to know current cell of result // matrix C[][]. k is used to // know current column number of // A[][] and row number of B[][] // to be multiplied public static int i = 0, j = 0, k = 0; static void multiplyMatrixRec(int row1, int col1, int [,]A, int row2, int col2, int [,]B, int [,]C) { // If all rows traversed if (i >= row1) return; // If i < row1 if (j < col2) { if (k < col1) { C[i, j] += A[i, k] * B[k, j]; k++; multiplyMatrixRec(row1, col1, A, row2, col2, B, C); } k = 0; j++; multiplyMatrixRec(row1, col1, A, row2, col2, B, C); } j = 0; i++; multiplyMatrixRec(row1, col1, A, row2, col2, B, C); } // Function to multiply two // matrices A[][] and B[][] static void multiplyMatrix(int row1, int col1, int [,]A, int row2, int col2, int [,]B) { if (row2 != col1) { Console.WriteLine(\"Not Possible\\n\"); return; } int[,]C = new int[MAX, MAX]; multiplyMatrixRec(row1, col1, A, row2, col2, B, C); // Print the result for (int i = 0; i < row1; i++) { for (int j = 0; j < col2; j++) Console.Write(C[i, j] + \" \"); Console.WriteLine(); } } // Driver Code static public void Main () { int row1 = 3, col1 = 3, row2 = 3, col2 = 3; int [,]A = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int [,]B = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; multiplyMatrix(row1, col1, A, row2, col2, B); }} // This code is contributed by m_kit", "e": 35427, "s": 33156, "text": null }, { "code": "<script> // Javascript recursive code for Matrix Multiplication let MAX = 100; // Note that below variables are static // i and j are used to know current cell of // result matrix C[][]. k is used to know // current column number of A[][] and row // number of B[][] to be multiplied let i = 0, j = 0, k = 0; function multiplyMatrixRec(row1, col1, A, row2, col2, B, C) { // If all rows traversed if (i >= row1) return; // If i < row1 if (j < col2) { if (k < col1) { C[i][j] += A[i][k] * B[k][j]; k++; multiplyMatrixRec(row1, col1, A, row2, col2, B, C); } k = 0; j++; multiplyMatrixRec(row1, col1, A, row2, col2, B, C); } j = 0; i++; multiplyMatrixRec(row1, col1, A, row2, col2, B, C); } // Function to multiply two matrices A[][] and B[][] function multiplyMatrix(row1, col1, A, row2, col2, B) { if (row2 != col1) { document.write(\"Not Possible\" + \"</br>\"); return; } let C = new Array(MAX); for(let i = 0; i < MAX; i++) { C[i] = new Array(MAX); for(let j = 0; j < MAX; j++) { C[i][j] = 0; } } multiplyMatrixRec(row1, col1, A, row2, col2, B, C); // Print the result for (let i = 0; i < row1; i++) { for (let j = 0; j < col2; j++) document.write(C[i][j]+\" \"); document.write(\"</br>\"); } } let row1 = 3, col1 = 3, row2 = 3, col2 = 3; let A = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; let B = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; multiplyMatrix(row1, col1, A, row2, col2, B); </script>", "e": 37366, "s": 35427, "text": null }, { "code": null, "e": 37377, "s": 37366, "text": "Output : " }, { "code": null, "e": 37419, "s": 37377, "text": "30 36 42 \n66 81 96 \n102 126 150 " }, { "code": null, "e": 37844, "s": 37419, "text": "This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 37850, "s": 37844, "text": "jit_t" }, { "code": null, "e": 37865, "s": 37850, "text": "sahilshelangia" }, { "code": null, "e": 37876, "s": 37865, "text": "decode2207" }, { "code": null, "e": 37883, "s": 37876, "text": "Matrix" }, { "code": null, "e": 37890, "s": 37883, "text": "Matrix" }, { "code": null, "e": 37988, "s": 37890, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38031, "s": 37988, "text": "Maximum size square sub-matrix with all 1s" }, { "code": null, "e": 38055, "s": 38031, "text": "Sudoku | Backtracking-7" }, { "code": null, "e": 38126, "s": 38055, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 38179, "s": 38126, "text": "Maximum size rectangle binary sub-matrix with all 1s" }, { "code": null, "e": 38230, "s": 38179, "text": "Inplace rotate square matrix by 90 degrees | Set 1" }, { "code": null, "e": 38251, "s": 38230, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 38293, "s": 38251, "text": "Printing all solutions in N-Queen Problem" }, { "code": null, "e": 38375, "s": 38293, "text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space" }, { "code": null, "e": 38397, "s": 38375, "text": "The Celebrity Problem" } ]
Program to check if an array is palindrome or not using Recursion - GeeksforGeeks
01 Apr, 2021 Given an array. The task is to determine whether an array is a palindrome or not using recursion.Examples: Input: arr[] = {3, 6, 0, 6, 3} Output: Palindrome Input: arr[] = {1, 2, 3, 4, 5} Output: Not Palindrome Approach: Base case: If array has only one element i.e. begin == end then return 1, also if begin>end which means the array is palindrome then also return 1.If the first and the last elements are equal then recursively call the function again but increment begin by 1 and decrement end by 1.If the first and last element is not equal then return 0. Base case: If array has only one element i.e. begin == end then return 1, also if begin>end which means the array is palindrome then also return 1. If the first and the last elements are equal then recursively call the function again but increment begin by 1 and decrement end by 1. If the first and last element is not equal then return 0. Below is the implementation of the above approach: C++ Java Python 3 C# PHP Javascript // C++ implementation of above approach#include <iostream>using namespace std; // Recursive function that returns 1 if// palindrome, 0 if not palindromeint palindrome(int arr[], int begin, int end){ // base case if (begin >= end) { return 1; } if (arr[begin] == arr[end]) { return palindrome(arr, begin + 1, end - 1); } else { return 0; }} // Driver codeint main(){ int a[] = { 3, 6, 0, 6, 3 }; int n = sizeof(a) / sizeof(a[0]); if (palindrome(a, 0, n - 1) == 1) cout << "Palindrome"; else cout << "Not Palindrome"; return 0;} // Java implementation of above approach import java.io.*; class GFG { // Recursive function that returns 1 if// palindrome, 0 if not palindromestatic int palindrome(int arr[], int begin, int end){ // base case if (begin >= end) { return 1; } if (arr[begin] == arr[end]) { return palindrome(arr, begin + 1, end - 1); } else { return 0; }} // Driver code public static void main (String[] args) { int a[] = { 3, 6, 0, 6, 3 }; int n = a.length; if (palindrome(a, 0, n - 1) == 1) System.out.print( "Palindrome"); else System.out.println( "Not Palindrome"); }} # Python 3 implementation of above approach # Recursive function that returns 1 if# palindrome, 0 if not palindromedef palindrome(arr, begin, end): # base case if (begin >= end) : return 1 if (arr[begin] == arr[end]) : return palindrome(arr, begin + 1, end - 1) else : return 0 # Driver codeif __name__ == "__main__": a = [ 3, 6, 0, 6, 3 ] n = len(a) if (palindrome(a, 0, n - 1) == 1): print("Palindrome") else: print("Not Palindrome") # This code is contributed# by ChitraNayal // C# implementation of above approachusing System; class GFG{ // Recursive function that returns 1// if palindrome, 0 if not palindromestatic int palindrome(int []arr, int begin, int end){ // base case if (begin >= end) { return 1; } if (arr[begin] == arr[end]) { return palindrome(arr, begin + 1, end - 1); } else { return 0; }} // Driver codepublic static void Main (){ int []a = { 3, 6, 0, 6, 3 }; int n = a.Length; if (palindrome(a, 0, n - 1) == 1) Console.WriteLine("Palindrome"); else Console.WriteLine("Not Palindrome");}} // This code is contributed by inder_verma <?php// PHP implementation of above approach // Recursive function that returns 1// if palindrome, 0 if not palindromefunction palindrome($arr, $begin, $end){ // base case if ($begin >= $end) { return 1; } if ($arr[$begin] == $arr[$end]) { return palindrome($arr, $begin + 1, $end - 1); } else { return 0; }} // Driver code$a = array( 3, 6, 0, 6, 3 );$n = count($a); if (palindrome($a, 0, $n - 1) == 1) echo "Palindrome";else echo "Not Palindrome"; // This code is contributed// by inder_verma?> <script> // Javascript implementation of above approach // Recursive function that returns 1 if // palindrome, 0 if not palindrome function palindrome(arr, begin, end) { // base case if (begin >= end) { return 1; } if (arr[begin] == arr[end]) { return palindrome(arr, begin + 1, end - 1); } else { return 0; } } // Driver code let a = [ 3, 6, 0, 6, 3 ]; let n = a.length; if (palindrome(a, 0, n - 1) == 1) document.write("Palindrome"); else document.write("Not Palindrome"); // This code is contributed by divyeshrabadiya07. </script> Palindrome Shashank12 inderDuMCA ukasp divyeshrabadiya07 palindrome Arrays Recursion Arrays Recursion palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Write a program to print all permutations of a given string Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Backtracking | Introduction
[ { "code": null, "e": 26294, "s": 26266, "text": "\n01 Apr, 2021" }, { "code": null, "e": 26403, "s": 26294, "text": "Given an array. The task is to determine whether an array is a palindrome or not using recursion.Examples: " }, { "code": null, "e": 26508, "s": 26403, "text": "Input: arr[] = {3, 6, 0, 6, 3}\nOutput: Palindrome\n\nInput: arr[] = {1, 2, 3, 4, 5}\nOutput: Not Palindrome" }, { "code": null, "e": 26522, "s": 26510, "text": "Approach: " }, { "code": null, "e": 26861, "s": 26522, "text": "Base case: If array has only one element i.e. begin == end then return 1, also if begin>end which means the array is palindrome then also return 1.If the first and the last elements are equal then recursively call the function again but increment begin by 1 and decrement end by 1.If the first and last element is not equal then return 0." }, { "code": null, "e": 27009, "s": 26861, "text": "Base case: If array has only one element i.e. begin == end then return 1, also if begin>end which means the array is palindrome then also return 1." }, { "code": null, "e": 27144, "s": 27009, "text": "If the first and the last elements are equal then recursively call the function again but increment begin by 1 and decrement end by 1." }, { "code": null, "e": 27202, "s": 27144, "text": "If the first and last element is not equal then return 0." }, { "code": null, "e": 27255, "s": 27202, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27259, "s": 27255, "text": "C++" }, { "code": null, "e": 27264, "s": 27259, "text": "Java" }, { "code": null, "e": 27273, "s": 27264, "text": "Python 3" }, { "code": null, "e": 27276, "s": 27273, "text": "C#" }, { "code": null, "e": 27280, "s": 27276, "text": "PHP" }, { "code": null, "e": 27291, "s": 27280, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <iostream>using namespace std; // Recursive function that returns 1 if// palindrome, 0 if not palindromeint palindrome(int arr[], int begin, int end){ // base case if (begin >= end) { return 1; } if (arr[begin] == arr[end]) { return palindrome(arr, begin + 1, end - 1); } else { return 0; }} // Driver codeint main(){ int a[] = { 3, 6, 0, 6, 3 }; int n = sizeof(a) / sizeof(a[0]); if (palindrome(a, 0, n - 1) == 1) cout << \"Palindrome\"; else cout << \"Not Palindrome\"; return 0;}", "e": 27891, "s": 27291, "text": null }, { "code": "// Java implementation of above approach import java.io.*; class GFG { // Recursive function that returns 1 if// palindrome, 0 if not palindromestatic int palindrome(int arr[], int begin, int end){ // base case if (begin >= end) { return 1; } if (arr[begin] == arr[end]) { return palindrome(arr, begin + 1, end - 1); } else { return 0; }} // Driver code public static void main (String[] args) { int a[] = { 3, 6, 0, 6, 3 }; int n = a.length; if (palindrome(a, 0, n - 1) == 1) System.out.print( \"Palindrome\"); else System.out.println( \"Not Palindrome\"); }}", "e": 28523, "s": 27891, "text": null }, { "code": "# Python 3 implementation of above approach # Recursive function that returns 1 if# palindrome, 0 if not palindromedef palindrome(arr, begin, end): # base case if (begin >= end) : return 1 if (arr[begin] == arr[end]) : return palindrome(arr, begin + 1, end - 1) else : return 0 # Driver codeif __name__ == \"__main__\": a = [ 3, 6, 0, 6, 3 ] n = len(a) if (palindrome(a, 0, n - 1) == 1): print(\"Palindrome\") else: print(\"Not Palindrome\") # This code is contributed# by ChitraNayal", "e": 29105, "s": 28523, "text": null }, { "code": "// C# implementation of above approachusing System; class GFG{ // Recursive function that returns 1// if palindrome, 0 if not palindromestatic int palindrome(int []arr, int begin, int end){ // base case if (begin >= end) { return 1; } if (arr[begin] == arr[end]) { return palindrome(arr, begin + 1, end - 1); } else { return 0; }} // Driver codepublic static void Main (){ int []a = { 3, 6, 0, 6, 3 }; int n = a.Length; if (palindrome(a, 0, n - 1) == 1) Console.WriteLine(\"Palindrome\"); else Console.WriteLine(\"Not Palindrome\");}} // This code is contributed by inder_verma", "e": 29812, "s": 29105, "text": null }, { "code": "<?php// PHP implementation of above approach // Recursive function that returns 1// if palindrome, 0 if not palindromefunction palindrome($arr, $begin, $end){ // base case if ($begin >= $end) { return 1; } if ($arr[$begin] == $arr[$end]) { return palindrome($arr, $begin + 1, $end - 1); } else { return 0; }} // Driver code$a = array( 3, 6, 0, 6, 3 );$n = count($a); if (palindrome($a, 0, $n - 1) == 1) echo \"Palindrome\";else echo \"Not Palindrome\"; // This code is contributed// by inder_verma?>", "e": 30396, "s": 29812, "text": null }, { "code": "<script> // Javascript implementation of above approach // Recursive function that returns 1 if // palindrome, 0 if not palindrome function palindrome(arr, begin, end) { // base case if (begin >= end) { return 1; } if (arr[begin] == arr[end]) { return palindrome(arr, begin + 1, end - 1); } else { return 0; } } // Driver code let a = [ 3, 6, 0, 6, 3 ]; let n = a.length; if (palindrome(a, 0, n - 1) == 1) document.write(\"Palindrome\"); else document.write(\"Not Palindrome\"); // This code is contributed by divyeshrabadiya07. </script>", "e": 31085, "s": 30396, "text": null }, { "code": null, "e": 31096, "s": 31085, "text": "Palindrome" }, { "code": null, "e": 31109, "s": 31098, "text": "Shashank12" }, { "code": null, "e": 31120, "s": 31109, "text": "inderDuMCA" }, { "code": null, "e": 31126, "s": 31120, "text": "ukasp" }, { "code": null, "e": 31144, "s": 31126, "text": "divyeshrabadiya07" }, { "code": null, "e": 31155, "s": 31144, "text": "palindrome" }, { "code": null, "e": 31162, "s": 31155, "text": "Arrays" }, { "code": null, "e": 31172, "s": 31162, "text": "Recursion" }, { "code": null, "e": 31179, "s": 31172, "text": "Arrays" }, { "code": null, "e": 31189, "s": 31179, "text": "Recursion" }, { "code": null, "e": 31200, "s": 31189, "text": "palindrome" }, { "code": null, "e": 31298, "s": 31200, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31366, "s": 31298, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 31410, "s": 31366, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 31458, "s": 31410, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 31481, "s": 31458, "text": "Introduction to Arrays" }, { "code": null, "e": 31513, "s": 31481, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 31573, "s": 31513, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 31658, "s": 31573, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 31668, "s": 31658, "text": "Recursion" }, { "code": null, "e": 31695, "s": 31668, "text": "Program for Tower of Hanoi" } ]
How to concatenate two integer arrays without using loop in C ? - GeeksforGeeks
02 Jun, 2017 Given two arrays such that first array has enough extra space to accommodate elements of second array. How to concatenate second array to first in C without using any loop in program? Example: Input: arr1[5] = {1, 2, 3} arr2[] = {4, 5} Output: arr1[] = {1, 2, 3, 4, 5} We strongly recommend you to minimize your browser and try this yourself first. Hint: We may use library functions in C. The idea is to use memcpy() or memmove() in C. // arr1[] is of size m+n and arr2[] is of size n. This function// appends contents of arr2[] at the end of arr1[]void concatenate(int arr1[], int arr2[], int m, int n){ memcpy(arr1 + m, arr2, sizeof(arr2)); } See this for complete running code. Thanks to Utkarsh Trivedi for suggesting above solution. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above C-Arrays C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C 'this' pointer in C++ Arrow operator -> in C/C++ with Examples Ways to copy a vector in C++ Smart Pointers in C++ and How to Use Them Understanding "extern" keyword in C Multiple Inheritance in C++ How to split a string in C/C++, Python and Java?
[ { "code": null, "e": 25477, "s": 25449, "text": "\n02 Jun, 2017" }, { "code": null, "e": 25661, "s": 25477, "text": "Given two arrays such that first array has enough extra space to accommodate elements of second array. How to concatenate second array to first in C without using any loop in program?" }, { "code": null, "e": 25670, "s": 25661, "text": "Example:" }, { "code": null, "e": 25755, "s": 25670, "text": "Input: arr1[5] = {1, 2, 3}\n arr2[] = {4, 5}\nOutput: arr1[] = {1, 2, 3, 4, 5}\n" }, { "code": null, "e": 25835, "s": 25755, "text": "We strongly recommend you to minimize your browser and try this yourself first." }, { "code": null, "e": 25878, "s": 25837, "text": "Hint: We may use library functions in C." }, { "code": null, "e": 25925, "s": 25878, "text": "The idea is to use memcpy() or memmove() in C." }, { "code": "// arr1[] is of size m+n and arr2[] is of size n. This function// appends contents of arr2[] at the end of arr1[]void concatenate(int arr1[], int arr2[], int m, int n){ memcpy(arr1 + m, arr2, sizeof(arr2)); }", "e": 26136, "s": 25925, "text": null }, { "code": null, "e": 26172, "s": 26136, "text": "See this for complete running code." }, { "code": null, "e": 26229, "s": 26172, "text": "Thanks to Utkarsh Trivedi for suggesting above solution." }, { "code": null, "e": 26353, "s": 26229, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 26362, "s": 26353, "text": "C-Arrays" }, { "code": null, "e": 26373, "s": 26362, "text": "C Language" }, { "code": null, "e": 26471, "s": 26373, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26509, "s": 26471, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 26535, "s": 26509, "text": "Exception Handling in C++" }, { "code": null, "e": 26555, "s": 26535, "text": "Multithreading in C" }, { "code": null, "e": 26577, "s": 26555, "text": "'this' pointer in C++" }, { "code": null, "e": 26618, "s": 26577, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 26647, "s": 26618, "text": "Ways to copy a vector in C++" }, { "code": null, "e": 26689, "s": 26647, "text": "Smart Pointers in C++ and How to Use Them" }, { "code": null, "e": 26725, "s": 26689, "text": "Understanding \"extern\" keyword in C" }, { "code": null, "e": 26753, "s": 26725, "text": "Multiple Inheritance in C++" } ]
Skewness of statistical data - GeeksforGeeks
25 May, 2021 Given data in an array. Find skewness of the data distribution.Skewness is a measure of the asymmetry of data distribution. Skewness is an asymmetry in a statistical distribution, in which the curve appears distorted or skewed either to the left or to the right. Skewness can be quantified to define the extent to which a distribution differs from a normal distribution. Skewness can be calculated as Where gamma is called skewness sigma is called standard deviation and sigma square can be calculated as N is number of population and mu is called mean of data. Examples : Input : arr[] = {2.5, 3.7, 6.6, 9.1, 9.5, 10.7, 11.9, 21.5, 22.6, 25.2} Output : 0.777001 Input : arr[] = {5, 20, 40, 80, 100} Output : 0.0980392 For more about skewness https://en.wikipedia.org/wiki/Skewness https://www.universalclass.com/articles/math/statistics/skewness-in-statistical-terms.htm C++ Java Python3 C# PHP Javascript // CPP code to find skewness// of statistical data. #include<bits/stdc++.h>using namespace std; // Function to calculate// mean of data.float mean(float arr[], int n){ float sum = 0; for (int i = 0; i < n; i++) sum = sum + arr[i]; return sum / n;} // Function to calculate standard// deviation of data.float standardDeviation(float arr[], int n){ float sum = 0; // find standard deviation // deviation of data. for (int i = 0; i < n; i++) sum = (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)); return sqrt(sum / n);} // Function to calculate skewness.float skewness(float arr[], int n){ // Find skewness using above formula float sum = 0; for (int i = 0; i < n; i++) sum = (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)); return sum / (n * standardDeviation(arr, n) * standardDeviation(arr, n) * standardDeviation(arr, n) * standardDeviation(arr, n));} // Driver functionint main(){ float arr[] = {2.5, 3.7, 6.6, 9.1, 9.5, 10.7, 11.9, 21.5, 22.6, 25.2}; // calculate size of array. int n = sizeof(arr)/sizeof(arr[0]); // skewness Function call cout << skewness(arr, n); return 0;} // java code to find skewness// of statistical data.import java.io.*; class GFG { // Function to calculate // mean of data. static double mean(double arr[], int n) { double sum = 0; for (int i = 0; i < n; i++) sum = sum + arr[i]; return sum / n; } // Function to calculate standard // deviation of data. static double standardDeviation(double arr[], int n) { double sum = 0 ; // find standard deviation // deviation of data. for (int i = 0; i < n; i++) sum = (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)); return Math.sqrt(sum / n); } // Function to calculate skewness. static double skewness(double arr[], int n) { // Find skewness using // above formula double sum = 0; for (int i = 0; i < n; i++) sum = (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)); return sum / (n * standardDeviation(arr, n) * standardDeviation(arr, n) * standardDeviation(arr, n) * standardDeviation(arr, n)); } // Driver function public static void main (String[] args) { double arr[] = { 2.5, 3.7, 6.6, 9.1, 9.5, 10.7, 11.9, 21.5, 22.6, 25.2 }; // calculate size of array. int n = arr.length; // skewness Function call System.out.println(skewness(arr, n)); }} //This code is contributed by vt_m # Python3 code to find skewness# of statistical data.from math import sqrt # Function to calculate# mean of data.def mean(arr, n): summ = 0 for i in range(n): summ = summ + arr[i] return summ / n # Function to calculate standard# deviation of data.def standardDeviation(arr,n): summ = 0 # find standard deviation # deviation of data. for i in range(n): summ = (arr[i] - mean(arr, n)) *(arr[i] - mean(arr, n)) return sqrt(summ / n) # Function to calculate skewness.def skewness(arr, n): # Find skewness using above formula summ = 0 for i in range(n): summ = (arr[i] - mean(arr, n))*(arr[i] - mean(arr, n))*(arr[i] - mean(arr, n)) return summ / (n * standardDeviation(arr, n) *standardDeviation(arr, n) *standardDeviation(arr, n) * standardDeviation(arr, n)) # Driver function arr = [2.5, 3.7, 6.6, 9.1,9.5, 10.7, 11.9, 21.5,22.6, 25.2] # calculate size of array.n = len(arr) # skewness Function callprint('%.6f'%skewness(arr, n)) # This code is contributed by shubhamsingh10 // C# code to find skewness// of statistical data.using System; class GFG { // Function to calculate // mean of data. static float mean(double []arr, int n) { double sum = 0; for (int i = 0; i < n; i++) sum = sum + arr[i]; return (float)sum / n; } // Function to calculate standard // deviation of data. static float standardDeviation(double []arr, int n) { double sum = 0 ; // find standard deviation // deviation of data. for (int i = 0; i < n; i++) sum = (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)); return (float)Math.Sqrt(sum / n); } // Function to calculate skewness. static float skewness(double []arr, int n) { // Find skewness using // above formula double sum = 0; for (int i = 0; i < n; i++) sum = (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)); return (float)sum / (n * standardDeviation(arr, n) * standardDeviation(arr, n) * standardDeviation(arr, n) * standardDeviation(arr, n)); } // Driver function public static void Main () { double []arr = { 2.5, 3.7, 6.6, 9.1, 9.5, 10.7, 11.9, 21.5, 22.6, 25.2 }; // calculate size of array. int n = arr.Length; // skewness Function call Console.WriteLine(skewness(arr, n)); }} // This code is contributed by vt_m <?php// PHP code to find skewness// of statistical data. // Function to calculate// mean of data.function mean( $arr, $n){ $sum = 0; for ($i = 0; $i < $n; $i++) $sum = $sum + $arr[$i]; return $sum / $n;} // Function to calculate standard// deviation of data.function standardDeviation($arr, $n){ $sum = 0; // find standard deviation // deviation of data. for ($i = 0; $i < $n; $i++) $sum = ($arr[$i] - mean($arr, $n)) * ($arr[$i] - mean($arr, $n)); return sqrt($sum / $n);} // Function to calculate skewness.function skewness($arr, $n){ // Find skewness using above formula $sum = 0; for ($i = 0; $i < $n; $i++) $sum = ($arr[$i] - mean($arr, $n)) * ($arr[$i] - mean($arr, $n)) * ($arr[$i] - mean($arr, $n)); return $sum / ($n * standardDeviation($arr, $n) * standardDeviation($arr, $n) * standardDeviation($arr, $n) * standardDeviation($arr, $n));} // Driver Code$arr = array(2.5, 3.7, 6.6, 9.1, 9.5, 10.7, 11.9, 21.5, 22.6, 25.2); // calculate size of array.$n = count($arr); // skewness Function callecho skewness($arr, $n); // This code is contributed by vt_m?> <script> // JavaScript code to find skewness // of statistical data. // Function to calculate // mean of data. function mean(arr, n) { let sum = 0; for (let i = 0; i < n; i++) sum = sum + arr[i]; return sum / n; } // Function to calculate standard // deviation of data. function standardDeviation(arr, n) { let sum = 0 ; // find standard deviation // deviation of data. for (let i = 0; i < n; i++) sum = (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)); return Math.sqrt(sum / n); } // Function to calculate skewness. function skewness(arr, n) { // Find skewness using // above formula let sum = 0; for (let i = 0; i < n; i++) sum = (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)); return sum / (n * standardDeviation(arr, n) * standardDeviation(arr, n) * standardDeviation(arr, n) * standardDeviation(arr, n)); } let arr = [ 2.5, 3.7, 6.6, 9.1, 9.5, 10.7, 11.9, 21.5, 22.6, 25.2 ]; // calculate size of array. let n = arr.length; // skewness Function call document.write(skewness(arr, n).toFixed(6)); </script> Output: 0.777001 vt_m SHUBHAMSINGH10 mukesh07 statistical-algorithms Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum 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 Find subarray with given sum | Set 1 (Nonnegative Numbers) Remove duplicates from sorted array Move all negative numbers to beginning and positive to end with constant extra space Building Heap from Array
[ { "code": null, "e": 26066, "s": 26038, "text": "\n25 May, 2021" }, { "code": null, "e": 26469, "s": 26066, "text": "Given data in an array. Find skewness of the data distribution.Skewness is a measure of the asymmetry of data distribution. Skewness is an asymmetry in a statistical distribution, in which the curve appears distorted or skewed either to the left or to the right. Skewness can be quantified to define the extent to which a distribution differs from a normal distribution. Skewness can be calculated as " }, { "code": null, "e": 26588, "s": 26471, "text": "Where gamma is called skewness\n sigma is called standard deviation and sigma square can be calculated as\n " }, { "code": null, "e": 26659, "s": 26588, "text": " N is number of population and\n mu is called mean of data. " }, { "code": null, "e": 26672, "s": 26659, "text": "Examples : " }, { "code": null, "e": 26819, "s": 26672, "text": "Input : arr[] = {2.5, 3.7, 6.6, 9.1, 9.5, 10.7, 11.9, 21.5, 22.6, 25.2}\nOutput : 0.777001\n\nInput : arr[] = {5, 20, 40, 80, 100}\nOutput : 0.0980392" }, { "code": null, "e": 26973, "s": 26819, "text": "For more about skewness https://en.wikipedia.org/wiki/Skewness https://www.universalclass.com/articles/math/statistics/skewness-in-statistical-terms.htm " }, { "code": null, "e": 26979, "s": 26975, "text": "C++" }, { "code": null, "e": 26984, "s": 26979, "text": "Java" }, { "code": null, "e": 26992, "s": 26984, "text": "Python3" }, { "code": null, "e": 26995, "s": 26992, "text": "C#" }, { "code": null, "e": 26999, "s": 26995, "text": "PHP" }, { "code": null, "e": 27010, "s": 26999, "text": "Javascript" }, { "code": "// CPP code to find skewness// of statistical data. #include<bits/stdc++.h>using namespace std; // Function to calculate// mean of data.float mean(float arr[], int n){ float sum = 0; for (int i = 0; i < n; i++) sum = sum + arr[i]; return sum / n;} // Function to calculate standard// deviation of data.float standardDeviation(float arr[], int n){ float sum = 0; // find standard deviation // deviation of data. for (int i = 0; i < n; i++) sum = (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)); return sqrt(sum / n);} // Function to calculate skewness.float skewness(float arr[], int n){ // Find skewness using above formula float sum = 0; for (int i = 0; i < n; i++) sum = (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)); return sum / (n * standardDeviation(arr, n) * standardDeviation(arr, n) * standardDeviation(arr, n) * standardDeviation(arr, n));} // Driver functionint main(){ float arr[] = {2.5, 3.7, 6.6, 9.1, 9.5, 10.7, 11.9, 21.5, 22.6, 25.2}; // calculate size of array. int n = sizeof(arr)/sizeof(arr[0]); // skewness Function call cout << skewness(arr, n); return 0;}", "e": 28414, "s": 27010, "text": null }, { "code": "// java code to find skewness// of statistical data.import java.io.*; class GFG { // Function to calculate // mean of data. static double mean(double arr[], int n) { double sum = 0; for (int i = 0; i < n; i++) sum = sum + arr[i]; return sum / n; } // Function to calculate standard // deviation of data. static double standardDeviation(double arr[], int n) { double sum = 0 ; // find standard deviation // deviation of data. for (int i = 0; i < n; i++) sum = (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)); return Math.sqrt(sum / n); } // Function to calculate skewness. static double skewness(double arr[], int n) { // Find skewness using // above formula double sum = 0; for (int i = 0; i < n; i++) sum = (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)); return sum / (n * standardDeviation(arr, n) * standardDeviation(arr, n) * standardDeviation(arr, n) * standardDeviation(arr, n)); } // Driver function public static void main (String[] args) { double arr[] = { 2.5, 3.7, 6.6, 9.1, 9.5, 10.7, 11.9, 21.5, 22.6, 25.2 }; // calculate size of array. int n = arr.length; // skewness Function call System.out.println(skewness(arr, n)); }} //This code is contributed by vt_m", "e": 30208, "s": 28414, "text": null }, { "code": "# Python3 code to find skewness# of statistical data.from math import sqrt # Function to calculate# mean of data.def mean(arr, n): summ = 0 for i in range(n): summ = summ + arr[i] return summ / n # Function to calculate standard# deviation of data.def standardDeviation(arr,n): summ = 0 # find standard deviation # deviation of data. for i in range(n): summ = (arr[i] - mean(arr, n)) *(arr[i] - mean(arr, n)) return sqrt(summ / n) # Function to calculate skewness.def skewness(arr, n): # Find skewness using above formula summ = 0 for i in range(n): summ = (arr[i] - mean(arr, n))*(arr[i] - mean(arr, n))*(arr[i] - mean(arr, n)) return summ / (n * standardDeviation(arr, n) *standardDeviation(arr, n) *standardDeviation(arr, n) * standardDeviation(arr, n)) # Driver function arr = [2.5, 3.7, 6.6, 9.1,9.5, 10.7, 11.9, 21.5,22.6, 25.2] # calculate size of array.n = len(arr) # skewness Function callprint('%.6f'%skewness(arr, n)) # This code is contributed by shubhamsingh10", "e": 31284, "s": 30208, "text": null }, { "code": "// C# code to find skewness// of statistical data.using System; class GFG { // Function to calculate // mean of data. static float mean(double []arr, int n) { double sum = 0; for (int i = 0; i < n; i++) sum = sum + arr[i]; return (float)sum / n; } // Function to calculate standard // deviation of data. static float standardDeviation(double []arr, int n) { double sum = 0 ; // find standard deviation // deviation of data. for (int i = 0; i < n; i++) sum = (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)); return (float)Math.Sqrt(sum / n); } // Function to calculate skewness. static float skewness(double []arr, int n) { // Find skewness using // above formula double sum = 0; for (int i = 0; i < n; i++) sum = (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)); return (float)sum / (n * standardDeviation(arr, n) * standardDeviation(arr, n) * standardDeviation(arr, n) * standardDeviation(arr, n)); } // Driver function public static void Main () { double []arr = { 2.5, 3.7, 6.6, 9.1, 9.5, 10.7, 11.9, 21.5, 22.6, 25.2 }; // calculate size of array. int n = arr.Length; // skewness Function call Console.WriteLine(skewness(arr, n)); }} // This code is contributed by vt_m", "e": 33054, "s": 31284, "text": null }, { "code": "<?php// PHP code to find skewness// of statistical data. // Function to calculate// mean of data.function mean( $arr, $n){ $sum = 0; for ($i = 0; $i < $n; $i++) $sum = $sum + $arr[$i]; return $sum / $n;} // Function to calculate standard// deviation of data.function standardDeviation($arr, $n){ $sum = 0; // find standard deviation // deviation of data. for ($i = 0; $i < $n; $i++) $sum = ($arr[$i] - mean($arr, $n)) * ($arr[$i] - mean($arr, $n)); return sqrt($sum / $n);} // Function to calculate skewness.function skewness($arr, $n){ // Find skewness using above formula $sum = 0; for ($i = 0; $i < $n; $i++) $sum = ($arr[$i] - mean($arr, $n)) * ($arr[$i] - mean($arr, $n)) * ($arr[$i] - mean($arr, $n)); return $sum / ($n * standardDeviation($arr, $n) * standardDeviation($arr, $n) * standardDeviation($arr, $n) * standardDeviation($arr, $n));} // Driver Code$arr = array(2.5, 3.7, 6.6, 9.1, 9.5, 10.7, 11.9, 21.5, 22.6, 25.2); // calculate size of array.$n = count($arr); // skewness Function callecho skewness($arr, $n); // This code is contributed by vt_m?>", "e": 34346, "s": 33054, "text": null }, { "code": "<script> // JavaScript code to find skewness // of statistical data. // Function to calculate // mean of data. function mean(arr, n) { let sum = 0; for (let i = 0; i < n; i++) sum = sum + arr[i]; return sum / n; } // Function to calculate standard // deviation of data. function standardDeviation(arr, n) { let sum = 0 ; // find standard deviation // deviation of data. for (let i = 0; i < n; i++) sum = (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)); return Math.sqrt(sum / n); } // Function to calculate skewness. function skewness(arr, n) { // Find skewness using // above formula let sum = 0; for (let i = 0; i < n; i++) sum = (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)); return sum / (n * standardDeviation(arr, n) * standardDeviation(arr, n) * standardDeviation(arr, n) * standardDeviation(arr, n)); } let arr = [ 2.5, 3.7, 6.6, 9.1, 9.5, 10.7, 11.9, 21.5, 22.6, 25.2 ]; // calculate size of array. let n = arr.length; // skewness Function call document.write(skewness(arr, n).toFixed(6)); </script>", "e": 35851, "s": 34346, "text": null }, { "code": null, "e": 35861, "s": 35851, "text": "Output: " }, { "code": null, "e": 35870, "s": 35861, "text": "0.777001" }, { "code": null, "e": 35877, "s": 35872, "text": "vt_m" }, { "code": null, "e": 35892, "s": 35877, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 35901, "s": 35892, "text": "mukesh07" }, { "code": null, "e": 35924, "s": 35901, "text": "statistical-algorithms" }, { "code": null, "e": 35931, "s": 35924, "text": "Arrays" }, { "code": null, "e": 35938, "s": 35931, "text": "Arrays" }, { "code": null, "e": 36036, "s": 35938, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36063, "s": 36036, "text": "Count pairs with given sum" }, { "code": null, "e": 36094, "s": 36063, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 36119, "s": 36094, "text": "Window Sliding Technique" }, { "code": null, "e": 36157, "s": 36119, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 36178, "s": 36157, "text": "Next Greater Element" }, { "code": null, "e": 36236, "s": 36178, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 36295, "s": 36236, "text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)" }, { "code": null, "e": 36331, "s": 36295, "text": "Remove duplicates from sorted array" }, { "code": null, "e": 36416, "s": 36331, "text": "Move all negative numbers to beginning and positive to end with constant extra space" } ]
How to use the mouse to scale and rotate an image in PyGame ? - GeeksforGeeks
28 Apr, 2021 In this article, we will discuss how to transform the image i.e (scaling and rotating images) using the mouse in Pygame. Step 1: First, import the libraries Pygame and math. import pygame import math from pygame.locals import * Step 2: Now, take the colors as input that we want to use in the game. color_1 = #RGB value of color 1 color_2 = #RGB value of color 2 color_n = #RGB value of color n Step 3: Then, initialize the constructor pygame.init() Step 4: Set the dimensions of your GUI game. w, h = #Width dimension, #Height dimension screen = pygame.display.set_mode((w, h)) Step 5: Set the running value for running the game, the angle by which it can be moved. running = True angle = 0 scale = 1 Step 6: Next, take the image as input which we want to move with the mouse img_logo = pygame.image.load('#Enter the image url') img_logo.convert() Step 7: Draw a border around an image. rect_logo = img_logo.get_rect() pygame.draw.rect(img_logo, color_1, rect_logo, 1) Step 8: Locate the center of the GUI game and get the position of the mouse. center = w//2, h//2 mouse = pygame.mouse.get_pos() Step 9: Store the image in a new variable and construct a rectangle around the image. img = img_logo rect = img.get_rect() rect.center = center Step 10: Set the things which you want your app to do when in running state. while running: for event in pygame.event.get(): Step 10.1: Once the app is in a running state, make it quit if the user wants to quit. if event.type == QUIT: running = False Step 10.2: In case, the user doesn’t want to quit, set at what angle the image should rotate. if event.type == KEYDOWN: if event.key == K_ra: if event.mod & KMOD_SHIFT: # angle at which it should move left angle -= else: # angle at which it should move right angle += Step 10.3: Also, set at what ratio the image size should decrease or increase. elif event.key == K_sa: if event.mod & KMOD_SHIFT: scale /= #scale at which the image size should decrease else: scale *= #scale at which the image size should increase Step 10.4: Set at what coordinates, angle, and scale the image will rotate or resize. elif event.type == MOUSEMOTION: Step 10.4.1: Store the current position of the event in the new variable. mouse = event.pos Step 10.4.2: Locate the Cartesian coordinates with the help of the mouse variable and center of the image for rotating the image.. x = mouse[0] - center[0] y = mouse[1] - center[1] Step 10.4.3: Further, calculate the distance between the two points (0,0) and (x, y) with the help of formula √x2+y2 d = math.sqrt(x ** 2 + y ** 2) Step 10.4.4: Now, calculate the angle in degrees at which the image should rotate using the Python method math.atan2() which returns the arctangent of y/x, in radians. angle = math.degrees(-math.atan2(y, x)) Step 10.4.5: Calculate which scale the image size should decrease or increase using the function abs, which returns the magnitude of the number. scale = abs(5 * d / w) Step 10.4.6: Calculate the updated position of the image in the running state using the rotozoom function which is a combined scale and rotation transform. img = pygame.transform.rotozoom(img_logo, angle, scale) Step 10.4.7: Construct the rectangle around the updated image rect = img.get_rect() rect.center = center Step 11: Next, you need to set the screen color and the image on the screen. screen.fill(color_3) screen.blit(img, rect) Step 12: Later on, draw the rectangle, line, and circles which will help in moving the image. pygame.draw.rect(screen, color_2, rect, #thickness of rectangle) pygame.draw.line(screen, color_3, center, mouse, #Thickness of line) pygame.draw.circle(screen, color_1, center, #radius of circle, #thickness of circumference) pygame.draw.circle(screen, color_2, mouse, #radius of circle, #thickness of circumference) Step 13: Furthermore, update the changes done in the GUI game. pygame.display.update() Step 14: Finally, quit the GUI game. pygame.quit() Below is the implementation. Python # Python program to transform the # image with the mouse #Import the libraries pygame and mathimport pygameimport mathfrom pygame.locals import * # Take colors inputRED = (255, 0, 0)BLACK = (0, 0, 0)YELLOW = (255, 255, 0) #Construct the GUI gamepygame.init() #Set dimensions of game GUIw, h = 600, 440screen = pygame.display.set_mode((w, h)) # Set running, angle and scale valuesrunning = Trueangle = 0scale = 1 # Take image as inputimg_logo = pygame.image.load('gfg_image.jpg')img_logo.convert() # Draw a rectangle around the imagerect_logo = img_logo.get_rect()pygame.draw.rect(img_logo, RED, rect_logo, 1) # Set the center and mouse positioncenter = w//2, h//2mouse = pygame.mouse.get_pos() #Store the image in a new variable#Construct the rectangle around imageimg = img_logorect = img.get_rect()rect.center = center # Setting what happens when game is# in running statewhile running: for event in pygame.event.get(): # Close if the user quits the game if event.type == QUIT: running = False # Set at which angle the image will # move left or right if event.type == KEYDOWN: if event.key == K_ra: if event.mod & KMOD_SHIFT: angle -= 5 else: angle += 5 # Set at what ratio the image will # decrease or increase elif event.key == K_sa: if event.mod & KMOD_SHIFT: scale /= 1.5 else: scale *= 1.5 # Move the image with the specified coordinates, # angle and scale elif event.type == MOUSEMOTION: mouse = event.pos x = mouse[0] - center[0] y = mouse[1] - center[1] d = math.sqrt(x ** 2 + y ** 2) angle = math.degrees(-math.atan2(y, x)) scale = abs(5 * d / w) img = pygame.transform.rotozoom(img_logo, angle, scale) rect = img.get_rect() rect.center = center # Set screen color and image on screen screen.fill(YELLOW) screen.blit(img, rect) # Draw the rectangle, line and circle through # which image can be transformed pygame.draw.rect(screen, BLACK, rect, 3) pygame.draw.line(screen, RED, center, mouse, 2) pygame.draw.circle(screen, RED, center, 6, 1) pygame.draw.circle(screen, BLACK, mouse, 6, 2) # Update the GUI game pygame.display.update() # Quit the GUI gamepygame.quit() Output: Picked Python-PyGame Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n28 Apr, 2021" }, { "code": null, "e": 25658, "s": 25537, "text": "In this article, we will discuss how to transform the image i.e (scaling and rotating images) using the mouse in Pygame." }, { "code": null, "e": 25711, "s": 25658, "text": "Step 1: First, import the libraries Pygame and math." }, { "code": null, "e": 25765, "s": 25711, "text": "import pygame\nimport math\nfrom pygame.locals import *" }, { "code": null, "e": 25836, "s": 25765, "text": "Step 2: Now, take the colors as input that we want to use in the game." }, { "code": null, "e": 25932, "s": 25836, "text": "color_1 = #RGB value of color 1\ncolor_2 = #RGB value of color 2\ncolor_n = #RGB value of color n" }, { "code": null, "e": 25973, "s": 25932, "text": "Step 3: Then, initialize the constructor" }, { "code": null, "e": 25987, "s": 25973, "text": "pygame.init()" }, { "code": null, "e": 26032, "s": 25987, "text": "Step 4: Set the dimensions of your GUI game." }, { "code": null, "e": 26116, "s": 26032, "text": "w, h = #Width dimension, #Height dimension\nscreen = pygame.display.set_mode((w, h))" }, { "code": null, "e": 26204, "s": 26116, "text": "Step 5: Set the running value for running the game, the angle by which it can be moved." }, { "code": null, "e": 26239, "s": 26204, "text": "running = True\nangle = 0\nscale = 1" }, { "code": null, "e": 26314, "s": 26239, "text": "Step 6: Next, take the image as input which we want to move with the mouse" }, { "code": null, "e": 26386, "s": 26314, "text": "img_logo = pygame.image.load('#Enter the image url')\nimg_logo.convert()" }, { "code": null, "e": 26425, "s": 26386, "text": "Step 7: Draw a border around an image." }, { "code": null, "e": 26507, "s": 26425, "text": "rect_logo = img_logo.get_rect()\npygame.draw.rect(img_logo, color_1, rect_logo, 1)" }, { "code": null, "e": 26584, "s": 26507, "text": "Step 8: Locate the center of the GUI game and get the position of the mouse." }, { "code": null, "e": 26635, "s": 26584, "text": "center = w//2, h//2\nmouse = pygame.mouse.get_pos()" }, { "code": null, "e": 26721, "s": 26635, "text": "Step 9: Store the image in a new variable and construct a rectangle around the image." }, { "code": null, "e": 26779, "s": 26721, "text": "img = img_logo\nrect = img.get_rect()\nrect.center = center" }, { "code": null, "e": 26856, "s": 26779, "text": "Step 10: Set the things which you want your app to do when in running state." }, { "code": null, "e": 26908, "s": 26856, "text": "while running:\n for event in pygame.event.get():" }, { "code": null, "e": 26995, "s": 26908, "text": "Step 10.1: Once the app is in a running state, make it quit if the user wants to quit." }, { "code": null, "e": 27054, "s": 26995, "text": " if event.type == QUIT:\n running = False" }, { "code": null, "e": 27148, "s": 27054, "text": "Step 10.2: In case, the user doesn’t want to quit, set at what angle the image should rotate." }, { "code": null, "e": 27490, "s": 27148, "text": " if event.type == KEYDOWN:\n if event.key == K_ra:\n if event.mod & KMOD_SHIFT:\n \n # angle at which it should move left\n angle -= \n else:\n \n # angle at which it should move right\n angle += " }, { "code": null, "e": 27569, "s": 27490, "text": "Step 10.3: Also, set at what ratio the image size should decrease or increase." }, { "code": null, "e": 27822, "s": 27569, "text": " elif event.key == K_sa:\n if event.mod & KMOD_SHIFT:\n scale /= #scale at which the image size should decrease\n else:\n scale *= #scale at which the image size should increase" }, { "code": null, "e": 27908, "s": 27822, "text": "Step 10.4: Set at what coordinates, angle, and scale the image will rotate or resize." }, { "code": null, "e": 27948, "s": 27908, "text": " elif event.type == MOUSEMOTION:" }, { "code": null, "e": 28022, "s": 27948, "text": "Step 10.4.1: Store the current position of the event in the new variable." }, { "code": null, "e": 28052, "s": 28022, "text": " mouse = event.pos" }, { "code": null, "e": 28183, "s": 28052, "text": "Step 10.4.2: Locate the Cartesian coordinates with the help of the mouse variable and center of the image for rotating the image.." }, { "code": null, "e": 28257, "s": 28183, "text": " x = mouse[0] - center[0]\n y = mouse[1] - center[1]" }, { "code": null, "e": 28376, "s": 28257, "text": "Step 10.4.3: Further, calculate the distance between the two points (0,0) and (x, y) with the help of formula √x2+y2 " }, { "code": null, "e": 28419, "s": 28376, "text": " d = math.sqrt(x ** 2 + y ** 2)" }, { "code": null, "e": 28587, "s": 28419, "text": "Step 10.4.4: Now, calculate the angle in degrees at which the image should rotate using the Python method math.atan2() which returns the arctangent of y/x, in radians." }, { "code": null, "e": 28639, "s": 28587, "text": " angle = math.degrees(-math.atan2(y, x))" }, { "code": null, "e": 28784, "s": 28639, "text": "Step 10.4.5: Calculate which scale the image size should decrease or increase using the function abs, which returns the magnitude of the number." }, { "code": null, "e": 28819, "s": 28784, "text": " scale = abs(5 * d / w)" }, { "code": null, "e": 28975, "s": 28819, "text": "Step 10.4.6: Calculate the updated position of the image in the running state using the rotozoom function which is a combined scale and rotation transform." }, { "code": null, "e": 29043, "s": 28975, "text": " img = pygame.transform.rotozoom(img_logo, angle, scale)" }, { "code": null, "e": 29105, "s": 29043, "text": "Step 10.4.7: Construct the rectangle around the updated image" }, { "code": null, "e": 29172, "s": 29105, "text": " rect = img.get_rect()\n rect.center = center" }, { "code": null, "e": 29249, "s": 29172, "text": "Step 11: Next, you need to set the screen color and the image on the screen." }, { "code": null, "e": 29301, "s": 29249, "text": " screen.fill(color_3)\n screen.blit(img, rect)" }, { "code": null, "e": 29396, "s": 29301, "text": "Step 12: Later on, draw the rectangle, line, and circles which will help in moving the image." }, { "code": null, "e": 29729, "s": 29396, "text": " pygame.draw.rect(screen, color_2, rect, #thickness of rectangle)\n pygame.draw.line(screen, color_3, center, mouse, #Thickness of line)\n pygame.draw.circle(screen, color_1, center, #radius of circle, #thickness of circumference)\n pygame.draw.circle(screen, color_2, mouse, #radius of circle, #thickness of circumference)" }, { "code": null, "e": 29792, "s": 29729, "text": "Step 13: Furthermore, update the changes done in the GUI game." }, { "code": null, "e": 29818, "s": 29792, "text": " pygame.display.update()" }, { "code": null, "e": 29855, "s": 29818, "text": "Step 14: Finally, quit the GUI game." }, { "code": null, "e": 29869, "s": 29855, "text": "pygame.quit()" }, { "code": null, "e": 29898, "s": 29869, "text": "Below is the implementation." }, { "code": null, "e": 29905, "s": 29898, "text": "Python" }, { "code": "# Python program to transform the # image with the mouse #Import the libraries pygame and mathimport pygameimport mathfrom pygame.locals import * # Take colors inputRED = (255, 0, 0)BLACK = (0, 0, 0)YELLOW = (255, 255, 0) #Construct the GUI gamepygame.init() #Set dimensions of game GUIw, h = 600, 440screen = pygame.display.set_mode((w, h)) # Set running, angle and scale valuesrunning = Trueangle = 0scale = 1 # Take image as inputimg_logo = pygame.image.load('gfg_image.jpg')img_logo.convert() # Draw a rectangle around the imagerect_logo = img_logo.get_rect()pygame.draw.rect(img_logo, RED, rect_logo, 1) # Set the center and mouse positioncenter = w//2, h//2mouse = pygame.mouse.get_pos() #Store the image in a new variable#Construct the rectangle around imageimg = img_logorect = img.get_rect()rect.center = center # Setting what happens when game is# in running statewhile running: for event in pygame.event.get(): # Close if the user quits the game if event.type == QUIT: running = False # Set at which angle the image will # move left or right if event.type == KEYDOWN: if event.key == K_ra: if event.mod & KMOD_SHIFT: angle -= 5 else: angle += 5 # Set at what ratio the image will # decrease or increase elif event.key == K_sa: if event.mod & KMOD_SHIFT: scale /= 1.5 else: scale *= 1.5 # Move the image with the specified coordinates, # angle and scale elif event.type == MOUSEMOTION: mouse = event.pos x = mouse[0] - center[0] y = mouse[1] - center[1] d = math.sqrt(x ** 2 + y ** 2) angle = math.degrees(-math.atan2(y, x)) scale = abs(5 * d / w) img = pygame.transform.rotozoom(img_logo, angle, scale) rect = img.get_rect() rect.center = center # Set screen color and image on screen screen.fill(YELLOW) screen.blit(img, rect) # Draw the rectangle, line and circle through # which image can be transformed pygame.draw.rect(screen, BLACK, rect, 3) pygame.draw.line(screen, RED, center, mouse, 2) pygame.draw.circle(screen, RED, center, 6, 1) pygame.draw.circle(screen, BLACK, mouse, 6, 2) # Update the GUI game pygame.display.update() # Quit the GUI gamepygame.quit()", "e": 32424, "s": 29905, "text": null }, { "code": null, "e": 32432, "s": 32424, "text": "Output:" }, { "code": null, "e": 32439, "s": 32432, "text": "Picked" }, { "code": null, "e": 32453, "s": 32439, "text": "Python-PyGame" }, { "code": null, "e": 32460, "s": 32453, "text": "Python" }, { "code": null, "e": 32558, "s": 32460, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32590, "s": 32558, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 32632, "s": 32590, "text": "Check if element exists in list in Python" }, { "code": null, "e": 32674, "s": 32632, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 32701, "s": 32674, "text": "Python Classes and Objects" }, { "code": null, "e": 32757, "s": 32701, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 32779, "s": 32757, "text": "Defaultdict in Python" }, { "code": null, "e": 32818, "s": 32779, "text": "Python | Get unique values from a list" }, { "code": null, "e": 32849, "s": 32818, "text": "Python | os.path.join() method" }, { "code": null, "e": 32878, "s": 32849, "text": "Create a directory in Python" } ]