title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Steps to Create and Publish NPM packages
27 Jan, 2020 In this article, we will learn how to develop and publish your own npm package (also called an NPM module). There are many benefits of NPM packages, some of them are listed below: Reusable code Managing code (using versioning) Sharing code The life-cycle of an npm package takes place like below: Module Life-cycle 1. Setup a Project: Setting up a project is required before doing anything. Install Node.js Create an npm account.npm-signup npm-signup Logging in to the npm account using npm loginnpm-login npm-login 2. Initializing a module: To initialize a module, Go to the terminal/command-line and type npm init and answer the prompts. npm-init In the version prompt, set it to 0.0.0. It initializes the module. If you keep it 1.0.0, it means that the current module version is the first major release to the potential downloaders. Of course, you don’t want the first major release to be only a blank slate and full of bugs. In the main prompt, choose the entry point of the module. Potential downloaders will use it as the entry point to the module. Note that the entry point is ‘src/index.js’ which is considered as a standard practice these days to put your code in a ‘src’ directory. In the test command prompt, simply press Enter. In the photograph above, it has been edited out because of some typo mistake. You can change your test command from the eventually forming package.json file as well. In the git repository prompt, you can fill the url of the git repository where the package will be hosted. Fill the keywords, author, license or you can press ‘Enter’ your way through them. These can be later modified in the package.json. Include a README.md file in the project for potential downloaders to see. This will appear in the homepage of your module. Note that, the file should be a markdown.A README.md should be added to an npm module so that potential users for the purposes of serving them with information like module description, how to use the package, how to contribute to package, etc. Ultimately, it is desirable if our project directory looks something like: project-directory-structure 3. Building a module: This phase is the coding phase. If you have any experience of using NPM modules, you would know that NPM modules expose methods that are then used by the project. A typical control-flow is: Function-call-workflow-that-present-in-npm-module Lets first implement a simple function that add two numbers in the npm module. This function looks like below: File Name: index.js const gfgFns = { add : function addTwoNums( num1, num2 ) { return (num1 + num2) ; }} module.exports = gfgFns Note that, the structure of index.js file (which is the entry point of npm module that we are building). const gfgFns = {} The object that is exported for others to use. add: function addTwoNums() The function name (addTwoNums) is marked by ‘add’. This ‘add’ name is used to call this function to add two numbers. module.exports = gfgFns The gfgFns object is then exported with this name. When this function needs to be used in some other file. 4. Publishing a module: After completion of coding module, publish the npm package. To publish the package, there is one thing to keep in mind: if your package name already exists in the npm registry, you won’t be able to publish your package. To check if your package name is usable or not, go to the command-line and type npm search packagename If your package name is usable, it should show something like in the image below. npm-search-gfgnpmpkgupload-cmd-1 If your module name already exists, go to the package.json file of the npm module project and change the module name to something else. Now after checking the name availability, go to command-line/terminal and do the following: npm publish npm-publish-cmd Now, lets try to use this module and see if it works. Make a fresh project directory. In the terminal, type npm init to initialize the Node project. Now do npm install gfgnpmpkgupload to download the npm module that we just made.appjs-npmpkgupload-directory-add_function appjs-npmpkgupload-directory-add_function Now everything is set, lets try to run node.js file and see if our module is correctly uploaded, published, imported in our new project, and used.node-appjs-add(4+5=9)-run-success-11 node-appjs-add(4+5=9)-run-success-11 5. Updating and managing versions: If a software is being developed, it is obvious that it has versions. Versions are a result of bug fixes, minor improvement, major improvements and major releases. To cater to versioning, NPM provides us with the following functionality. Versioning and publishing code: NPM allows us to version our module on the basis of semantic-versioning. There are three types of version bumps that we can do, ie, patch, minor, and major. For example, if the current module version is 0.4.5: # note how minor version upgrade resets patch version to 0, similarly, # major version upgrade sets minor and patch #to 0. > npm version patch # update version to 0.4.6 > npm version minor # update version to 0.5.0 > npm version major # update version to 1.0.0 When we run the above command, the version number in the package.json file is automatically updated as well. Note: If the module is being re-published without bumping up the version, NPM command-line will throw an error. For example, look the below image. npm publish abort due to unchanged version number Here, the command-line threw an error because an ‘npm publish’ was attempted without bumping up the version.An obvious note: You can’t bump-down the version. For example, the version can’t change from 0.1.2 to 0.1.1 . What happens when user has older version of the module ? When an npm module is re-published (updated), the users just have to run ‘npm install gfgnpmpkgupload’ (npm install packagename) again to get the latest version. A package dependent on other packages: In the journey of developing packages, it is common to search, use and see dependencies. Doing this takes place like something below: In the npm module project, install the dependencies that are required by your npm module. Install those dependencies to your project usingnpm install packagename1[ packagename2] npm install packagename1[ packagename2] Check that these dependencies are now mentioned in the 'dependencies' key in the package.json file. Note that the dependencies and their version mentioned here will be carried on forward with the npm package. After assuring that all the above steps are rightly executed, simply publish the module using > npm version minor npm publish .Above procedure should execute successfully, and the result should be available to see in the npm registry website like below:three-dependencies-prompt-jest-mathsjs > npm version minor npm publish .Above procedure should execute successfully, and the result should be available to see in the npm registry website like below: three-dependencies-prompt-jest-mathsjs Building a more complex module: Lets try to build a module that reads a txt file, extract numbers from the file, adds them all and display the result in a console.To do this, our npm module should be this.Now, we have our module set, lets import it into our new project using npm install gfgnpmpkgupload Before running the above command, do run npm init -y to set up the project. Make your project like below: npmpkguploadtest project structure The datafiles should contain a numFile.txt that has the numbers that have to be added and displayed in console. // numFile.txt - sum = 55 1 2 3 4 5 6 7 8 9 10 To consume this numFile.txt, we will have a gfgapp.js that will do the actual addition. npmpkguploadtest-gfgappjs To test this, go to command-line and run node gfgapp.js node gfgappjs commandline view run success NPM module boilerplate: NPM module boilerplates are also available for project scaffolding on yeoman.io . Various combinations of technologies are available and you can use the generator that you like. To start, go to Yeoman Generator Search and search for something like 'npm module boilerplate'. Unpublishing an NPM package: An NPM package should be taken down within 72 hours of the initial publish. The other way is to contact the npm registry. If you are unpublishing within 72 hours, use the following command: npm unpublish packageName NPM's unpublishing packages from the registry is a good page to go through to learn more about this. Example: Use the published package to add two numbers.Filename: app.js const GFGFns = require('gfgnpmpkgupload');console.log(GFGFns.add(4, 5)); Output: node-appjs-add459-run-success-1 Node.js-Basics Node.js-Misc Technical Scripter 2019 JavaScript Node.js Technical Scripter Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Jan, 2020" }, { "code": null, "e": 160, "s": 52, "text": "In this article, we will learn how to develop and publish your own npm package (also called an NPM module)." }, { "code": null, "e": 232, "s": 160, "text": "There are many benefits of NPM packages, some of them are listed below:" }, { "code": null, "e": 246, "s": 232, "text": "Reusable code" }, { "code": null, "e": 279, "s": 246, "text": "Managing code (using versioning)" }, { "code": null, "e": 292, "s": 279, "text": "Sharing code" }, { "code": null, "e": 349, "s": 292, "text": "The life-cycle of an npm package takes place like below:" }, { "code": null, "e": 367, "s": 349, "text": "Module Life-cycle" }, { "code": null, "e": 443, "s": 367, "text": "1. Setup a Project: Setting up a project is required before doing anything." }, { "code": null, "e": 459, "s": 443, "text": "Install Node.js" }, { "code": null, "e": 492, "s": 459, "text": "Create an npm account.npm-signup" }, { "code": null, "e": 503, "s": 492, "text": "npm-signup" }, { "code": null, "e": 558, "s": 503, "text": "Logging in to the npm account using npm loginnpm-login" }, { "code": null, "e": 568, "s": 558, "text": "npm-login" }, { "code": null, "e": 692, "s": 568, "text": "2. Initializing a module: To initialize a module, Go to the terminal/command-line and type npm init and answer the prompts." }, { "code": null, "e": 701, "s": 692, "text": "npm-init" }, { "code": null, "e": 981, "s": 701, "text": "In the version prompt, set it to 0.0.0. It initializes the module. If you keep it 1.0.0, it means that the current module version is the first major release to the potential downloaders. Of course, you don’t want the first major release to be only a blank slate and full of bugs." }, { "code": null, "e": 1244, "s": 981, "text": "In the main prompt, choose the entry point of the module. Potential downloaders will use it as the entry point to the module. Note that the entry point is ‘src/index.js’ which is considered as a standard practice these days to put your code in a ‘src’ directory." }, { "code": null, "e": 1458, "s": 1244, "text": "In the test command prompt, simply press Enter. In the photograph above, it has been edited out because of some typo mistake. You can change your test command from the eventually forming package.json file as well." }, { "code": null, "e": 1565, "s": 1458, "text": "In the git repository prompt, you can fill the url of the git repository where the package will be hosted." }, { "code": null, "e": 1697, "s": 1565, "text": "Fill the keywords, author, license or you can press ‘Enter’ your way through them. These can be later modified in the package.json." }, { "code": null, "e": 2064, "s": 1697, "text": "Include a README.md file in the project for potential downloaders to see. This will appear in the homepage of your module. Note that, the file should be a markdown.A README.md should be added to an npm module so that potential users for the purposes of serving them with information like module description, how to use the package, how to contribute to package, etc." }, { "code": null, "e": 2139, "s": 2064, "text": "Ultimately, it is desirable if our project directory looks something like:" }, { "code": null, "e": 2167, "s": 2139, "text": "project-directory-structure" }, { "code": null, "e": 2379, "s": 2167, "text": "3. Building a module: This phase is the coding phase. If you have any experience of using NPM modules, you would know that NPM modules expose methods that are then used by the project. A typical control-flow is:" }, { "code": null, "e": 2429, "s": 2379, "text": "Function-call-workflow-that-present-in-npm-module" }, { "code": null, "e": 2540, "s": 2429, "text": "Lets first implement a simple function that add two numbers in the npm module. This function looks like below:" }, { "code": null, "e": 2560, "s": 2540, "text": "File Name: index.js" }, { "code": "const gfgFns = { add : function addTwoNums( num1, num2 ) { return (num1 + num2) ; }} module.exports = gfgFns", "e": 2675, "s": 2560, "text": null }, { "code": null, "e": 2780, "s": 2675, "text": "Note that, the structure of index.js file (which is the entry point of npm module that we are building)." }, { "code": null, "e": 2845, "s": 2780, "text": "const gfgFns = {} The object that is exported for others to use." }, { "code": null, "e": 2989, "s": 2845, "text": "add: function addTwoNums() The function name (addTwoNums) is marked by ‘add’. This ‘add’ name is used to call this function to add two numbers." }, { "code": null, "e": 3120, "s": 2989, "text": "module.exports = gfgFns The gfgFns object is then exported with this name. When this function needs to be used in some other file." }, { "code": null, "e": 3444, "s": 3120, "text": "4. Publishing a module: After completion of coding module, publish the npm package. To publish the package, there is one thing to keep in mind: if your package name already exists in the npm registry, you won’t be able to publish your package. To check if your package name is usable or not, go to the command-line and type" }, { "code": null, "e": 3467, "s": 3444, "text": "npm search packagename" }, { "code": null, "e": 3549, "s": 3467, "text": "If your package name is usable, it should show something like in the image below." }, { "code": null, "e": 3582, "s": 3549, "text": "npm-search-gfgnpmpkgupload-cmd-1" }, { "code": null, "e": 3718, "s": 3582, "text": "If your module name already exists, go to the package.json file of the npm module project and change the module name to something else." }, { "code": null, "e": 3810, "s": 3718, "text": "Now after checking the name availability, go to command-line/terminal and do the following:" }, { "code": null, "e": 3822, "s": 3810, "text": "npm publish" }, { "code": null, "e": 3838, "s": 3822, "text": "npm-publish-cmd" }, { "code": null, "e": 3892, "s": 3838, "text": "Now, lets try to use this module and see if it works." }, { "code": null, "e": 3924, "s": 3892, "text": "Make a fresh project directory." }, { "code": null, "e": 3987, "s": 3924, "text": "In the terminal, type npm init to initialize the Node project." }, { "code": null, "e": 4109, "s": 3987, "text": "Now do npm install gfgnpmpkgupload to download the npm module that we just made.appjs-npmpkgupload-directory-add_function" }, { "code": null, "e": 4151, "s": 4109, "text": "appjs-npmpkgupload-directory-add_function" }, { "code": null, "e": 4334, "s": 4151, "text": "Now everything is set, lets try to run node.js file and see if our module is correctly uploaded, published, imported in our new project, and used.node-appjs-add(4+5=9)-run-success-11" }, { "code": null, "e": 4371, "s": 4334, "text": "node-appjs-add(4+5=9)-run-success-11" }, { "code": null, "e": 4644, "s": 4371, "text": "5. Updating and managing versions: If a software is being developed, it is obvious that it has versions. Versions are a result of bug fixes, minor improvement, major improvements and major releases. To cater to versioning, NPM provides us with the following functionality." }, { "code": null, "e": 4886, "s": 4644, "text": "Versioning and publishing code: NPM allows us to version our module on the basis of semantic-versioning. There are three types of version bumps that we can do, ie, patch, minor, and major. For example, if the current module version is 0.4.5:" }, { "code": null, "e": 5151, "s": 4886, "text": "# note how minor version upgrade resets patch version to 0, similarly,\n# major version upgrade sets minor and patch #to 0.\n> npm version patch # update version to 0.4.6\n> npm version minor # update version to 0.5.0\n> npm version major # update version to 1.0.0\n" }, { "code": null, "e": 5260, "s": 5151, "text": "When we run the above command, the version number in the package.json file is automatically updated as well." }, { "code": null, "e": 5407, "s": 5260, "text": "Note: If the module is being re-published without bumping up the version, NPM command-line will throw an error. For example, look the below image." }, { "code": null, "e": 5457, "s": 5407, "text": "npm publish abort due to unchanged version number" }, { "code": null, "e": 5675, "s": 5457, "text": "Here, the command-line threw an error because an ‘npm publish’ was attempted without bumping up the version.An obvious note: You can’t bump-down the version. For example, the version can’t change from 0.1.2 to 0.1.1 ." }, { "code": null, "e": 5894, "s": 5675, "text": "What happens when user has older version of the module ? When an npm module is re-published (updated), the users just have to run ‘npm install gfgnpmpkgupload’ (npm install packagename) again to get the latest version." }, { "code": null, "e": 6067, "s": 5894, "text": "A package dependent on other packages: In the journey of developing packages, it is common to search, use and see dependencies. Doing this takes place like something below:" }, { "code": null, "e": 6157, "s": 6067, "text": "In the npm module project, install the dependencies that are required by your npm module." }, { "code": null, "e": 6245, "s": 6157, "text": "Install those dependencies to your project usingnpm install packagename1[ packagename2]" }, { "code": null, "e": 6285, "s": 6245, "text": "npm install packagename1[ packagename2]" }, { "code": null, "e": 6494, "s": 6285, "text": "Check that these dependencies are now mentioned in the 'dependencies' key in the package.json file. Note that the dependencies and their version mentioned here will be carried on forward with the npm package." }, { "code": null, "e": 6786, "s": 6494, "text": "After assuring that all the above steps are rightly executed, simply publish the module using > npm version minor\nnpm publish\n.Above procedure should execute successfully, and the result should be available to see in the npm registry website like below:three-dependencies-prompt-jest-mathsjs" }, { "code": null, "e": 6819, "s": 6786, "text": "> npm version minor\nnpm publish\n" }, { "code": null, "e": 6947, "s": 6819, "text": ".Above procedure should execute successfully, and the result should be available to see in the npm registry website like below:" }, { "code": null, "e": 6986, "s": 6947, "text": "three-dependencies-prompt-jest-mathsjs" }, { "code": null, "e": 7262, "s": 6986, "text": "Building a more complex module: Lets try to build a module that reads a txt file, extract numbers from the file, adds them all and display the result in a console.To do this, our npm module should be this.Now, we have our module set, lets import it into our new project using" }, { "code": null, "e": 7290, "s": 7262, "text": "npm install gfgnpmpkgupload" }, { "code": null, "e": 7331, "s": 7290, "text": "Before running the above command, do run" }, { "code": null, "e": 7343, "s": 7331, "text": "npm init -y" }, { "code": null, "e": 7366, "s": 7343, "text": "to set up the project." }, { "code": null, "e": 7396, "s": 7366, "text": "Make your project like below:" }, { "code": null, "e": 7431, "s": 7396, "text": "npmpkguploadtest project structure" }, { "code": null, "e": 7543, "s": 7431, "text": "The datafiles should contain a numFile.txt that has the numbers that have to be added and displayed in console." }, { "code": null, "e": 7591, "s": 7543, "text": "// numFile.txt - sum = 55\n1 2 3 4 5 6 7 8 9 10\n" }, { "code": null, "e": 7679, "s": 7591, "text": "To consume this numFile.txt, we will have a gfgapp.js that will do the actual addition." }, { "code": null, "e": 7705, "s": 7679, "text": "npmpkguploadtest-gfgappjs" }, { "code": null, "e": 7746, "s": 7705, "text": "To test this, go to command-line and run" }, { "code": null, "e": 7761, "s": 7746, "text": "node gfgapp.js" }, { "code": null, "e": 7804, "s": 7761, "text": "node gfgappjs commandline view run success" }, { "code": null, "e": 8102, "s": 7804, "text": "NPM module boilerplate: NPM module boilerplates are also available for project scaffolding on yeoman.io . Various combinations of technologies are available and you can use the generator that you like. To start, go to Yeoman Generator Search and search for something like 'npm module boilerplate'." }, { "code": null, "e": 8321, "s": 8102, "text": "Unpublishing an NPM package: An NPM package should be taken down within 72 hours of the initial publish. The other way is to contact the npm registry. If you are unpublishing within 72 hours, use the following command:" }, { "code": null, "e": 8347, "s": 8321, "text": "npm unpublish packageName" }, { "code": null, "e": 8448, "s": 8347, "text": "NPM's unpublishing packages from the registry is a good page to go through to learn more about this." }, { "code": null, "e": 8519, "s": 8448, "text": "Example: Use the published package to add two numbers.Filename: app.js" }, { "code": "const GFGFns = require('gfgnpmpkgupload');console.log(GFGFns.add(4, 5));", "e": 8592, "s": 8519, "text": null }, { "code": null, "e": 8600, "s": 8592, "text": "Output:" }, { "code": null, "e": 8632, "s": 8600, "text": "node-appjs-add459-run-success-1" }, { "code": null, "e": 8647, "s": 8632, "text": "Node.js-Basics" }, { "code": null, "e": 8660, "s": 8647, "text": "Node.js-Misc" }, { "code": null, "e": 8684, "s": 8660, "text": "Technical Scripter 2019" }, { "code": null, "e": 8695, "s": 8684, "text": "JavaScript" }, { "code": null, "e": 8703, "s": 8695, "text": "Node.js" }, { "code": null, "e": 8722, "s": 8703, "text": "Technical Scripter" }, { "code": null, "e": 8739, "s": 8722, "text": "Web Technologies" }, { "code": null, "e": 8766, "s": 8739, "text": "Web technologies Questions" } ]
Pure Virtual Destructor in C++
02 Jun, 2022 A pure virtual destructor can be declared in C++. After a destructor has been created as a pure virtual object(instance of a class), where the destructor body is provided. This is due to the fact that destructors will not be overridden in derived classes, but will instead be called in reverse order. As a result, for a pure virtual destructor, you must specify a destructor body. When destroying instances of a derived class using a base class pointer object, a virtual destructor is used to free up memory space allocated by the derived class object or instance. Note: Only Destructors can be Virtual. Constructors cannot be declared as virtual, this is because if you try to override a constructor by declaring it in a base/super class and call it in the derived/sub class with same functionalities it will always give an error as overriding means a feature that lets us to use a method from the parent class in the child class which is not possible. Can a destructor be pure virtual in C++? Yes, it is possible to have a pure virtual destructor. Pure virtual destructors are legal in standard C++ and one of the most important things to remember is that if a class contains a pure virtual destructor, it must provide a function body for the pure virtual destructor. Why a pure virtual function requires a function body? The reason is that destructors (unlike other functions) are not actually ‘overridden’, rather they are always called in the reverse order of the class derivation. This means that a derived class destructor will be invoked first, then the base class destructor will be called. If the definition of the pure virtual destructor is not provided, then what function body will be called during object destruction? Therefore the compiler and linker enforce the existence of a function body for pure virtual destructors. Example: CPP // C++ Program to demonstrate a pure virtual destructor#include <iostream>using namespace std; // Initialization of base classclass Base {public: virtual ~Base() = 0; // Pure virtual destructor}; // Initialization of derived classclass Derived : public Base {public: ~Derived() { cout << "~Derived() is executed"; }}; // Driver Codeint main(){ // base class pointer which is // allocating fresh storage // for Derived function object's Base* b = new Derived(); delete b; return 0;} The linker will produce the following error in the above program. test.cpp:(.text$_ZN7DerivedD1Ev[__ZN7DerivedD1Ev]+0x4c): undefined reference to `Base::~Base()' error: ld returned 1 exit status Now if the definition for the pure virtual destructor is provided, then the program compiles & runs fine. CPP // C++ program to demonstrate if the value of// of pure virtual destructor are provided// then the program compiles & runs fine. #include <iostream> // Initialization of base classclass Base {public: virtual ~Base() = 0; // Pure virtual destructor};Base::~Base() // Explicit destructor call{ std::cout << "Pure virtual destructor is called";} // Initialization of derived classclass Derived : public Base {public: ~Derived() { std::cout << "~Derived() is executed\n"; }}; int main(){ // Calling of derived member function Base* b = new Derived(); delete b; return 0;} ~Derived() is executed Pure virtual destructor is called How did the above code work MAGICALLY? This basically works because the destructors will be called recursively bottom to up if and only if the value is passed in the virtual destructor. So vtable is a table containing pointers of all virtual functions that the class defines, and the compiler provides vptr to the class as a ‘hidden pointer‘ that points to the ideal vtable, so the compiler makes use of an accurate or correct index, calculated at compile-time, to the vtable which will dispatch the correct virtual function at runtime. It is important to note that a class becomes an abstract class(at least a function that has no definition) when it contains a pure virtual destructor. Example: CPP // C++ program to demonstrate how a class becomes// an abstract class when a pure virtual destructor is// passed #include <iostream>class Test {public: virtual ~Test() = 0; // Test now becomes abstract class};Test::~Test() {} // Driver Codeint main(){ Test p; Test* t1 = new Test; return 0;} The above program fails in a compilation & shows the following error messages. [Error] cannot declare variable 'p' to be of abstract type 'Test' [Note] because the following virtual functions are pure within 'Test': [Note] virtual Test::~Test() [Error] cannot allocate an object of abstract type 'Test' [Note] since type 'Test' has pure virtual functions This article was contributed by Meet Pravasi. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. abrahammurciano anshikajain26 harsh_shokeen sagartomar9927 simmytarika5 surinderdawra388 cpp-constructor cpp-virtual C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n02 Jun, 2022" }, { "code": null, "e": 435, "s": 54, "text": "A pure virtual destructor can be declared in C++. After a destructor has been created as a pure virtual object(instance of a class), where the destructor body is provided. This is due to the fact that destructors will not be overridden in derived classes, but will instead be called in reverse order. As a result, for a pure virtual destructor, you must specify a destructor body." }, { "code": null, "e": 620, "s": 435, "text": "When destroying instances of a derived class using a base class pointer object, a virtual destructor is used to free up memory space allocated by the derived class object or instance. " }, { "code": null, "e": 1010, "s": 620, "text": "Note: Only Destructors can be Virtual. Constructors cannot be declared as virtual, this is because if you try to override a constructor by declaring it in a base/super class and call it in the derived/sub class with same functionalities it will always give an error as overriding means a feature that lets us to use a method from the parent class in the child class which is not possible. " }, { "code": null, "e": 1327, "s": 1010, "text": "Can a destructor be pure virtual in C++? Yes, it is possible to have a pure virtual destructor. Pure virtual destructors are legal in standard C++ and one of the most important things to remember is that if a class contains a pure virtual destructor, it must provide a function body for the pure virtual destructor. " }, { "code": null, "e": 1381, "s": 1327, "text": "Why a pure virtual function requires a function body?" }, { "code": null, "e": 1904, "s": 1381, "text": "The reason is that destructors (unlike other functions) are not actually ‘overridden’, rather they are always called in the reverse order of the class derivation. This means that a derived class destructor will be invoked first, then the base class destructor will be called. If the definition of the pure virtual destructor is not provided, then what function body will be called during object destruction? Therefore the compiler and linker enforce the existence of a function body for pure virtual destructors. Example:" }, { "code": null, "e": 1908, "s": 1904, "text": "CPP" }, { "code": "// C++ Program to demonstrate a pure virtual destructor#include <iostream>using namespace std; // Initialization of base classclass Base {public: virtual ~Base() = 0; // Pure virtual destructor}; // Initialization of derived classclass Derived : public Base {public: ~Derived() { cout << \"~Derived() is executed\"; }}; // Driver Codeint main(){ // base class pointer which is // allocating fresh storage // for Derived function object's Base* b = new Derived(); delete b; return 0;}", "e": 2417, "s": 1908, "text": null }, { "code": null, "e": 2484, "s": 2417, "text": "The linker will produce the following error in the above program. " }, { "code": null, "e": 2615, "s": 2484, "text": "test.cpp:(.text$_ZN7DerivedD1Ev[__ZN7DerivedD1Ev]+0x4c): \nundefined reference to `Base::~Base()' error: ld returned 1 exit status" }, { "code": null, "e": 2721, "s": 2615, "text": "Now if the definition for the pure virtual destructor is provided, then the program compiles & runs fine." }, { "code": null, "e": 2725, "s": 2721, "text": "CPP" }, { "code": "// C++ program to demonstrate if the value of// of pure virtual destructor are provided// then the program compiles & runs fine. #include <iostream> // Initialization of base classclass Base {public: virtual ~Base() = 0; // Pure virtual destructor};Base::~Base() // Explicit destructor call{ std::cout << \"Pure virtual destructor is called\";} // Initialization of derived classclass Derived : public Base {public: ~Derived() { std::cout << \"~Derived() is executed\\n\"; }}; int main(){ // Calling of derived member function Base* b = new Derived(); delete b; return 0;}", "e": 3314, "s": 2725, "text": null }, { "code": null, "e": 3371, "s": 3314, "text": "~Derived() is executed\nPure virtual destructor is called" }, { "code": null, "e": 3410, "s": 3371, "text": "How did the above code work MAGICALLY?" }, { "code": null, "e": 3908, "s": 3410, "text": "This basically works because the destructors will be called recursively bottom to up if and only if the value is passed in the virtual destructor. So vtable is a table containing pointers of all virtual functions that the class defines, and the compiler provides vptr to the class as a ‘hidden pointer‘ that points to the ideal vtable, so the compiler makes use of an accurate or correct index, calculated at compile-time, to the vtable which will dispatch the correct virtual function at runtime." }, { "code": null, "e": 4059, "s": 3908, "text": "It is important to note that a class becomes an abstract class(at least a function that has no definition) when it contains a pure virtual destructor." }, { "code": null, "e": 4068, "s": 4059, "text": "Example:" }, { "code": null, "e": 4072, "s": 4068, "text": "CPP" }, { "code": "// C++ program to demonstrate how a class becomes// an abstract class when a pure virtual destructor is// passed #include <iostream>class Test {public: virtual ~Test() = 0; // Test now becomes abstract class};Test::~Test() {} // Driver Codeint main(){ Test p; Test* t1 = new Test; return 0;}", "e": 4379, "s": 4072, "text": null }, { "code": null, "e": 4459, "s": 4379, "text": "The above program fails in a compilation & shows the following error messages. " }, { "code": null, "e": 4739, "s": 4459, "text": "[Error] cannot declare variable 'p' to be of abstract type 'Test' \n[Note] because the following virtual functions are pure within 'Test': \n[Note] virtual Test::~Test() \n[Error] cannot allocate an object of abstract type 'Test' \n[Note] since type 'Test' has pure virtual functions" }, { "code": null, "e": 4913, "s": 4739, "text": "This article was contributed by Meet Pravasi. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above." }, { "code": null, "e": 4929, "s": 4913, "text": "abrahammurciano" }, { "code": null, "e": 4943, "s": 4929, "text": "anshikajain26" }, { "code": null, "e": 4957, "s": 4943, "text": "harsh_shokeen" }, { "code": null, "e": 4972, "s": 4957, "text": "sagartomar9927" }, { "code": null, "e": 4985, "s": 4972, "text": "simmytarika5" }, { "code": null, "e": 5002, "s": 4985, "text": "surinderdawra388" }, { "code": null, "e": 5018, "s": 5002, "text": "cpp-constructor" }, { "code": null, "e": 5030, "s": 5018, "text": "cpp-virtual" }, { "code": null, "e": 5041, "s": 5030, "text": "C Language" }, { "code": null, "e": 5045, "s": 5041, "text": "C++" }, { "code": null, "e": 5049, "s": 5045, "text": "CPP" } ]
Python – Catch All Exceptions
19 Oct, 2021 In this article, we will discuss how to catch all exceptions in Python using try, except statements with the help of proper examples. But before let’s see different types of errors in Python. There are generally two types of errors in Python i.e. Syntax error and Exceptions. Let’s see the difference between them. Syntax Error: As the name suggests this error is caused by the wrong syntax in the code. It leads to the termination of the program. Python3 # initialize the amount variableamount = 10000 # check that You are eligible to# purchase Dsa Self Paced or notif(amount > 2999)print("You are eligible to purchase Dsa Self Paced") Output: SyntaxError: invalid syntax Exceptions: Exceptions are raised when the program is syntactically correct, but the code resulted in an error. This error does not stop the execution of the program, however, it changes the normal flow of the program. Python3 # initialize the amount variablemarks = 10000 # perform division with 0a = marks / 0print(a) Output: ZeroDivisionError: division by zero Try and except statements are used to catch and handle exceptions in Python. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause. Python3 # Python program to handle simple runtime error a = [1, 2, 3]try: print ("Second element = %d" %(a[1])) # Throws error since there are only 3 # elements in array print ("Fourth element = %d" %(a[3])) except: print ("Error occurred") Second element = 2 An error occurred In the above example, the statements that can cause the error are placed inside the try statement (second print statement in our case). The second print statement tries to access the fourth element of the list which is not there and this throws an exception. This exception is then caught by the except statement. Without specifying any type of exception all the exceptions cause within the try block will be caught by the except block. We can also catch a specific exception. Let’s see how to do that. A try statement can have more than one except clause, to specify handlers for different exceptions. Please note that at most one handler will be executed. For example, we can add IndexError in the above code. The general syntax for adding specific exceptions are – try: # statement(s) except IndexError: # statement(s) except ValueError: # statement(s) Python3 # Program to handle multiple errors with one# except statement# Python 3 def fun(a): if a < 4: # throws ZeroDivisionError for a = 3 b = a/(a-3) # throws NameError if a >= 4 print("Value of b = ", b) try: fun(3) fun(5) # note that braces () are necessary here for# multiple exceptionsexcept ZeroDivisionError: print("ZeroDivisionError Occurred and Handled")except NameError: print("NameError Occurred and Handled") Output ZeroDivisionError Occurred and Handled If you comment the line fun(3), the output will be NameError Occurred and Handled The output above is so because as soon as python tries to access the value of b, NameError occurs. Note: For more information, refer to our Python Exception Handling Tutorial. Python-exceptions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Oct, 2021" }, { "code": null, "e": 220, "s": 28, "text": "In this article, we will discuss how to catch all exceptions in Python using try, except statements with the help of proper examples. But before let’s see different types of errors in Python." }, { "code": null, "e": 343, "s": 220, "text": "There are generally two types of errors in Python i.e. Syntax error and Exceptions. Let’s see the difference between them." }, { "code": null, "e": 476, "s": 343, "text": "Syntax Error: As the name suggests this error is caused by the wrong syntax in the code. It leads to the termination of the program." }, { "code": null, "e": 484, "s": 476, "text": "Python3" }, { "code": "# initialize the amount variableamount = 10000 # check that You are eligible to# purchase Dsa Self Paced or notif(amount > 2999)print(\"You are eligible to purchase Dsa Self Paced\")", "e": 666, "s": 484, "text": null }, { "code": null, "e": 674, "s": 666, "text": "Output:" }, { "code": null, "e": 702, "s": 674, "text": "SyntaxError: invalid syntax" }, { "code": null, "e": 921, "s": 702, "text": "Exceptions: Exceptions are raised when the program is syntactically correct, but the code resulted in an error. This error does not stop the execution of the program, however, it changes the normal flow of the program." }, { "code": null, "e": 929, "s": 921, "text": "Python3" }, { "code": "# initialize the amount variablemarks = 10000 # perform division with 0a = marks / 0print(a)", "e": 1023, "s": 929, "text": null }, { "code": null, "e": 1031, "s": 1023, "text": "Output:" }, { "code": null, "e": 1067, "s": 1031, "text": "ZeroDivisionError: division by zero" }, { "code": null, "e": 1291, "s": 1067, "text": "Try and except statements are used to catch and handle exceptions in Python. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause." }, { "code": null, "e": 1299, "s": 1291, "text": "Python3" }, { "code": "# Python program to handle simple runtime error a = [1, 2, 3]try: print (\"Second element = %d\" %(a[1])) # Throws error since there are only 3 # elements in array print (\"Fourth element = %d\" %(a[3])) except: print (\"Error occurred\")", "e": 1552, "s": 1299, "text": null }, { "code": null, "e": 1589, "s": 1552, "text": "Second element = 2\nAn error occurred" }, { "code": null, "e": 2092, "s": 1589, "text": "In the above example, the statements that can cause the error are placed inside the try statement (second print statement in our case). The second print statement tries to access the fourth element of the list which is not there and this throws an exception. This exception is then caught by the except statement. Without specifying any type of exception all the exceptions cause within the try block will be caught by the except block. We can also catch a specific exception. Let’s see how to do that." }, { "code": null, "e": 2357, "s": 2092, "text": "A try statement can have more than one except clause, to specify handlers for different exceptions. Please note that at most one handler will be executed. For example, we can add IndexError in the above code. The general syntax for adding specific exceptions are –" }, { "code": null, "e": 2454, "s": 2357, "text": "try:\n # statement(s)\nexcept IndexError:\n # statement(s)\nexcept ValueError:\n # statement(s)" }, { "code": null, "e": 2462, "s": 2454, "text": "Python3" }, { "code": "# Program to handle multiple errors with one# except statement# Python 3 def fun(a): if a < 4: # throws ZeroDivisionError for a = 3 b = a/(a-3) # throws NameError if a >= 4 print(\"Value of b = \", b) try: fun(3) fun(5) # note that braces () are necessary here for# multiple exceptionsexcept ZeroDivisionError: print(\"ZeroDivisionError Occurred and Handled\")except NameError: print(\"NameError Occurred and Handled\")", "e": 2922, "s": 2462, "text": null }, { "code": null, "e": 2929, "s": 2922, "text": "Output" }, { "code": null, "e": 2968, "s": 2929, "text": "ZeroDivisionError Occurred and Handled" }, { "code": null, "e": 3019, "s": 2968, "text": "If you comment the line fun(3), the output will be" }, { "code": null, "e": 3050, "s": 3019, "text": "NameError Occurred and Handled" }, { "code": null, "e": 3150, "s": 3050, "text": "The output above is so because as soon as python tries to access the value of b, NameError occurs. " }, { "code": null, "e": 3227, "s": 3150, "text": "Note: For more information, refer to our Python Exception Handling Tutorial." }, { "code": null, "e": 3245, "s": 3227, "text": "Python-exceptions" }, { "code": null, "e": 3252, "s": 3245, "text": "Python" } ]
Map of Tuples in C++ with Examples
19 Dec, 2021 What is a tuple? A tuple in C++ is an object that has the ability to group a number of elements. The elements can be of the same type as well as different data types. The order in which tuple elements are initialized can be accessed in the same order. Functions associated with a tuple: 1. make_tuple(): It is used to assign tuples with values. The values passed should be in order with the values declared in the tuple.2. get(): It is used to access the tuple values and modify them, it accepts the index and tuple name as arguments to access a particular tuple element. What is map? Maps in C++ are associative containers that can store elements in a mapped fashion. Each element of a map has a key and the corresponding mapped value. No two mapped values can have the same key values. A map follows the below syntax, Functions associated with Map: begin(): Returns an iterator to the first element in the map end(): Returns an iterator to the hypothetical element that follows the last element in the map size(): Returns the number of elements in the map max_size(): Returns the maximum number of elements that the map can hold empty(): Returns whether the map is empty clear(): Removes all the elements from the map Map of Tuples A map of tuples is a map in which either of the key or values is a tuple. Syntax: map<tuple<dataType1, dataType2, dataType3>, dataType>; Here, dataType1, dataType2, dataType3 are the data types for the tuple which is a key here dataType is the data type for value This article focuses on how to create a map of tuples in C++. Although one can make a tuple of more or fewer elements also but for simplicity, In this article, we have used tuples having only three elements. Example 1: Below is the C++ program to demonstrate the working of a map of tuples. C++ // CPP program to demonstrate // the working of a map of // tuples.#include <bits/stdc++.h>using namespace std; // Function to print map elementsvoid print(map<tuple<int, int, int>, int> &mapOfTuple){ cout << " Key(Tuple) " << "Value(Sum)\n\n"; for (auto pr : mapOfTuple) // pr points to current pair of mapOfTuple cout << "[" << get<0>(pr.first) << ", " << get<1>(pr.first) << ", " << get<2>(pr.first) << "] " << pr.second << "\n"; } // Driver codeint main(){ // Sending the hash function // as a third argument map<tuple<int, int, int>, int> mapOfTuple; // Creating some tuples to be used // as keys tuple<int, int, int> tuple1(100, 200, 300); tuple<int, int, int> tuple2(400, 500, 600); tuple<int, int, int> tuple3(700, 800, 900); // Mapping sum of tuple elements as values mapOfTuple[tuple1] = get<0>(tuple1) + get<1>(tuple1) + get<2>(tuple1); mapOfTuple[tuple2] = get<0>(tuple2) + get<1>(tuple2) + get<2>(tuple2); mapOfTuple[tuple3] = get<0>(tuple3) + get<1>(tuple3) + get<2>(tuple3); // Calling print function print(mapOfTuple); return 0;} Output: Key(Tuple) Value(Sum) [100, 200, 300] 600 [400, 500, 600] 1500 [700, 800, 900] 2400 Example 2: Below is the C++ program to demonstrate the working of a map of tuples. C++ // C++ program to demonstrate // the working of a map of // tuples.#include <bits/stdc++.h>using namespace std; // Function to print map elementsvoid print(map<tuple<string, string, string>, string> &mapOfTuple){ cout << " Key(Tuple) " << "Value(Concatenation)\n\n"; // Iterating over map using range-based loop for (auto pr : mapOfTuple) // pr points to current pair of mapOfTuple cout << "[" << get<0>(pr.first) << ", " << get<1>(pr.first) << ", " << get<2>(pr.first) << "] " << pr.second << "\n";} // Driver codeint main(){ // Declaring a map whose key is a // tuple of strings value is of // also string type map<tuple<string, string, string>, string> mapOfTuple; // Creating some tuples of string types // to be used as keys tuple<string, string, string> tuple1("Geeks", "for", "Geeks"); tuple<string, string, string> tuple2("R", "HTML", "Javascript"); tuple<string, string, string> tuple3("Python", "Swift", "Java"); // Mapping concatenation of tuple elements as values mapOfTuple[tuple1] = get<0>(tuple1) + " " + get<1>(tuple1) + " " + get<2>(tuple1); mapOfTuple[tuple2] = get<0>(tuple2) + " " + get<1>(tuple2) + " " + get<2>(tuple2); mapOfTuple[tuple3] = get<0>(tuple3) + " " + get<1>(tuple3) + " " + get<2>(tuple3); // Calling print function print(mapOfTuple); return 0;} Output: Key(Tuple) Value(Concatenation) [Geeks, for, Geeks] Geeks for Geeks [Python, Swift, Java] Python Swift Java [R, HTML, Javascript] R HTML Javascript cpp-map cpp-tuple STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Dec, 2021" }, { "code": null, "e": 69, "s": 52, "text": "What is a tuple?" }, { "code": null, "e": 304, "s": 69, "text": "A tuple in C++ is an object that has the ability to group a number of elements. The elements can be of the same type as well as different data types. The order in which tuple elements are initialized can be accessed in the same order." }, { "code": null, "e": 339, "s": 304, "text": "Functions associated with a tuple:" }, { "code": null, "e": 624, "s": 339, "text": "1. make_tuple(): It is used to assign tuples with values. The values passed should be in order with the values declared in the tuple.2. get(): It is used to access the tuple values and modify them, it accepts the index and tuple name as arguments to access a particular tuple element." }, { "code": null, "e": 637, "s": 624, "text": "What is map?" }, { "code": null, "e": 872, "s": 637, "text": "Maps in C++ are associative containers that can store elements in a mapped fashion. Each element of a map has a key and the corresponding mapped value. No two mapped values can have the same key values. A map follows the below syntax," }, { "code": null, "e": 903, "s": 872, "text": "Functions associated with Map:" }, { "code": null, "e": 964, "s": 903, "text": "begin(): Returns an iterator to the first element in the map" }, { "code": null, "e": 1060, "s": 964, "text": "end(): Returns an iterator to the hypothetical element that follows the last element in the map" }, { "code": null, "e": 1110, "s": 1060, "text": "size(): Returns the number of elements in the map" }, { "code": null, "e": 1183, "s": 1110, "text": "max_size(): Returns the maximum number of elements that the map can hold" }, { "code": null, "e": 1225, "s": 1183, "text": "empty(): Returns whether the map is empty" }, { "code": null, "e": 1272, "s": 1225, "text": "clear(): Removes all the elements from the map" }, { "code": null, "e": 1286, "s": 1272, "text": "Map of Tuples" }, { "code": null, "e": 1360, "s": 1286, "text": "A map of tuples is a map in which either of the key or values is a tuple." }, { "code": null, "e": 1368, "s": 1360, "text": "Syntax:" }, { "code": null, "e": 1423, "s": 1368, "text": "map<tuple<dataType1, dataType2, dataType3>, dataType>;" }, { "code": null, "e": 1430, "s": 1423, "text": "Here, " }, { "code": null, "e": 1515, "s": 1430, "text": "dataType1, dataType2, dataType3 are the data types for the tuple which is a key here" }, { "code": null, "e": 1553, "s": 1515, "text": "dataType is the data type for value " }, { "code": null, "e": 1761, "s": 1553, "text": "This article focuses on how to create a map of tuples in C++. Although one can make a tuple of more or fewer elements also but for simplicity, In this article, we have used tuples having only three elements." }, { "code": null, "e": 1844, "s": 1761, "text": "Example 1: Below is the C++ program to demonstrate the working of a map of tuples." }, { "code": null, "e": 1848, "s": 1844, "text": "C++" }, { "code": "// CPP program to demonstrate // the working of a map of // tuples.#include <bits/stdc++.h>using namespace std; // Function to print map elementsvoid print(map<tuple<int, int, int>, int> &mapOfTuple){ cout << \" Key(Tuple) \" << \"Value(Sum)\\n\\n\"; for (auto pr : mapOfTuple) // pr points to current pair of mapOfTuple cout << \"[\" << get<0>(pr.first) << \", \" << get<1>(pr.first) << \", \" << get<2>(pr.first) << \"] \" << pr.second << \"\\n\"; } // Driver codeint main(){ // Sending the hash function // as a third argument map<tuple<int, int, int>, int> mapOfTuple; // Creating some tuples to be used // as keys tuple<int, int, int> tuple1(100, 200, 300); tuple<int, int, int> tuple2(400, 500, 600); tuple<int, int, int> tuple3(700, 800, 900); // Mapping sum of tuple elements as values mapOfTuple[tuple1] = get<0>(tuple1) + get<1>(tuple1) + get<2>(tuple1); mapOfTuple[tuple2] = get<0>(tuple2) + get<1>(tuple2) + get<2>(tuple2); mapOfTuple[tuple3] = get<0>(tuple3) + get<1>(tuple3) + get<2>(tuple3); // Calling print function print(mapOfTuple); return 0;}", "e": 3188, "s": 1848, "text": null }, { "code": null, "e": 3196, "s": 3188, "text": "Output:" }, { "code": null, "e": 3229, "s": 3196, "text": "Key(Tuple) Value(Sum)" }, { "code": null, "e": 3260, "s": 3229, "text": "[100, 200, 300] 600" }, { "code": null, "e": 3292, "s": 3260, "text": "[400, 500, 600] 1500" }, { "code": null, "e": 3324, "s": 3292, "text": "[700, 800, 900] 2400" }, { "code": null, "e": 3407, "s": 3324, "text": "Example 2: Below is the C++ program to demonstrate the working of a map of tuples." }, { "code": null, "e": 3411, "s": 3407, "text": "C++" }, { "code": "// C++ program to demonstrate // the working of a map of // tuples.#include <bits/stdc++.h>using namespace std; // Function to print map elementsvoid print(map<tuple<string, string, string>, string> &mapOfTuple){ cout << \" Key(Tuple) \" << \"Value(Concatenation)\\n\\n\"; // Iterating over map using range-based loop for (auto pr : mapOfTuple) // pr points to current pair of mapOfTuple cout << \"[\" << get<0>(pr.first) << \", \" << get<1>(pr.first) << \", \" << get<2>(pr.first) << \"] \" << pr.second << \"\\n\";} // Driver codeint main(){ // Declaring a map whose key is a // tuple of strings value is of // also string type map<tuple<string, string, string>, string> mapOfTuple; // Creating some tuples of string types // to be used as keys tuple<string, string, string> tuple1(\"Geeks\", \"for\", \"Geeks\"); tuple<string, string, string> tuple2(\"R\", \"HTML\", \"Javascript\"); tuple<string, string, string> tuple3(\"Python\", \"Swift\", \"Java\"); // Mapping concatenation of tuple elements as values mapOfTuple[tuple1] = get<0>(tuple1) + \" \" + get<1>(tuple1) + \" \" + get<2>(tuple1); mapOfTuple[tuple2] = get<0>(tuple2) + \" \" + get<1>(tuple2) + \" \" + get<2>(tuple2); mapOfTuple[tuple3] = get<0>(tuple3) + \" \" + get<1>(tuple3) + \" \" + get<2>(tuple3); // Calling print function print(mapOfTuple); return 0;}", "e": 4969, "s": 3411, "text": null }, { "code": null, "e": 4977, "s": 4969, "text": "Output:" }, { "code": null, "e": 5022, "s": 4977, "text": " Key(Tuple) Value(Concatenation)" }, { "code": null, "e": 5066, "s": 5022, "text": "[Geeks, for, Geeks] Geeks for Geeks" }, { "code": null, "e": 5114, "s": 5066, "text": "[Python, Swift, Java] Python Swift Java" }, { "code": null, "e": 5162, "s": 5114, "text": "[R, HTML, Javascript] R HTML Javascript" }, { "code": null, "e": 5170, "s": 5162, "text": "cpp-map" }, { "code": null, "e": 5180, "s": 5170, "text": "cpp-tuple" }, { "code": null, "e": 5184, "s": 5180, "text": "STL" }, { "code": null, "e": 5188, "s": 5184, "text": "C++" }, { "code": null, "e": 5192, "s": 5188, "text": "STL" }, { "code": null, "e": 5196, "s": 5192, "text": "CPP" } ]
Min-Max Range Queries in Array
18 Apr, 2022 Given an array arr[0 . . . n-1]. We need to efficiently find the minimum and maximum value from index qs (query start) to qe (query end) where 0 <= qs <= qe <= n-1. We are given multiple queries. Examples: Input : arr[] = {1, 8, 5, 9, 6, 14, 2, 4, 3, 7} queries = 5 qs = 0 qe = 4 qs = 3 qe = 7 qs = 1 qe = 6 qs = 2 qe = 5 qs = 0 qe = 8 Output: Minimum = 1 and Maximum = 9 Minimum = 2 and Maximum = 14 Minimum = 2 and Maximum = 14 Minimum = 5 and Maximum = 14 Minimum = 1 and Maximum = 14 Simple Solution : We solve this problem using Tournament Method for each query. Complexity for this approach will be O(queries * n). Efficient solution : This problem can be solved more efficiently by using Segment Tree. First read given segment tree link then start solving this problem. C++ // C++ program to find minimum and maximum using segment tree#include<bits/stdc++.h>using namespace std; // Node for storing minimum and maximum value of given rangestruct node{ int minimum; int maximum;}; // A utility function to get the middle index from corner indexes.int getMid(int s, int e) { return s + (e -s)/2; } /* A recursive function to get the minimum and maximum value in a given range of array indexes. The following are parameters for this function. st --> Pointer to segment tree index --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range */struct node MaxMinUntill(struct node *st, int ss, int se, int qs, int qe, int index){ // If segment of this node is a part of given range, then return // the minimum and maximum node of the segment struct node tmp,left,right; if (qs <= ss && qe >= se) return st[index]; // If segment of this node is outside the given range if (se < qs || ss > qe) { tmp.minimum = INT_MAX; tmp.maximum = INT_MIN; return tmp; } // If a part of this segment overlaps with the given range int mid = getMid(ss, se); left = MaxMinUntill(st, ss, mid, qs, qe, 2*index+1); right = MaxMinUntill(st, mid+1, se, qs, qe, 2*index+2); tmp.minimum = min(left.minimum, right.minimum); tmp.maximum = max(left.maximum, right.maximum); return tmp;} // Return minimum and maximum of elements in range from index// qs (query start) to qe (query end). It mainly uses// MaxMinUtill()struct node MaxMin(struct node *st, int n, int qs, int qe){ struct node tmp; // Check for erroneous input values if (qs < 0 || qe > n-1 || qs > qe) { printf("Invalid Input"); tmp.minimum = INT_MIN; tmp.minimum = INT_MAX; return tmp; } return MaxMinUntill(st, 0, n-1, qs, qe, 0);} // A recursive function that constructs Segment Tree for array[ss..se].// si is index of current node in segment tree stvoid constructSTUtil(int arr[], int ss, int se, struct node *st, int si){ // If there is one element in array, store it in current node of // segment tree and return if (ss == se) { st[si].minimum = arr[ss]; st[si].maximum = arr[ss]; return ; } // If there are more than one elements, then recur for left and // right subtrees and store the minimum and maximum of two values // in this node int mid = getMid(ss, se); constructSTUtil(arr, ss, mid, st, si*2+1); constructSTUtil(arr, mid+1, se, st, si*2+2); st[si].minimum = min(st[si*2+1].minimum, st[si*2+2].minimum); st[si].maximum = max(st[si*2+1].maximum, st[si*2+2].maximum);} /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */struct node *constructST(int arr[], int n){ // Allocate memory for segment tree // Height of segment tree int x = (int)(ceil(log2(n))); // Maximum size of segment tree int max_size = 2*(int)pow(2, x) - 1; struct node *st = new struct node[max_size]; // Fill the allocated memory st constructSTUtil(arr, 0, n-1, st, 0); // Return the constructed segment tree return st;} // Driver program to test above functionsint main(){ int arr[] = {1, 8, 5, 9, 6, 14, 2, 4, 3, 7}; int n = sizeof(arr)/sizeof(arr[0]); // Build segment tree from given array struct node *st = constructST(arr, n); int qs = 0; // Starting index of query range int qe = 8; // Ending index of query range struct node result=MaxMin(st, n, qs, qe); // Print minimum and maximum value in arr[qs..qe] printf("Minimum = %d and Maximum = %d ", result.minimum, result.maximum); return 0;} Output: Minimum = 1 and Maximum = 14 Time Complexity : O(queries * logn) Auxiliary Space: O(n) Can we do better if there are no updates on array? The above segment tree based solution also allows array updates also to happen in O(Log n) time. Assume a situation when there are no updates (or array is static). We can actually process all queries in O(1) time with some preprocessing. One simple solution is to make a 2D table of nodes that stores all range minimum and maximum. This solution requires O(1) query time, but requires O(n2) preprocessing time and O(n2) extra space which can be a problem for large n. We can solve this problem in O(1) query time, O(n Log n) space and O(n Log n) preprocessing time using Sparse Table. This article is contributed by Shashank Mishra.This article is reviewed by team GeeksForGeeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. surinderdawra388 prophet1999 simmytarika5 array-range-queries Segment-Tree Advanced Data Structure Segment-Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. AVL Tree | Set 1 (Insertion) Trie | (Insert and Search) LRU Cache Implementation Introduction of B-Tree Agents in Artificial Intelligence Red-Black Tree | Set 1 (Introduction) Decision Tree Introduction with example Binary Indexed Tree or Fenwick Tree AVL Tree | Set 2 (Deletion) Disjoint Set Data Structures
[ { "code": null, "e": 52, "s": 24, "text": "\n18 Apr, 2022" }, { "code": null, "e": 248, "s": 52, "text": "Given an array arr[0 . . . n-1]. We need to efficiently find the minimum and maximum value from index qs (query start) to qe (query end) where 0 <= qs <= qe <= n-1. We are given multiple queries." }, { "code": null, "e": 259, "s": 248, "text": "Examples: " }, { "code": null, "e": 625, "s": 259, "text": "Input : arr[] = {1, 8, 5, 9, 6, 14, 2, 4, 3, 7}\n queries = 5\n qs = 0 qe = 4\n qs = 3 qe = 7\n qs = 1 qe = 6\n qs = 2 qe = 5\n qs = 0 qe = 8\nOutput: Minimum = 1 and Maximum = 9 \n Minimum = 2 and Maximum = 14 \n Minimum = 2 and Maximum = 14 \n Minimum = 5 and Maximum = 14\n Minimum = 1 and Maximum = 14 " }, { "code": null, "e": 758, "s": 625, "text": "Simple Solution : We solve this problem using Tournament Method for each query. Complexity for this approach will be O(queries * n)." }, { "code": null, "e": 915, "s": 758, "text": "Efficient solution : This problem can be solved more efficiently by using Segment Tree. First read given segment tree link then start solving this problem. " }, { "code": null, "e": 919, "s": 915, "text": "C++" }, { "code": "// C++ program to find minimum and maximum using segment tree#include<bits/stdc++.h>using namespace std; // Node for storing minimum and maximum value of given rangestruct node{ int minimum; int maximum;}; // A utility function to get the middle index from corner indexes.int getMid(int s, int e) { return s + (e -s)/2; } /* A recursive function to get the minimum and maximum value in a given range of array indexes. The following are parameters for this function. st --> Pointer to segment tree index --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range */struct node MaxMinUntill(struct node *st, int ss, int se, int qs, int qe, int index){ // If segment of this node is a part of given range, then return // the minimum and maximum node of the segment struct node tmp,left,right; if (qs <= ss && qe >= se) return st[index]; // If segment of this node is outside the given range if (se < qs || ss > qe) { tmp.minimum = INT_MAX; tmp.maximum = INT_MIN; return tmp; } // If a part of this segment overlaps with the given range int mid = getMid(ss, se); left = MaxMinUntill(st, ss, mid, qs, qe, 2*index+1); right = MaxMinUntill(st, mid+1, se, qs, qe, 2*index+2); tmp.minimum = min(left.minimum, right.minimum); tmp.maximum = max(left.maximum, right.maximum); return tmp;} // Return minimum and maximum of elements in range from index// qs (query start) to qe (query end). It mainly uses// MaxMinUtill()struct node MaxMin(struct node *st, int n, int qs, int qe){ struct node tmp; // Check for erroneous input values if (qs < 0 || qe > n-1 || qs > qe) { printf(\"Invalid Input\"); tmp.minimum = INT_MIN; tmp.minimum = INT_MAX; return tmp; } return MaxMinUntill(st, 0, n-1, qs, qe, 0);} // A recursive function that constructs Segment Tree for array[ss..se].// si is index of current node in segment tree stvoid constructSTUtil(int arr[], int ss, int se, struct node *st, int si){ // If there is one element in array, store it in current node of // segment tree and return if (ss == se) { st[si].minimum = arr[ss]; st[si].maximum = arr[ss]; return ; } // If there are more than one elements, then recur for left and // right subtrees and store the minimum and maximum of two values // in this node int mid = getMid(ss, se); constructSTUtil(arr, ss, mid, st, si*2+1); constructSTUtil(arr, mid+1, se, st, si*2+2); st[si].minimum = min(st[si*2+1].minimum, st[si*2+2].minimum); st[si].maximum = max(st[si*2+1].maximum, st[si*2+2].maximum);} /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */struct node *constructST(int arr[], int n){ // Allocate memory for segment tree // Height of segment tree int x = (int)(ceil(log2(n))); // Maximum size of segment tree int max_size = 2*(int)pow(2, x) - 1; struct node *st = new struct node[max_size]; // Fill the allocated memory st constructSTUtil(arr, 0, n-1, st, 0); // Return the constructed segment tree return st;} // Driver program to test above functionsint main(){ int arr[] = {1, 8, 5, 9, 6, 14, 2, 4, 3, 7}; int n = sizeof(arr)/sizeof(arr[0]); // Build segment tree from given array struct node *st = constructST(arr, n); int qs = 0; // Starting index of query range int qe = 8; // Ending index of query range struct node result=MaxMin(st, n, qs, qe); // Print minimum and maximum value in arr[qs..qe] printf(\"Minimum = %d and Maximum = %d \", result.minimum, result.maximum); return 0;}", "e": 4948, "s": 919, "text": null }, { "code": null, "e": 4957, "s": 4948, "text": "Output: " }, { "code": null, "e": 4987, "s": 4957, "text": "Minimum = 1 and Maximum = 14 " }, { "code": null, "e": 5023, "s": 4987, "text": "Time Complexity : O(queries * logn)" }, { "code": null, "e": 5045, "s": 5023, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 5681, "s": 5045, "text": "Can we do better if there are no updates on array? The above segment tree based solution also allows array updates also to happen in O(Log n) time. Assume a situation when there are no updates (or array is static). We can actually process all queries in O(1) time with some preprocessing. One simple solution is to make a 2D table of nodes that stores all range minimum and maximum. This solution requires O(1) query time, but requires O(n2) preprocessing time and O(n2) extra space which can be a problem for large n. We can solve this problem in O(1) query time, O(n Log n) space and O(n Log n) preprocessing time using Sparse Table." }, { "code": null, "e": 5902, "s": 5681, "text": "This article is contributed by Shashank Mishra.This article is reviewed by team GeeksForGeeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 5919, "s": 5902, "text": "surinderdawra388" }, { "code": null, "e": 5931, "s": 5919, "text": "prophet1999" }, { "code": null, "e": 5944, "s": 5931, "text": "simmytarika5" }, { "code": null, "e": 5964, "s": 5944, "text": "array-range-queries" }, { "code": null, "e": 5977, "s": 5964, "text": "Segment-Tree" }, { "code": null, "e": 6001, "s": 5977, "text": "Advanced Data Structure" }, { "code": null, "e": 6014, "s": 6001, "text": "Segment-Tree" }, { "code": null, "e": 6112, "s": 6014, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6141, "s": 6112, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 6168, "s": 6141, "text": "Trie | (Insert and Search)" }, { "code": null, "e": 6193, "s": 6168, "text": "LRU Cache Implementation" }, { "code": null, "e": 6216, "s": 6193, "text": "Introduction of B-Tree" }, { "code": null, "e": 6250, "s": 6216, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 6288, "s": 6250, "text": "Red-Black Tree | Set 1 (Introduction)" }, { "code": null, "e": 6328, "s": 6288, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 6364, "s": 6328, "text": "Binary Indexed Tree or Fenwick Tree" }, { "code": null, "e": 6392, "s": 6364, "text": "AVL Tree | Set 2 (Deletion)" } ]
Discrete Fourier Transform and its Inverse using MATLAB
04 Jul, 2021 With the advent of MATLAB and all the scientific inbuilt that it has brought, there’s been a significant change and simplification of sophisticating engineering scenarios. In fact, this change has contributed to helping build better visualization and practical skills for students pursuing technical studies in the sciences, if not other fields at the very least. Here we look at implementing a fundamental mathematical idea – the Discrete Fourier Transform and its Inverse using MATLAB. The standard equations which define how the Discrete Fourier Transform and the Inverse convert a signal from the time domain to the frequency domain and vice versa are as follows: DFT: for k=0, 1, 2....., N-1 IDFT: for n=0, 1, 2....., N-1 The equations being rather straightforward, one might simply execute repetitive/nested loops for the summation and be done with it. However, we should attempt to utilize another method where we use matrices to find the solution to the problem. Many readers would recall that the DFT and IDFT of a time/frequency domain signal may be represented in vector format as the following: When we take the twiddle factors as components of a matrix, it becomes much easier to calculate the DFT and IDFT. Therefore, if our frequency-domain signal is a single-row matrix represented by XN and the time-domain signal is also a single-row matrix represented as xN...... With this interpretation, all we require to do, is create two arrays upon which we shall issue a matrix multiplication to obtain the output. The output matrix will ALWAYS be a Nx1 order matrix since we take a single-row matrix as our input signal (XN or xN). This is essentially a vector which we may transpose to a horizontal matrix for our convenience. Obtain the input sequence and number of points of the DFT sequence.Send the obtained data to a function which calculates the DFT. It isn’t imperative to declare a new function but code legibility and flow become cleaner and apparent.Determine the length of the input sequence using the length( ) function and check if the length is greater than the number of points. N must always be equal to or greater than the sequence. If you try to execute the matrix multiplication by not satisfying the condition, you’ll be met with an error in your command window.Accounting for the difference in lengths of the input sequence and the N-points using a separate array which adds extra zeros to elongate the input sequence. This is done using the zeros(no_of_rows, no_of_columns) function which creates a 2D array composed of zeros.Based on the value of N obtained as input, create the WN matrix. To do this, implement 2 ‘for’ loops -quite a basic procedure.Simply multiply the two arrays that have been created. This is an array of the required frequency-domain signal samples.Plot the magnitude and the phase of the output signal via inbuilt functions abs(function_name) and angle(function_name). Obtain the input sequence and number of points of the DFT sequence. Send the obtained data to a function which calculates the DFT. It isn’t imperative to declare a new function but code legibility and flow become cleaner and apparent. Determine the length of the input sequence using the length( ) function and check if the length is greater than the number of points. N must always be equal to or greater than the sequence. If you try to execute the matrix multiplication by not satisfying the condition, you’ll be met with an error in your command window. Accounting for the difference in lengths of the input sequence and the N-points using a separate array which adds extra zeros to elongate the input sequence. This is done using the zeros(no_of_rows, no_of_columns) function which creates a 2D array composed of zeros. Based on the value of N obtained as input, create the WN matrix. To do this, implement 2 ‘for’ loops -quite a basic procedure. Simply multiply the two arrays that have been created. This is an array of the required frequency-domain signal samples. Plot the magnitude and the phase of the output signal via inbuilt functions abs(function_name) and angle(function_name). Matlab % MATLAB code for DFT clc;xn=input('Input sequence: ');N = input('Enter the number of points: ');Xk=calcdft(xn,N);disp('DFT X(k): ');disp(Xk);mgXk = abs(Xk);phaseXk = angle(Xk);k=0:N-1;subplot (2,1,1);stem(k,mgXk);title ('DFT sequence: ');xlabel('Frequency');ylabel('Magnitude');subplot(2,1,2);stem(k,phaseXk);title('Phase of the DFT sequence');xlabel('Frequency');ylabel('Phase'); function[Xk] = calcdft(xn,N) L=length(xn); if(N<L) error('N must be greater than or equal to L!!') end x1=[xn, zeros(1,N-L)]; for k=0:1:N-1 for n=0:1:N-1 p=exp(-i*2*pi*n*k/N); W(k+1,n+1)=p; end end disp('Transformation matrix for DFT') disp(W); Xk=W*(x1.')end Output: >> Input sequence: [1 4 9 16 25 36 49 64 81] >> Enter the number of points: 9 Obtain the frequency-domain signal / sequence as input (X(k)). The length of this sequence suffices as a value for N (points).Pass this array to a function for computation.Run 2 loops in the function to create the matrix. Note that this matrix must be conjugated when being utilized for the calculation. You may choose to explicitly declare another array which is the conjugate of the matrix WN.Once, the matrix has been created, obtain the conjugate using ‘*‘ and simply multiply it with the input sequence’s transpose. We require the transpose as the input is a row matrix. When multiplying with the WN matrix we have created, the number of columns in WN must match the number of rows in X(k).Plot this sequence using stem(x_axis, y_axis). DO NOT use plot( ) since this is not a CT signal. Obtain the frequency-domain signal / sequence as input (X(k)). The length of this sequence suffices as a value for N (points). Pass this array to a function for computation. Run 2 loops in the function to create the matrix. Note that this matrix must be conjugated when being utilized for the calculation. You may choose to explicitly declare another array which is the conjugate of the matrix WN. Once, the matrix has been created, obtain the conjugate using ‘*‘ and simply multiply it with the input sequence’s transpose. We require the transpose as the input is a row matrix. When multiplying with the WN matrix we have created, the number of columns in WN must match the number of rows in X(k). Plot this sequence using stem(x_axis, y_axis). DO NOT use plot( ) since this is not a CT signal. Matlab % MATLAB code for IDFTclc;Xk = input('Input sequence X(k): ');xn=calcidft(Xk);N=length(xn);disp('xn');disp(xn);n=0:N-1;stem(n,xn);xlabel('time');ylabel('Amplitude'); function [xn] = calcidft(Xk) %function to calculate IDFT N=length(Xk); for k=0:1:N-1 for n=0:1:N-1 p=exp(i*2*pi*n*k/N); IT(k+1,n+1)=p; end end disp('Transformation Matrix for IDFT'); disp(IT); xn = (IT*(Xk.'))/N;end >> Enter the input sequence: [1 2 3 4 5 9 8 7 6 5] Transformation Matrix The time-domain sequence Functions MATLAB MATLAB Program Output Functions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n04 Jul, 2021" }, { "code": null, "e": 542, "s": 53, "text": "With the advent of MATLAB and all the scientific inbuilt that it has brought, there’s been a significant change and simplification of sophisticating engineering scenarios. In fact, this change has contributed to helping build better visualization and practical skills for students pursuing technical studies in the sciences, if not other fields at the very least. Here we look at implementing a fundamental mathematical idea – the Discrete Fourier Transform and its Inverse using MATLAB. " }, { "code": null, "e": 723, "s": 542, "text": "The standard equations which define how the Discrete Fourier Transform and the Inverse convert a signal from the time domain to the frequency domain and vice versa are as follows: " }, { "code": null, "e": 752, "s": 723, "text": "DFT: for k=0, 1, 2....., N-1" }, { "code": null, "e": 782, "s": 752, "text": "IDFT: for n=0, 1, 2....., N-1" }, { "code": null, "e": 1162, "s": 782, "text": "The equations being rather straightforward, one might simply execute repetitive/nested loops for the summation and be done with it. However, we should attempt to utilize another method where we use matrices to find the solution to the problem. Many readers would recall that the DFT and IDFT of a time/frequency domain signal may be represented in vector format as the following:" }, { "code": null, "e": 1438, "s": 1162, "text": "When we take the twiddle factors as components of a matrix, it becomes much easier to calculate the DFT and IDFT. Therefore, if our frequency-domain signal is a single-row matrix represented by XN and the time-domain signal is also a single-row matrix represented as xN......" }, { "code": null, "e": 1793, "s": 1438, "text": "With this interpretation, all we require to do, is create two arrays upon which we shall issue a matrix multiplication to obtain the output. The output matrix will ALWAYS be a Nx1 order matrix since we take a single-row matrix as our input signal (XN or xN). This is essentially a vector which we may transpose to a horizontal matrix for our convenience." }, { "code": null, "e": 2981, "s": 1793, "text": "Obtain the input sequence and number of points of the DFT sequence.Send the obtained data to a function which calculates the DFT. It isn’t imperative to declare a new function but code legibility and flow become cleaner and apparent.Determine the length of the input sequence using the length( ) function and check if the length is greater than the number of points. N must always be equal to or greater than the sequence. If you try to execute the matrix multiplication by not satisfying the condition, you’ll be met with an error in your command window.Accounting for the difference in lengths of the input sequence and the N-points using a separate array which adds extra zeros to elongate the input sequence. This is done using the zeros(no_of_rows, no_of_columns) function which creates a 2D array composed of zeros.Based on the value of N obtained as input, create the WN matrix. To do this, implement 2 ‘for’ loops -quite a basic procedure.Simply multiply the two arrays that have been created. This is an array of the required frequency-domain signal samples.Plot the magnitude and the phase of the output signal via inbuilt functions abs(function_name) and angle(function_name)." }, { "code": null, "e": 3049, "s": 2981, "text": "Obtain the input sequence and number of points of the DFT sequence." }, { "code": null, "e": 3216, "s": 3049, "text": "Send the obtained data to a function which calculates the DFT. It isn’t imperative to declare a new function but code legibility and flow become cleaner and apparent." }, { "code": null, "e": 3539, "s": 3216, "text": "Determine the length of the input sequence using the length( ) function and check if the length is greater than the number of points. N must always be equal to or greater than the sequence. If you try to execute the matrix multiplication by not satisfying the condition, you’ll be met with an error in your command window." }, { "code": null, "e": 3806, "s": 3539, "text": "Accounting for the difference in lengths of the input sequence and the N-points using a separate array which adds extra zeros to elongate the input sequence. This is done using the zeros(no_of_rows, no_of_columns) function which creates a 2D array composed of zeros." }, { "code": null, "e": 3933, "s": 3806, "text": "Based on the value of N obtained as input, create the WN matrix. To do this, implement 2 ‘for’ loops -quite a basic procedure." }, { "code": null, "e": 4054, "s": 3933, "text": "Simply multiply the two arrays that have been created. This is an array of the required frequency-domain signal samples." }, { "code": null, "e": 4175, "s": 4054, "text": "Plot the magnitude and the phase of the output signal via inbuilt functions abs(function_name) and angle(function_name)." }, { "code": null, "e": 4182, "s": 4175, "text": "Matlab" }, { "code": "% MATLAB code for DFT clc;xn=input('Input sequence: ');N = input('Enter the number of points: ');Xk=calcdft(xn,N);disp('DFT X(k): ');disp(Xk);mgXk = abs(Xk);phaseXk = angle(Xk);k=0:N-1;subplot (2,1,1);stem(k,mgXk);title ('DFT sequence: ');xlabel('Frequency');ylabel('Magnitude');subplot(2,1,2);stem(k,phaseXk);title('Phase of the DFT sequence');xlabel('Frequency');ylabel('Phase'); function[Xk] = calcdft(xn,N) L=length(xn); if(N<L) error('N must be greater than or equal to L!!') end x1=[xn, zeros(1,N-L)]; for k=0:1:N-1 for n=0:1:N-1 p=exp(-i*2*pi*n*k/N); W(k+1,n+1)=p; end end disp('Transformation matrix for DFT') disp(W); Xk=W*(x1.')end", "e": 4895, "s": 4182, "text": null }, { "code": null, "e": 4903, "s": 4895, "text": "Output:" }, { "code": null, "e": 4981, "s": 4903, "text": ">> Input sequence: [1 4 9 16 25 36 49 64 81]\n>> Enter the number of points: 9" }, { "code": null, "e": 5773, "s": 4981, "text": "Obtain the frequency-domain signal / sequence as input (X(k)). The length of this sequence suffices as a value for N (points).Pass this array to a function for computation.Run 2 loops in the function to create the matrix. Note that this matrix must be conjugated when being utilized for the calculation. You may choose to explicitly declare another array which is the conjugate of the matrix WN.Once, the matrix has been created, obtain the conjugate using ‘*‘ and simply multiply it with the input sequence’s transpose. We require the transpose as the input is a row matrix. When multiplying with the WN matrix we have created, the number of columns in WN must match the number of rows in X(k).Plot this sequence using stem(x_axis, y_axis). DO NOT use plot( ) since this is not a CT signal." }, { "code": null, "e": 5900, "s": 5773, "text": "Obtain the frequency-domain signal / sequence as input (X(k)). The length of this sequence suffices as a value for N (points)." }, { "code": null, "e": 5947, "s": 5900, "text": "Pass this array to a function for computation." }, { "code": null, "e": 6171, "s": 5947, "text": "Run 2 loops in the function to create the matrix. Note that this matrix must be conjugated when being utilized for the calculation. You may choose to explicitly declare another array which is the conjugate of the matrix WN." }, { "code": null, "e": 6472, "s": 6171, "text": "Once, the matrix has been created, obtain the conjugate using ‘*‘ and simply multiply it with the input sequence’s transpose. We require the transpose as the input is a row matrix. When multiplying with the WN matrix we have created, the number of columns in WN must match the number of rows in X(k)." }, { "code": null, "e": 6569, "s": 6472, "text": "Plot this sequence using stem(x_axis, y_axis). DO NOT use plot( ) since this is not a CT signal." }, { "code": null, "e": 6576, "s": 6569, "text": "Matlab" }, { "code": "% MATLAB code for IDFTclc;Xk = input('Input sequence X(k): ');xn=calcidft(Xk);N=length(xn);disp('xn');disp(xn);n=0:N-1;stem(n,xn);xlabel('time');ylabel('Amplitude'); function [xn] = calcidft(Xk) %function to calculate IDFT N=length(Xk); for k=0:1:N-1 for n=0:1:N-1 p=exp(i*2*pi*n*k/N); IT(k+1,n+1)=p; end end disp('Transformation Matrix for IDFT'); disp(IT); xn = (IT*(Xk.'))/N;end", "e": 7013, "s": 6576, "text": null }, { "code": null, "e": 7064, "s": 7013, "text": ">> Enter the input sequence: [1 2 3 4 5 9 8 7 6 5]" }, { "code": null, "e": 7086, "s": 7064, "text": "Transformation Matrix" }, { "code": null, "e": 7111, "s": 7086, "text": "The time-domain sequence" }, { "code": null, "e": 7121, "s": 7111, "text": "Functions" }, { "code": null, "e": 7128, "s": 7121, "text": "MATLAB" }, { "code": null, "e": 7135, "s": 7128, "text": "MATLAB" }, { "code": null, "e": 7150, "s": 7135, "text": "Program Output" }, { "code": null, "e": 7160, "s": 7150, "text": "Functions" } ]
TreeMap lastKey() Method in Java
09 Jul, 2018 The java.util.TreeMap.lastKey() is used to retrieve the last or the highest key present in the map. Syntax: tree_map.lastKey() Parameters: The method does not take any parameters. Return Value: The method returns the last key present in the map. Exception: The method throws NoSuchElementException if the map is empty. Below programs illustrate the working of java.util.TreeMap.lastKey() method:Program 1: // Java code to illustrate the lastKey() methodimport java.util.*; public class Tree_Map_Demo { public static void main(String[] args) { // Creating an empty TreeMap TreeMap<Integer, String> tree_map = new TreeMap<Integer, String>(); // Mapping string values to int keys tree_map.put(10, "Geeks"); tree_map.put(15, "4"); tree_map.put(20, "Geeks"); tree_map.put(25, "Welcomes"); tree_map.put(30, "You"); // Displaying the TreeMap System.out.println("The Mappings are: " + tree_map); // Displaying the lastKey of the map System.out.println("The last key is " + tree_map.lastKey()); }} The Mappings are: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You} The last key is 30 Program 2: // Java code to illustrate the lastKey() methodimport java.util.*; public class Tree_Map_Demo { public static void main(String[] args) { // Creating an empty TreeMap TreeMap<String, Integer> tree_map = new TreeMap<String, Integer>(); // Mapping int values to string keys tree_map.put("Geeks", 10); tree_map.put("4", 15); tree_map.put("Geeks", 20); tree_map.put("Welcomes", 25); tree_map.put("You", 30); // Displaying the TreeMap System.out.println("The Mappings are: " + tree_map); // Displaying the lastKey of the map System.out.println("The last key is " + tree_map.lastKey()); }} The Mappings are: {4=15, Geeks=20, Welcomes=25, You=30} The last key is You Java-Collections java-TreeMap Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Jul, 2018" }, { "code": null, "e": 128, "s": 28, "text": "The java.util.TreeMap.lastKey() is used to retrieve the last or the highest key present in the map." }, { "code": null, "e": 136, "s": 128, "text": "Syntax:" }, { "code": null, "e": 156, "s": 136, "text": " tree_map.lastKey()" }, { "code": null, "e": 209, "s": 156, "text": "Parameters: The method does not take any parameters." }, { "code": null, "e": 275, "s": 209, "text": "Return Value: The method returns the last key present in the map." }, { "code": null, "e": 348, "s": 275, "text": "Exception: The method throws NoSuchElementException if the map is empty." }, { "code": null, "e": 435, "s": 348, "text": "Below programs illustrate the working of java.util.TreeMap.lastKey() method:Program 1:" }, { "code": "// Java code to illustrate the lastKey() methodimport java.util.*; public class Tree_Map_Demo { public static void main(String[] args) { // Creating an empty TreeMap TreeMap<Integer, String> tree_map = new TreeMap<Integer, String>(); // Mapping string values to int keys tree_map.put(10, \"Geeks\"); tree_map.put(15, \"4\"); tree_map.put(20, \"Geeks\"); tree_map.put(25, \"Welcomes\"); tree_map.put(30, \"You\"); // Displaying the TreeMap System.out.println(\"The Mappings are: \" + tree_map); // Displaying the lastKey of the map System.out.println(\"The last key is \" + tree_map.lastKey()); }}", "e": 1120, "s": 435, "text": null }, { "code": null, "e": 1206, "s": 1120, "text": "The Mappings are: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}\nThe last key is 30\n" }, { "code": null, "e": 1217, "s": 1206, "text": "Program 2:" }, { "code": "// Java code to illustrate the lastKey() methodimport java.util.*; public class Tree_Map_Demo { public static void main(String[] args) { // Creating an empty TreeMap TreeMap<String, Integer> tree_map = new TreeMap<String, Integer>(); // Mapping int values to string keys tree_map.put(\"Geeks\", 10); tree_map.put(\"4\", 15); tree_map.put(\"Geeks\", 20); tree_map.put(\"Welcomes\", 25); tree_map.put(\"You\", 30); // Displaying the TreeMap System.out.println(\"The Mappings are: \" + tree_map); // Displaying the lastKey of the map System.out.println(\"The last key is \" + tree_map.lastKey()); }}", "e": 1902, "s": 1217, "text": null }, { "code": null, "e": 1979, "s": 1902, "text": "The Mappings are: {4=15, Geeks=20, Welcomes=25, You=30}\nThe last key is You\n" }, { "code": null, "e": 1996, "s": 1979, "text": "Java-Collections" }, { "code": null, "e": 2009, "s": 1996, "text": "java-TreeMap" }, { "code": null, "e": 2014, "s": 2009, "text": "Java" }, { "code": null, "e": 2019, "s": 2014, "text": "Java" }, { "code": null, "e": 2036, "s": 2019, "text": "Java-Collections" } ]
Output of Java program | Set 15 (Inner Classes)
29 Jan, 2020 Prerequisite :- Local inner classes , anonymous inner classes 1) What is the output of the following java program? public class Outer { public static int temp1 = 1; private static int temp2 = 2; public int temp3 = 3; private int temp4 = 4; public static class Inner { private static int temp5 = 5; private static int getSum() { return (temp1 + temp2 + temp3 + temp4 + temp5); } } public static void main(String[] args) { Outer.Inner obj = new Outer.Inner(); System.out.println(obj.getSum()); } } a) 15b) 9c) 5d) Compilation Error Ans. (d)Explanation: static inner classes cannot access non-static fields of the outer class. 2) What is the output of the following program? public class Outer { private static int data = 10; private static int LocalClass() { class Inner { public int data = 20; private int getData() { return data; } }; Inner inner = new Inner(); return inner.getData(); } public static void main(String[] args) { System.out.println(data * LocalClass()); }} a) Compilation errorb) Runtime Errorc) 200d) None of the above Ans. (c)Explanation: LocalClass() method defines a local inner class. This method creates an object of class Inner and return the value of the variable data that resides within it. 3) What is the output of the following program? interface Anonymous{ public int getValue();}public class Outer { private int data = 15; public static void main(String[] args) { Anonymous inner = new Anonymous() { int data = 5; public int getValue() { return data; } public int getData() { return data; } }; Outer outer = new Outer(); System.out.println(inner.getValue() + inner.getData() + outer.data); }} a) 25b) Compilation errorc) 20d) Runtime error Ans. (b)Explanation: the method getData() is undefined in Anonymous class which causes the compilation error. 4) What is the output of the following java program? public class Outer{ private int data = 10; class Inner { private int data = 20; private int getData() { return data; } public void main(String[] args) { Inner inner = new Inner(); System.out.println(inner.getData()); } } private int getData() { return data; } public static void main(String[] args) { Outer outer = new Outer(); Outer.Inner inner = outer.new Inner(); System.out.printf("%d", outer.getData()); inner.main(args); }} a) 2010b) 1020c) Compilation Errord) None of these Ans. (b)Explanation: Inner class defined above though, have access to the private variable data of the Outer class, but declaring a variable data inside an inner class makes it specific to the Inner class with no conflicts in term of variable declaration. For more see Shadowing 5) What is the output of the following program? interface OuterInterface{ public void InnerMethod(); public interface InnerInterface { public void InnerMethod(); }}public class Outer implements OuterInterface.InnerInterface, OuterInterface{ public void InnerMethod() { System.out.println(100); } public static void main(String[] args) { Outer obj = new Outer(); obj.InnerMethod(); }} a) 100b) Compilation Errorc) Runtime Errord) None of the above Ans. (a)Explanation: Nested Interfaces are defined in java. As both the interfaces has declaration of InnerMethod(), implementing it once works for both the InnerInterface and OuterInterface. This article is contributed by Mayank Kumar. 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. Java-Output Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n29 Jan, 2020" }, { "code": null, "e": 114, "s": 52, "text": "Prerequisite :- Local inner classes , anonymous inner classes" }, { "code": null, "e": 167, "s": 114, "text": "1) What is the output of the following java program?" }, { "code": "public class Outer { public static int temp1 = 1; private static int temp2 = 2; public int temp3 = 3; private int temp4 = 4; public static class Inner { private static int temp5 = 5; private static int getSum() { return (temp1 + temp2 + temp3 + temp4 + temp5); } } public static void main(String[] args) { Outer.Inner obj = new Outer.Inner(); System.out.println(obj.getSum()); } }", "e": 658, "s": 167, "text": null }, { "code": null, "e": 692, "s": 658, "text": "a) 15b) 9c) 5d) Compilation Error" }, { "code": null, "e": 786, "s": 692, "text": "Ans. (d)Explanation: static inner classes cannot access non-static fields of the outer class." }, { "code": null, "e": 834, "s": 786, "text": "2) What is the output of the following program?" }, { "code": "public class Outer { private static int data = 10; private static int LocalClass() { class Inner { public int data = 20; private int getData() { return data; } }; Inner inner = new Inner(); return inner.getData(); } public static void main(String[] args) { System.out.println(data * LocalClass()); }}", "e": 1263, "s": 834, "text": null }, { "code": null, "e": 1326, "s": 1263, "text": "a) Compilation errorb) Runtime Errorc) 200d) None of the above" }, { "code": null, "e": 1507, "s": 1326, "text": "Ans. (c)Explanation: LocalClass() method defines a local inner class. This method creates an object of class Inner and return the value of the variable data that resides within it." }, { "code": null, "e": 1555, "s": 1507, "text": "3) What is the output of the following program?" }, { "code": "interface Anonymous{ public int getValue();}public class Outer { private int data = 15; public static void main(String[] args) { Anonymous inner = new Anonymous() { int data = 5; public int getValue() { return data; } public int getData() { return data; } }; Outer outer = new Outer(); System.out.println(inner.getValue() + inner.getData() + outer.data); }}", "e": 2158, "s": 1555, "text": null }, { "code": null, "e": 2205, "s": 2158, "text": "a) 25b) Compilation errorc) 20d) Runtime error" }, { "code": null, "e": 2315, "s": 2205, "text": "Ans. (b)Explanation: the method getData() is undefined in Anonymous class which causes the compilation error." }, { "code": null, "e": 2368, "s": 2315, "text": "4) What is the output of the following java program?" }, { "code": "public class Outer{ private int data = 10; class Inner { private int data = 20; private int getData() { return data; } public void main(String[] args) { Inner inner = new Inner(); System.out.println(inner.getData()); } } private int getData() { return data; } public static void main(String[] args) { Outer outer = new Outer(); Outer.Inner inner = outer.new Inner(); System.out.printf(\"%d\", outer.getData()); inner.main(args); }}", "e": 2965, "s": 2368, "text": null }, { "code": null, "e": 3016, "s": 2965, "text": "a) 2010b) 1020c) Compilation Errord) None of these" }, { "code": null, "e": 3295, "s": 3016, "text": "Ans. (b)Explanation: Inner class defined above though, have access to the private variable data of the Outer class, but declaring a variable data inside an inner class makes it specific to the Inner class with no conflicts in term of variable declaration. For more see Shadowing" }, { "code": null, "e": 3343, "s": 3295, "text": "5) What is the output of the following program?" }, { "code": "interface OuterInterface{ public void InnerMethod(); public interface InnerInterface { public void InnerMethod(); }}public class Outer implements OuterInterface.InnerInterface, OuterInterface{ public void InnerMethod() { System.out.println(100); } public static void main(String[] args) { Outer obj = new Outer(); obj.InnerMethod(); }}", "e": 3749, "s": 3343, "text": null }, { "code": null, "e": 3812, "s": 3749, "text": "a) 100b) Compilation Errorc) Runtime Errord) None of the above" }, { "code": null, "e": 4004, "s": 3812, "text": "Ans. (a)Explanation: Nested Interfaces are defined in java. As both the interfaces has declaration of InnerMethod(), implementing it once works for both the InnerInterface and OuterInterface." }, { "code": null, "e": 4304, "s": 4004, "text": "This article is contributed by Mayank Kumar. 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": 4429, "s": 4304, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 4441, "s": 4429, "text": "Java-Output" }, { "code": null, "e": 4456, "s": 4441, "text": "Program Output" } ]
Spring – ApplicationContext
11 Jul, 2021 Spring IoC container is responsible for instantiating, wiring, configuring, and managing the entire life cycle of objects. BeanFactory and ApplicationContext represent the Spring IoC Containers. ApplicationContext is the sub-interface of BeanFactory. BeanFactory provides basic functionalities and is recommended to use for lightweight applications like mobile and applets. ApplicationContext provides basic features in addition to enterprise-specific functionalities which are as follows: Publishing events to registered listeners by resolving property files. Methods for accessing application components. Supports Internationalization. Loading File resources in a generic fashion. Note: It is because of these additional features, developers prefer to use ApplicationContext over BeanFactory. ApplicationContext Implementation Classes There are different types of Application containers provided by Spring for different requirements as listed below which later onwards are described alongside with declaration, at lastly providing an example to get through the implementation part with the pictorial aids. Containers are as follows: AnnotationConfigApplicationContext container AnnotationConfigWebApplicationContextXmlWebApplicationContext AnnotationConfigApplicationContext container AnnotationConfigWebApplicationContext XmlWebApplicationContext Container 1: AnnotationConfigApplicationContext AnnotationConfigApplicationContext class was introduced in Spring 3.0. It accepts classes annotated with @Configuration, @Component, and JSR-330 compliant classes. The constructor of AnnotationConfigApplicationContext accepts one or more classes. For example, in the below declaration, two Configuration classes Appconfig and AppConfig1 are passed as arguments to the constructor. The beans defined in later classes will override the same type and name beans in earlier classes when passed as arguments. For example, AppConfig and AppConfig1 have the same bean declaration. The bean defined in AppConfig1 overrides the bean in AppConfig. Syntax: Declaration ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class, AppConfig1.class); Note: Add the following to the properties file in the IDE to allow the spring to override beans. spring.main.allow-bean-definition-overriding=true Container 2: AnnotationConfigWebApplicationContext AnnotationConfigWebApplicationContext class was introduced in Spring 3.0. It is similar to AnnotationConfigApplicationContext for a web environment. It accepts classes annotated with @Configuration, @Component, and JSR-330 compliant classes. These classes can be registered via register() method or passing base packages to scan() method. This class may be used when we configure ContextLoaderListener servlet listener or a DispatcherServlet in a web.xml. From Spring 3.1, this class can be instantiated and injected to DispatcherServlet using java code by implementing WebApplicationInitializer, an alternative to web.xml. Example // Class // Implementing WebApplicationInitializer public class MyWebApplicationInitializer implements WebApplicationInitializer { // Servlet container public void onStartup(ServletContext container) throws ServletException { AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); context.register(AppConfig.class); context.setServletContext(container); // Servlet configuration } } Container 3: XmlWebApplicationContext Spring MVC Web-based application can be configured completely using XML or Java code. Configuring this container is similar to the AnnotationConfigWebApplicationContext container, which implies we can configure it in web.xml or using java code. // Class // Implementing WebApplicationInitializer public class MyXmlWebApplicationInitializer implements WebApplicationInitializer { // Servlet container public void onStartup(ServletContext container) throws ServletException { XmlWebApplicationContext context = new XmlWebApplicationContext(); context.setConfigLocation("/WEB-INF/spring/applicationContext.xml"); context.setServletContext(container); // Servlet configuration } } Container 4: FileSystemXmlApplicationContext FileSystemXmlApplicationContext is used to load XML-based Spring Configuration files from the file system or from URL. We can get the application context using Java code. It is useful for standalone environments and test harnesses. The following code shows how to create a container and use the XML as metadata information to load the beans. Illustration: String path = "Documents/demoProject/src/main/resources/applicationcontext/student-bean-config.xml"; ApplicationContext context = new FileSystemXmlApplicationContext(path); AccountService accountService = context.getBean("studentService", StudentService.class); Container 5: ClassPathXmlApplicationContext FileSystemXmlApplicationContext is used to load XML-based Spring Configuration files from the classpath. We can get the application context using Java code. It is useful for standalone environments and test harnesses. The following code shows how to create a container and use the XML as metadata information to load the beans. Illustration: ApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext/student-bean-config.xml"); StudentService studentService = context.getBean("studentService", StudentService.class); Now, let us implement the same showcasing an example which is as follows: Implementation: Create a Spring Project using Spring Initializer. Create Student class under com.gfg.demo.domain Similarly, AppConfig class under com.gfg.demo.config packages. The main application class at the root contains the creation of a container. Lastly, the SpringApplication.run() method is provided by default in the main class when the SpringBoot project is created. Example Step 1: Creating a Spring Project using Spring Initializer as pictorially depicted below. Step 2: Create Student class under com.gfg.demo.domain and AppConfig class under com.gfg.demo.config packages. The AppConfig is the configuration class that contains all the Java beans configured using Java Based Configuration. The Student class is the POJO class. Class 1: AppConfig class @Configuration // Class public class AppConfig { @Bean // Method public Student student() { return new Student(1, "Geek"); } } Class 2: Student class // Class public class Student { // member variables private int id; private String name; // Constructor 1 public Student() {} // Constructor 2 public Student(int id, String name) { this.id = id; this.name = name; } // Method of this class // @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + '}'; } } Step 3: Now the Main Application class at the root contains the creation of a container. // Class // @SpringBootApplication public class DemoApplication { // Main driver method public static void main(String[] args) { // SpringApplication.run(DemoApplication.class, args); // Creating its object ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); Student student = context.getBean(Student.class); // Print and display System.out.println(student); } } Step 4: The SpringApplication.run() method is provided by default in the main class when the SpringBoot project is created. It creates the container, creates beans, manages dependency injection and life cycle of those beans. This is done using @SpringBootApplication annotation. // Main driver method public static void main(String[] args) { ApplicationContext context = SpringApplication.run(DemoApplication.class, args); Student student = context.getBean(Student.class); // Print adn display System.out.println(student); } Java-Spring Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n11 Jul, 2021" }, { "code": null, "e": 543, "s": 53, "text": "Spring IoC container is responsible for instantiating, wiring, configuring, and managing the entire life cycle of objects. BeanFactory and ApplicationContext represent the Spring IoC Containers. ApplicationContext is the sub-interface of BeanFactory. BeanFactory provides basic functionalities and is recommended to use for lightweight applications like mobile and applets. ApplicationContext provides basic features in addition to enterprise-specific functionalities which are as follows:" }, { "code": null, "e": 614, "s": 543, "text": "Publishing events to registered listeners by resolving property files." }, { "code": null, "e": 660, "s": 614, "text": "Methods for accessing application components." }, { "code": null, "e": 691, "s": 660, "text": "Supports Internationalization." }, { "code": null, "e": 736, "s": 691, "text": "Loading File resources in a generic fashion." }, { "code": null, "e": 849, "s": 736, "text": "Note: It is because of these additional features, developers prefer to use ApplicationContext over BeanFactory. " }, { "code": null, "e": 891, "s": 849, "text": "ApplicationContext Implementation Classes" }, { "code": null, "e": 1189, "s": 891, "text": "There are different types of Application containers provided by Spring for different requirements as listed below which later onwards are described alongside with declaration, at lastly providing an example to get through the implementation part with the pictorial aids. Containers are as follows:" }, { "code": null, "e": 1296, "s": 1189, "text": "AnnotationConfigApplicationContext container AnnotationConfigWebApplicationContextXmlWebApplicationContext" }, { "code": null, "e": 1342, "s": 1296, "text": "AnnotationConfigApplicationContext container " }, { "code": null, "e": 1380, "s": 1342, "text": "AnnotationConfigWebApplicationContext" }, { "code": null, "e": 1405, "s": 1380, "text": "XmlWebApplicationContext" }, { "code": null, "e": 1453, "s": 1405, "text": "Container 1: AnnotationConfigApplicationContext" }, { "code": null, "e": 2091, "s": 1453, "text": "AnnotationConfigApplicationContext class was introduced in Spring 3.0. It accepts classes annotated with @Configuration, @Component, and JSR-330 compliant classes. The constructor of AnnotationConfigApplicationContext accepts one or more classes. For example, in the below declaration, two Configuration classes Appconfig and AppConfig1 are passed as arguments to the constructor. The beans defined in later classes will override the same type and name beans in earlier classes when passed as arguments. For example, AppConfig and AppConfig1 have the same bean declaration. The bean defined in AppConfig1 overrides the bean in AppConfig." }, { "code": null, "e": 2111, "s": 2091, "text": "Syntax: Declaration" }, { "code": null, "e": 2215, "s": 2111, "text": "ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class, AppConfig1.class);" }, { "code": null, "e": 2312, "s": 2215, "text": "Note: Add the following to the properties file in the IDE to allow the spring to override beans." }, { "code": null, "e": 2362, "s": 2312, "text": "spring.main.allow-bean-definition-overriding=true" }, { "code": null, "e": 2413, "s": 2362, "text": "Container 2: AnnotationConfigWebApplicationContext" }, { "code": null, "e": 3037, "s": 2413, "text": "AnnotationConfigWebApplicationContext class was introduced in Spring 3.0. It is similar to AnnotationConfigApplicationContext for a web environment. It accepts classes annotated with @Configuration, @Component, and JSR-330 compliant classes. These classes can be registered via register() method or passing base packages to scan() method. This class may be used when we configure ContextLoaderListener servlet listener or a DispatcherServlet in a web.xml. From Spring 3.1, this class can be instantiated and injected to DispatcherServlet using java code by implementing WebApplicationInitializer, an alternative to web.xml." }, { "code": null, "e": 3046, "s": 3037, "text": "Example " }, { "code": null, "e": 3492, "s": 3046, "text": "// Class\n// Implementing WebApplicationInitializer\npublic class MyWebApplicationInitializer implements WebApplicationInitializer {\n\n // Servlet container\n\n public void onStartup(ServletContext container) throws ServletException {\n AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();\n context.register(AppConfig.class);\n context.setServletContext(container);\n\n // Servlet configuration\n }\n}" }, { "code": null, "e": 3530, "s": 3492, "text": "Container 3: XmlWebApplicationContext" }, { "code": null, "e": 3775, "s": 3530, "text": "Spring MVC Web-based application can be configured completely using XML or Java code. Configuring this container is similar to the AnnotationConfigWebApplicationContext container, which implies we can configure it in web.xml or using java code." }, { "code": null, "e": 4231, "s": 3775, "text": "// Class\n// Implementing WebApplicationInitializer\npublic class MyXmlWebApplicationInitializer implements WebApplicationInitializer {\n\n // Servlet container\n public void onStartup(ServletContext container) throws ServletException {\n XmlWebApplicationContext context = new XmlWebApplicationContext();\n context.setConfigLocation(\"/WEB-INF/spring/applicationContext.xml\");\n context.setServletContext(container);\n\n // Servlet configuration\n }\n}" }, { "code": null, "e": 4276, "s": 4231, "text": "Container 4: FileSystemXmlApplicationContext" }, { "code": null, "e": 4618, "s": 4276, "text": "FileSystemXmlApplicationContext is used to load XML-based Spring Configuration files from the file system or from URL. We can get the application context using Java code. It is useful for standalone environments and test harnesses. The following code shows how to create a container and use the XML as metadata information to load the beans." }, { "code": null, "e": 4632, "s": 4618, "text": "Illustration:" }, { "code": null, "e": 4895, "s": 4632, "text": "String path = \"Documents/demoProject/src/main/resources/applicationcontext/student-bean-config.xml\";\n\nApplicationContext context = new FileSystemXmlApplicationContext(path);\nAccountService accountService = context.getBean(\"studentService\", StudentService.class);" }, { "code": null, "e": 4939, "s": 4895, "text": "Container 5: ClassPathXmlApplicationContext" }, { "code": null, "e": 5267, "s": 4939, "text": "FileSystemXmlApplicationContext is used to load XML-based Spring Configuration files from the classpath. We can get the application context using Java code. It is useful for standalone environments and test harnesses. The following code shows how to create a container and use the XML as metadata information to load the beans." }, { "code": null, "e": 5281, "s": 5267, "text": "Illustration:" }, { "code": null, "e": 5481, "s": 5281, "text": "ApplicationContext context = new ClassPathXmlApplicationContext(\"applicationcontext/student-bean-config.xml\");\nStudentService studentService = context.getBean(\"studentService\", StudentService.class);" }, { "code": null, "e": 5555, "s": 5481, "text": "Now, let us implement the same showcasing an example which is as follows:" }, { "code": null, "e": 5571, "s": 5555, "text": "Implementation:" }, { "code": null, "e": 5622, "s": 5571, "text": "Create a Spring Project using Spring Initializer. " }, { "code": null, "e": 5669, "s": 5622, "text": "Create Student class under com.gfg.demo.domain" }, { "code": null, "e": 5732, "s": 5669, "text": "Similarly, AppConfig class under com.gfg.demo.config packages." }, { "code": null, "e": 5809, "s": 5732, "text": "The main application class at the root contains the creation of a container." }, { "code": null, "e": 5933, "s": 5809, "text": "Lastly, the SpringApplication.run() method is provided by default in the main class when the SpringBoot project is created." }, { "code": null, "e": 5941, "s": 5933, "text": "Example" }, { "code": null, "e": 6031, "s": 5941, "text": "Step 1: Creating a Spring Project using Spring Initializer as pictorially depicted below." }, { "code": null, "e": 6296, "s": 6031, "text": "Step 2: Create Student class under com.gfg.demo.domain and AppConfig class under com.gfg.demo.config packages. The AppConfig is the configuration class that contains all the Java beans configured using Java Based Configuration. The Student class is the POJO class." }, { "code": null, "e": 6321, "s": 6296, "text": "Class 1: AppConfig class" }, { "code": null, "e": 6464, "s": 6321, "text": "@Configuration\n\n// Class\npublic class AppConfig {\n\n @Bean\n\n // Method\n public Student student() {\n\n return new Student(1, \"Geek\");\n }\n}" }, { "code": null, "e": 6487, "s": 6464, "text": "Class 2: Student class" }, { "code": null, "e": 6876, "s": 6487, "text": "// Class\npublic class Student {\n\n // member variables\n private int id;\n private String name;\n\n // Constructor 1\n public Student() {}\n\n // Constructor 2\n public Student(int id, String name) {\n this.id = id;\n this.name = name;\n }\n\n // Method of this class\n // @Override\n public String toString() {\n\n return \"Student{\" + \"id=\" + id + \", name='\" + name + '\\'' + '}';\n }\n}" }, { "code": null, "e": 6965, "s": 6876, "text": "Step 3: Now the Main Application class at the root contains the creation of a container." }, { "code": null, "e": 7396, "s": 6965, "text": "// Class\n// @SpringBootApplication\npublic class DemoApplication {\n\n // Main driver method\n public static void main(String[] args) {\n\n // SpringApplication.run(DemoApplication.class, args);\n\n // Creating its object\n ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);\n Student student = context.getBean(Student.class);\n\n // Print and display\n System.out.println(student);\n }\n}" }, { "code": null, "e": 7675, "s": 7396, "text": "Step 4: The SpringApplication.run() method is provided by default in the main class when the SpringBoot project is created. It creates the container, creates beans, manages dependency injection and life cycle of those beans. This is done using @SpringBootApplication annotation." }, { "code": null, "e": 7932, "s": 7675, "text": "// Main driver method\npublic static void main(String[] args) {\n\n ApplicationContext context = SpringApplication.run(DemoApplication.class, args);\n\n Student student = context.getBean(Student.class);\n\n // Print adn display\n System.out.println(student);\n}" }, { "code": null, "e": 7944, "s": 7932, "text": "Java-Spring" }, { "code": null, "e": 7949, "s": 7944, "text": "Java" }, { "code": null, "e": 7954, "s": 7949, "text": "Java" } ]
Working of Express.js middleware and its benefits
17 Jun, 2021 Framework: It is known to be a skeleton where the application defines the content of the operation by filling out the skeleton. For Web development, there is python with Django, java with spring, and For Web development in we have Node.js with Express.js in node.js there is an HTTP module by which we can create an only limited operatable website or web application. In general, the real working of any web application or website is that it is capable to handle any kind of request. Requests may be post, get, delete, and many more like a request for an image, video, etc that’s why Express.js is used as a Framework for Node.js. Express.js is a routing and Middleware framework for handling the different routing of the webpage and it works between the request and response cycle. There are lots of middleware functions in Express.js like Express.js app.use() Function etc. Syntax: app.use(path,(req,res,next)) Parameters: It accepts the two parameters as mentioned above and described below: path: It is the path for which the middleware function is being called. It can be a string representing a path or path pattern or a regular expression pattern to match the paths. callback: It is the callback function that contains the request object, response object, and next() function to call the next middleware function if the response of current middleware is not terminated. In the second parameter, we can also pass the function name of the middleware. 1. We generally use http.createServer() to create a server and performs request and response according to the information, but we cannot check what type of request made by the client so that we can perform operations according to the request. 2. Express.js contains multiple methods to handle all types of requests rather than work on a single type of request as shown below: Express.js req.get() Method: This method is used when get request is done by the client for eg: Redirecting another webpage requests etc Express.js req.post() Method: This method is used when post requests are done by the client for eg uploading documents etc. Express.js req.delete() Method: This method is used when a delete request is done by the client it is mainly done by the admin end for e.g. deleting the records from the server. Express.js req.put() Method: This method is used when update requests are done by the client to update the information over the website. 3. Easy to connect with databases such as MongoDB, MySQL. 4. Easy to serve static files and resources we can easily serve HTML documents using express.js. 5. There are several other benefits of using Express.js like handling multiple get requests on a single webpage that means Allows you to define multiple routes of your application based on HTTP methods and URLs. Project structure: Installing Module: Install the express module using the following command: npm install express Filename: Index.js Javascript // Requiring moduleconst express = require("express"); // Creating express app objectconst app = express(); // Handling '/' routeapp.get("/", (req,res,next) => { res.send("unknown request");}) // Handling '/GFG' route app.get("/GFG", (req,res,next) => { res.send("Getting request of GFG");}) // Handling '/Hello' routeapp.get("/Hello", (req,res,next) => { res.send("Getting request of the Hello");}) // Server setupapp.listen(3000, () => { console.log("Server is Running");}) Run the index.js file using the following command: node index.js Command to run the project Output: Now open your browser and go to http://localhost:3000/GFG, you can see the following output: Now go to http://localhost:3000/hello you can see the following output: Note: Handling Multiple requests using the HTTP module by default is a get request. This method cannot be used for multiple handling requests. If we use the HTTP module for handling multiple get requests it requires more length of code and multiple if-else conditions to handle the different routes. Filename: Index.js Javascript // Requiring modulevar http = require('http'); // Create a server objecthttp.createServer(function (req, res) { // The http header res.writeHead(200, {'Content-Type': 'text/html'}); // Getting URL from the request object var url = req.url; // Checking url if(url === '/GFG') { res.send("Getting request of GFG"); res.end(); } else if(url === '/hello') { res.send("Getting request of the Hello"); res.end(); } else { res.send("unknown request"); res.end(); } }).listen(3000, function() { // The server object listens on port 3000 console.log("server start at port 3000");}); Filename: index.js Javascript // Requiring moduleconst express = require("express"); const app = express(); // Middleware 1function Middleware1(req,res,next) { console.log("I am Middleware 1"); // Calling the next middleware present in stack next(); } // Middleware 2function Middleware2(req,res,next) { res.write("<h1>Express.js GFG<h1>") // Printing the statement console.log("I am Middleware 2"); // Ending the response res.end(); } // Request handlingapp.get("/", Middleware1, Middleware2); // Server setupapp.listen(3000, () => { console.log("Server is Running");}) Output: Now open your browser, you will see the following output: The following will be the output on your terminal screen: The express.static() middleware is the of the express.js module is used for serving the HTML static documents. The benefit of using it automatically fetches the name of the HTML document present in the particular directory. Project structure: Filename: index.html HTML <!DOCTYPE html><html> <head> <style> /* Assign full width inputs */ input[type=text], input[type=password] { width: 100%; padding: 12px 20px; margin: 8px 0; display: inline-block; border: 1px solid #ccc; box-sizing: border-box; } /* Set a style for the buttons */ button { background-color: #4CAF50; color: white; padding: 14px 20px; margin: 8px 0; border: none; cursor: pointer; width: 100%; } /* Set a hover effect for the button */ button:hover { opacity: 0.8; } /* Set extra style for the cancel button */ .cancelbtn { width: auto; padding: 10px 18px; background-color: #f44336; } /* Centre the display image inside the container */ .imgcontainer { text-align: center; margin: 24px 0 12px 0; position: relative; } /* Set image properties */ img.avatar { width: 40%; border-radius: 50%; } /* Set padding to the container */ .container { padding: 16px; } /* Set the forgot password text */ span.psw { float: right; padding-top: 16px; } /* Set the Modal background */ .modal { display: none; position: fixed; z-index: 1; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgb(0, 0, 0); background-color: rgba(0, 0, 0, 0.4); padding-top: 60px; } /* Style the model content box */ .modal-content { background-color: #fefefe; margin: 5% auto 15% auto; border: 1px solid #888; width: 80%; } /* Style the close button */ .close { position: absolute; right: 25px; top: 0; color: #000; font-size: 35px; font-weight: bold; } .close:hover, .close:focus { color: red; cursor: pointer; } /* Add zoom animation */ .animate { -webkit-animation: animatezoom 0.6s; animation: animatezoom 0.6s } @-webkit-keyframes animatezoom { from { -webkit-transform: scale(0) } to { -webkit-transform: scale(1) } } @keyframes animatezoom { from { transform: scale(0) } to { transform: scale(1) } } @media screen and (max-width: 300px) { span.psw { display: block; float: none; } .cancelbtn { width: 100%; } } </style></head> <body> <h2>Modal Login Form</h2> <button onclick="document.getElementById('id01') .style.display='block'" style="width:auto;"> Login </button> <div id="id01" class="modal"> <form class="modal-content animate" action="/action_page.php"> <div class="imgcontainer"> <span onclick="document .getElementById('id01').style .display='none'" class="close" title="Close Modal"> × </span> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" alt="Avatar" class="avatar"> </div> <div class="container"> <label><b>Username</b></label> <input type="text" placeholder= "Enter Username" name="uname" required> <label><b>Password</b></label> <input type="password" placeholder= "Enter Password" name="psw" required> <button type="submit">Login</button> <input type="checkbox" checked="checked"> Remember me </div> <div class="container" style= "background-color:#f1f1f1"> <button type="button" onclick= "document.getElementById('id01') .style.display='none'" class="cancelbtn"> Cancel </button> <span class="psw">Forgot <a href="#"> password? </a></span> </div> </form> </div> <script> var modal = document.getElementById('id01'); window.onclick = function (event) { if (event.target == modal) { modal.style.display = "none"; } } </script></body> </html> Filename: app.js Javascript // Requiring moduleconst express = require("express");const app = express();const path = require("path"); // Middlewareapp.use(express.static(__dirname+"/public")); // Handling requestapp.get("/", (req,res,next) => { res.write("GFG"); res.end();}) // Server setupapp.listen((3000), () => { console.log("Server is Running");}) Run the app.js file using the following command: node app.js Output: sagar0719kumar Express.js HTML-Misc Technical Scripter 2020 Node.js Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Jun, 2021" }, { "code": null, "e": 686, "s": 54, "text": "Framework: It is known to be a skeleton where the application defines the content of the operation by filling out the skeleton. For Web development, there is python with Django, java with spring, and For Web development in we have Node.js with Express.js in node.js there is an HTTP module by which we can create an only limited operatable website or web application. In general, the real working of any web application or website is that it is capable to handle any kind of request. Requests may be post, get, delete, and many more like a request for an image, video, etc that’s why Express.js is used as a Framework for Node.js. " }, { "code": null, "e": 838, "s": 686, "text": "Express.js is a routing and Middleware framework for handling the different routing of the webpage and it works between the request and response cycle." }, { "code": null, "e": 932, "s": 838, "text": "There are lots of middleware functions in Express.js like Express.js app.use() Function etc. " }, { "code": null, "e": 940, "s": 932, "text": "Syntax:" }, { "code": null, "e": 969, "s": 940, "text": "app.use(path,(req,res,next))" }, { "code": null, "e": 1051, "s": 969, "text": "Parameters: It accepts the two parameters as mentioned above and described below:" }, { "code": null, "e": 1230, "s": 1051, "text": "path: It is the path for which the middleware function is being called. It can be a string representing a path or path pattern or a regular expression pattern to match the paths." }, { "code": null, "e": 1512, "s": 1230, "text": "callback: It is the callback function that contains the request object, response object, and next() function to call the next middleware function if the response of current middleware is not terminated. In the second parameter, we can also pass the function name of the middleware." }, { "code": null, "e": 1756, "s": 1512, "text": "1. We generally use http.createServer() to create a server and performs request and response according to the information, but we cannot check what type of request made by the client so that we can perform operations according to the request. " }, { "code": null, "e": 1889, "s": 1756, "text": "2. Express.js contains multiple methods to handle all types of requests rather than work on a single type of request as shown below:" }, { "code": null, "e": 2026, "s": 1889, "text": "Express.js req.get() Method: This method is used when get request is done by the client for eg: Redirecting another webpage requests etc" }, { "code": null, "e": 2150, "s": 2026, "text": "Express.js req.post() Method: This method is used when post requests are done by the client for eg uploading documents etc." }, { "code": null, "e": 2328, "s": 2150, "text": "Express.js req.delete() Method: This method is used when a delete request is done by the client it is mainly done by the admin end for e.g. deleting the records from the server." }, { "code": null, "e": 2465, "s": 2328, "text": "Express.js req.put() Method: This method is used when update requests are done by the client to update the information over the website." }, { "code": null, "e": 2523, "s": 2465, "text": "3. Easy to connect with databases such as MongoDB, MySQL." }, { "code": null, "e": 2620, "s": 2523, "text": "4. Easy to serve static files and resources we can easily serve HTML documents using express.js." }, { "code": null, "e": 2832, "s": 2620, "text": "5. There are several other benefits of using Express.js like handling multiple get requests on a single webpage that means Allows you to define multiple routes of your application based on HTTP methods and URLs." }, { "code": null, "e": 2851, "s": 2832, "text": "Project structure:" }, { "code": null, "e": 2870, "s": 2851, "text": "Installing Module:" }, { "code": null, "e": 2926, "s": 2870, "text": "Install the express module using the following command:" }, { "code": null, "e": 2946, "s": 2926, "text": "npm install express" }, { "code": null, "e": 2965, "s": 2946, "text": "Filename: Index.js" }, { "code": null, "e": 2976, "s": 2965, "text": "Javascript" }, { "code": "// Requiring moduleconst express = require(\"express\"); // Creating express app objectconst app = express(); // Handling '/' routeapp.get(\"/\", (req,res,next) => { res.send(\"unknown request\");}) // Handling '/GFG' route app.get(\"/GFG\", (req,res,next) => { res.send(\"Getting request of GFG\");}) // Handling '/Hello' routeapp.get(\"/Hello\", (req,res,next) => { res.send(\"Getting request of the Hello\");}) // Server setupapp.listen(3000, () => { console.log(\"Server is Running\");})", "e": 3462, "s": 2976, "text": null }, { "code": null, "e": 3513, "s": 3462, "text": "Run the index.js file using the following command:" }, { "code": null, "e": 3527, "s": 3513, "text": "node index.js" }, { "code": null, "e": 3554, "s": 3527, "text": "Command to run the project" }, { "code": null, "e": 3562, "s": 3554, "text": "Output:" }, { "code": null, "e": 3655, "s": 3562, "text": "Now open your browser and go to http://localhost:3000/GFG, you can see the following output:" }, { "code": null, "e": 3727, "s": 3655, "text": "Now go to http://localhost:3000/hello you can see the following output:" }, { "code": null, "e": 4027, "s": 3727, "text": "Note: Handling Multiple requests using the HTTP module by default is a get request. This method cannot be used for multiple handling requests. If we use the HTTP module for handling multiple get requests it requires more length of code and multiple if-else conditions to handle the different routes." }, { "code": null, "e": 4046, "s": 4027, "text": "Filename: Index.js" }, { "code": null, "e": 4057, "s": 4046, "text": "Javascript" }, { "code": "// Requiring modulevar http = require('http'); // Create a server objecthttp.createServer(function (req, res) { // The http header res.writeHead(200, {'Content-Type': 'text/html'}); // Getting URL from the request object var url = req.url; // Checking url if(url === '/GFG') { res.send(\"Getting request of GFG\"); res.end(); } else if(url === '/hello') { res.send(\"Getting request of the Hello\"); res.end(); } else { res.send(\"unknown request\"); res.end(); } }).listen(3000, function() { // The server object listens on port 3000 console.log(\"server start at port 3000\");});", "e": 4708, "s": 4057, "text": null }, { "code": null, "e": 4727, "s": 4708, "text": "Filename: index.js" }, { "code": null, "e": 4738, "s": 4727, "text": "Javascript" }, { "code": "// Requiring moduleconst express = require(\"express\"); const app = express(); // Middleware 1function Middleware1(req,res,next) { console.log(\"I am Middleware 1\"); // Calling the next middleware present in stack next(); } // Middleware 2function Middleware2(req,res,next) { res.write(\"<h1>Express.js GFG<h1>\") // Printing the statement console.log(\"I am Middleware 2\"); // Ending the response res.end(); } // Request handlingapp.get(\"/\", Middleware1, Middleware2); // Server setupapp.listen(3000, () => { console.log(\"Server is Running\");})", "e": 5311, "s": 4738, "text": null }, { "code": null, "e": 5322, "s": 5314, "text": "Output:" }, { "code": null, "e": 5382, "s": 5324, "text": "Now open your browser, you will see the following output:" }, { "code": null, "e": 5442, "s": 5384, "text": "The following will be the output on your terminal screen:" }, { "code": null, "e": 5668, "s": 5444, "text": "The express.static() middleware is the of the express.js module is used for serving the HTML static documents. The benefit of using it automatically fetches the name of the HTML document present in the particular directory." }, { "code": null, "e": 5689, "s": 5670, "text": "Project structure:" }, { "code": null, "e": 5712, "s": 5691, "text": "Filename: index.html" }, { "code": null, "e": 5719, "s": 5714, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> /* Assign full width inputs */ input[type=text], input[type=password] { width: 100%; padding: 12px 20px; margin: 8px 0; display: inline-block; border: 1px solid #ccc; box-sizing: border-box; } /* Set a style for the buttons */ button { background-color: #4CAF50; color: white; padding: 14px 20px; margin: 8px 0; border: none; cursor: pointer; width: 100%; } /* Set a hover effect for the button */ button:hover { opacity: 0.8; } /* Set extra style for the cancel button */ .cancelbtn { width: auto; padding: 10px 18px; background-color: #f44336; } /* Centre the display image inside the container */ .imgcontainer { text-align: center; margin: 24px 0 12px 0; position: relative; } /* Set image properties */ img.avatar { width: 40%; border-radius: 50%; } /* Set padding to the container */ .container { padding: 16px; } /* Set the forgot password text */ span.psw { float: right; padding-top: 16px; } /* Set the Modal background */ .modal { display: none; position: fixed; z-index: 1; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgb(0, 0, 0); background-color: rgba(0, 0, 0, 0.4); padding-top: 60px; } /* Style the model content box */ .modal-content { background-color: #fefefe; margin: 5% auto 15% auto; border: 1px solid #888; width: 80%; } /* Style the close button */ .close { position: absolute; right: 25px; top: 0; color: #000; font-size: 35px; font-weight: bold; } .close:hover, .close:focus { color: red; cursor: pointer; } /* Add zoom animation */ .animate { -webkit-animation: animatezoom 0.6s; animation: animatezoom 0.6s } @-webkit-keyframes animatezoom { from { -webkit-transform: scale(0) } to { -webkit-transform: scale(1) } } @keyframes animatezoom { from { transform: scale(0) } to { transform: scale(1) } } @media screen and (max-width: 300px) { span.psw { display: block; float: none; } .cancelbtn { width: 100%; } } </style></head> <body> <h2>Modal Login Form</h2> <button onclick=\"document.getElementById('id01') .style.display='block'\" style=\"width:auto;\"> Login </button> <div id=\"id01\" class=\"modal\"> <form class=\"modal-content animate\" action=\"/action_page.php\"> <div class=\"imgcontainer\"> <span onclick=\"document .getElementById('id01').style .display='none'\" class=\"close\" title=\"Close Modal\"> × </span> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\" alt=\"Avatar\" class=\"avatar\"> </div> <div class=\"container\"> <label><b>Username</b></label> <input type=\"text\" placeholder= \"Enter Username\" name=\"uname\" required> <label><b>Password</b></label> <input type=\"password\" placeholder= \"Enter Password\" name=\"psw\" required> <button type=\"submit\">Login</button> <input type=\"checkbox\" checked=\"checked\"> Remember me </div> <div class=\"container\" style= \"background-color:#f1f1f1\"> <button type=\"button\" onclick= \"document.getElementById('id01') .style.display='none'\" class=\"cancelbtn\"> Cancel </button> <span class=\"psw\">Forgot <a href=\"#\"> password? </a></span> </div> </form> </div> <script> var modal = document.getElementById('id01'); window.onclick = function (event) { if (event.target == modal) { modal.style.display = \"none\"; } } </script></body> </html>", "e": 10802, "s": 5719, "text": null }, { "code": null, "e": 10819, "s": 10802, "text": "Filename: app.js" }, { "code": null, "e": 10830, "s": 10819, "text": "Javascript" }, { "code": "// Requiring moduleconst express = require(\"express\");const app = express();const path = require(\"path\"); // Middlewareapp.use(express.static(__dirname+\"/public\")); // Handling requestapp.get(\"/\", (req,res,next) => { res.write(\"GFG\"); res.end();}) // Server setupapp.listen((3000), () => { console.log(\"Server is Running\");})", "e": 11165, "s": 10830, "text": null }, { "code": null, "e": 11217, "s": 11168, "text": "Run the app.js file using the following command:" }, { "code": null, "e": 11231, "s": 11219, "text": "node app.js" }, { "code": null, "e": 11239, "s": 11231, "text": "Output:" }, { "code": null, "e": 11258, "s": 11243, "text": "sagar0719kumar" }, { "code": null, "e": 11269, "s": 11258, "text": "Express.js" }, { "code": null, "e": 11279, "s": 11269, "text": "HTML-Misc" }, { "code": null, "e": 11303, "s": 11279, "text": "Technical Scripter 2020" }, { "code": null, "e": 11311, "s": 11303, "text": "Node.js" }, { "code": null, "e": 11330, "s": 11311, "text": "Technical Scripter" }, { "code": null, "e": 11347, "s": 11330, "text": "Web Technologies" } ]
C# | Add an object to the end of the ArrayList
01 Feb, 2019 ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.Add(Object) method adds an object to the end of the ArrayList. Properties of ArrayList Class: Elements can be added or removed from the Array List collection at any point in time. The ArrayList is not guaranteed to be sorted. The capacity of an ArrayList is the number of elements the ArrayList can hold. Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based. It also allows duplicate elements. Using multidimensional arrays as elements in an ArrayList collection is not supported. Syntax: public virtual int Add (object value); Here, value is the Object to be added to the end of the ArrayList. The value can be null. Return Value: This method returns the ArrayList index at which the value has been added. Exception: This method will give NotSupportedException if the ArrayList is either read-only or fixed size. Below are the programs to illustrate the use of ArrayList.Add(Object) Method: Example 1: // C# code to add an object to// the end of the ArrayListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating an ArrayList ArrayList myList = new ArrayList(); // Adding elements to ArrayList myList.Add("A"); myList.Add("B"); myList.Add("C"); myList.Add("D"); myList.Add("E"); myList.Add("F"); // Displaying the elements in the ArrayList foreach(string str in myList) { Console.WriteLine(str); } }} A B C D E F Example 2: // C# code to add an object to// the end of the ArrayListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating an ArrayList ArrayList myList = new ArrayList(); // Adding elements to ArrayList myList.Add(1); myList.Add(2); myList.Add(3); myList.Add(4); myList.Add(5); myList.Add(6); // Displaying the elements in the ArrayList foreach(int i in myList) { Console.WriteLine(i); } }} 1 2 3 4 5 6 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.add?view=netframework-4.7.2 CSharp-Collections-ArrayList CSharp-Collections-Namespace CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Feb, 2019" }, { "code": null, "e": 326, "s": 28, "text": "ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.Add(Object) method adds an object to the end of the ArrayList." }, { "code": null, "e": 357, "s": 326, "text": "Properties of ArrayList Class:" }, { "code": null, "e": 443, "s": 357, "text": "Elements can be added or removed from the Array List collection at any point in time." }, { "code": null, "e": 489, "s": 443, "text": "The ArrayList is not guaranteed to be sorted." }, { "code": null, "e": 568, "s": 489, "text": "The capacity of an ArrayList is the number of elements the ArrayList can hold." }, { "code": null, "e": 679, "s": 568, "text": "Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based." }, { "code": null, "e": 714, "s": 679, "text": "It also allows duplicate elements." }, { "code": null, "e": 801, "s": 714, "text": "Using multidimensional arrays as elements in an ArrayList collection is not supported." }, { "code": null, "e": 809, "s": 801, "text": "Syntax:" }, { "code": null, "e": 849, "s": 809, "text": "public virtual int Add (object value);\n" }, { "code": null, "e": 939, "s": 849, "text": "Here, value is the Object to be added to the end of the ArrayList. The value can be null." }, { "code": null, "e": 1028, "s": 939, "text": "Return Value: This method returns the ArrayList index at which the value has been added." }, { "code": null, "e": 1135, "s": 1028, "text": "Exception: This method will give NotSupportedException if the ArrayList is either read-only or fixed size." }, { "code": null, "e": 1213, "s": 1135, "text": "Below are the programs to illustrate the use of ArrayList.Add(Object) Method:" }, { "code": null, "e": 1224, "s": 1213, "text": "Example 1:" }, { "code": "// C# code to add an object to// the end of the ArrayListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating an ArrayList ArrayList myList = new ArrayList(); // Adding elements to ArrayList myList.Add(\"A\"); myList.Add(\"B\"); myList.Add(\"C\"); myList.Add(\"D\"); myList.Add(\"E\"); myList.Add(\"F\"); // Displaying the elements in the ArrayList foreach(string str in myList) { Console.WriteLine(str); } }}", "e": 1831, "s": 1224, "text": null }, { "code": null, "e": 1844, "s": 1831, "text": "A\nB\nC\nD\nE\nF\n" }, { "code": null, "e": 1855, "s": 1844, "text": "Example 2:" }, { "code": "// C# code to add an object to// the end of the ArrayListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating an ArrayList ArrayList myList = new ArrayList(); // Adding elements to ArrayList myList.Add(1); myList.Add(2); myList.Add(3); myList.Add(4); myList.Add(5); myList.Add(6); // Displaying the elements in the ArrayList foreach(int i in myList) { Console.WriteLine(i); } }}", "e": 2443, "s": 1855, "text": null }, { "code": null, "e": 2456, "s": 2443, "text": "1\n2\n3\n4\n5\n6\n" }, { "code": null, "e": 2467, "s": 2456, "text": "Reference:" }, { "code": null, "e": 2568, "s": 2467, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.add?view=netframework-4.7.2" }, { "code": null, "e": 2597, "s": 2568, "text": "CSharp-Collections-ArrayList" }, { "code": null, "e": 2626, "s": 2597, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 2640, "s": 2626, "text": "CSharp-method" }, { "code": null, "e": 2643, "s": 2640, "text": "C#" } ]
How to check caps lock is on/off using JavaScript / jQuery ?
29 May, 2019 The job is to determine the caps lock is turned on or turned off using JavaScript and jQuery. Check caps lock is on/off using JavaScript: addEventListener() Method: This method adds an event handler to the document.Syntax:document.addEventListener(event, function, useCapture) Parameters:event: This parameter is required. It specifies the string, the name of the event.function: This parameter is required. It specifies the function to run when the event occurs. When the event occurs, an event object is passed as the first parameter to the function. The type depends on the specified event. For example, the “click” event belongs to the MouseEvent object.useCapture: This parameter is optional. It specifies a boolean value which means whether the event should be executed in the capturing or in the bubbling phase.true: The event handler is executed in the capturing phase.false: The event handler is executed in the bubbling phase. Syntax: document.addEventListener(event, function, useCapture) Parameters: event: This parameter is required. It specifies the string, the name of the event. function: This parameter is required. It specifies the function to run when the event occurs. When the event occurs, an event object is passed as the first parameter to the function. The type depends on the specified event. For example, the “click” event belongs to the MouseEvent object. useCapture: This parameter is optional. It specifies a boolean value which means whether the event should be executed in the capturing or in the bubbling phase.true: The event handler is executed in the capturing phase.false: The event handler is executed in the bubbling phase. true: The event handler is executed in the capturing phase. false: The event handler is executed in the bubbling phase. Example 1: This example adds a event listener to the document and when it happens it calls an anonymous function to handle this. Which checks if it CAPS LOCK or SHIFT key by using keyCode of the button. <!DOCTYPE HTML> <html> <head> <title> Check caps lock is on or not </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); up.innerHTML = "Type anywhere on the page to check if CAPS LOCK is ON"; var down = document.getElementById('GFG_DOWN'); document.addEventListener('keypress', function(e) { e = (e) ? e : window.event; var charCode = false; if (e.which) { charCode = e.which; } else if (e.keyCode) { charCode = e.keyCode; } var shifton = false; if (e.shiftKey) { shifton = e.shiftKey; } else if (e.modifiers) { shifton = !!(e.modifiers & 4); } if (charCode >= 97 && charCode <= 122 && shifton) { down.innerHTML = "Caps Lock is On"; return; } if (charCode >= 65 && charCode <= 90 && !shifton) { down.innerHTML = "Caps Lock is On"; return; } down.innerHTML = "Caps Lock is Off"; return; }); </script> </body> </html> Output: Before clicking on the document: After clicking on the document: Example 2: This example adds an event listener to the document and when it happens it checks for whether the CAPS LOCK is pressed or not. <!DOCTYPE HTML> <html> <head> <title> Check caps lock is on or not </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); up.innerHTML = "Press the CAPS LOCK"; var down = document.getElementById('GFG_DOWN'); document.addEventListener("keyup", function(event) { if (event.getModifierState("CapsLock")) { down.innerHTML = "CAPS LOCK is On"; } else { down.innerHTML = "CAPS LOCK is Off"; } }); </script> </body> </html> Output: Before clicking on the document: After clicking on the document: Check caps lock is on/off using jQuery: jQuery on() Method: This method adds one or more event handlers for the selected elements and child elements.Syntax:$(selector).on(event, childSelector, data, function, map)Parameters:event: This parameter is required. It specifies one or more event(s) or namespaces to attach to the selected elements. In case of multiple event values, those are separated by space. Event must be a valid.childSelector: This parameter is optional. It specifies that the event handler should only be attached to the defined child elements.data: This parameter is optional. It specifies additional data to pass to the function.function: This parameter is required. It specifies the function to run when the event occurs.map: It specifies an event map ({event:func(), event:func(), ...}) having one or more event to add to the selected elements, and functions to run when the events happens. Syntax: $(selector).on(event, childSelector, data, function, map) Parameters: event: This parameter is required. It specifies one or more event(s) or namespaces to attach to the selected elements. In case of multiple event values, those are separated by space. Event must be a valid. childSelector: This parameter is optional. It specifies that the event handler should only be attached to the defined child elements. data: This parameter is optional. It specifies additional data to pass to the function. function: This parameter is required. It specifies the function to run when the event occurs. map: It specifies an event map ({event:func(), event:func(), ...}) having one or more event to add to the selected elements, and functions to run when the events happens. JavaScript String toUpperCase() Method: This method converts a string to uppercase letters.Syntax:string.toUpperCase()Return Value: It returns a string, representing the value of a string converted to uppercase. Syntax: string.toUpperCase() Return Value: It returns a string, representing the value of a string converted to uppercase. JavaScript String toLowerCase() Method: This method converts a string to lowercase letters.Syntax:string.toLowerCase()Return Value: It returns a string, representing the value of a string converted to lowercase. Syntax: string.toLowerCase() Return Value: It returns a string, representing the value of a string converted to lowercase. Example 1: This example adds a event listener to the body of document and when it occurs it calls an anonymous function to handle this. Which checks if it CAPS LOCK or SHIFT key by using toUpperCase(), toLowerCase() and shiftkey. <!DOCTYPE HTML> <html> <head> <title> Check caps lock is on or not </title> <script src ="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> </head> <body style = "text-align:center;" id = "body"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> $('#GFG_UP'). text("Type anywhere on the page to check if CAPS LOCK is ON"); $("#body").on('keypress', function(e) { var s = String.fromCharCode( e.which ); if ((s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey) || (s.toUpperCase() !== s && s.toLowerCase() === s && e.shiftKey)) { $('#GFG_DOWN').text("Caps Lock is ON"); } else if ((s.toLowerCase() === s && s.toUpperCase() !== s && !e.shiftKey) || (s.toLowerCase() !== s && s.toUpperCase() === s && e.shiftKey)) { $('#GFG_DOWN').text("Caps Lock is OFF"); } }); </script> </body> </html> Output: Before typing on the document: After typing on the document: Example 2: This example does the same as of the previous example but by a different approach. Adds an event listener to the document and when it happens it checks for whether the CAPS LOCK is pressed or not. <!DOCTYPE HTML> <html> <head> <title> Check caps lock is on or not </title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> </head> <body style = "text-align:center;" id = "body"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> $('#GFG_UP').text("Turn On the Caps Lock and type on screen"); $('#body').on('keypress', function(e) { var s = String.fromCharCode( e.which ); if ( (s.toUpperCase() === s && !e.shiftKey) || (s.toLowerCase() === s && e.shiftKey) ) { alert('Caps Lock is on'); } else { alert('Caps Lock is off'); } }); </script> </body> </html> Output: Before typing on the document: After typing on the document: JavaScript-Misc jQuery-Misc JavaScript JQuery 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 Roadmap to Learn JavaScript For Beginners JavaScript | Promises JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to add options to a select element using jQuery? How to fetch data from JSON file and display in HTML table using jQuery ?
[ { "code": null, "e": 28, "s": 0, "text": "\n29 May, 2019" }, { "code": null, "e": 122, "s": 28, "text": "The job is to determine the caps lock is turned on or turned off using JavaScript and jQuery." }, { "code": null, "e": 166, "s": 122, "text": "Check caps lock is on/off using JavaScript:" }, { "code": null, "e": 965, "s": 166, "text": "addEventListener() Method: This method adds an event handler to the document.Syntax:document.addEventListener(event, function, useCapture)\nParameters:event: This parameter is required. It specifies the string, the name of the event.function: This parameter is required. It specifies the function to run when the event occurs. When the event occurs, an event object is passed as the first parameter to the function. The type depends on the specified event. For example, the “click” event belongs to the MouseEvent object.useCapture: This parameter is optional. It specifies a boolean value which means whether the event should be executed in the capturing or in the bubbling phase.true: The event handler is executed in the capturing phase.false: The event handler is executed in the bubbling phase." }, { "code": null, "e": 973, "s": 965, "text": "Syntax:" }, { "code": null, "e": 1029, "s": 973, "text": "document.addEventListener(event, function, useCapture)\n" }, { "code": null, "e": 1041, "s": 1029, "text": "Parameters:" }, { "code": null, "e": 1124, "s": 1041, "text": "event: This parameter is required. It specifies the string, the name of the event." }, { "code": null, "e": 1413, "s": 1124, "text": "function: This parameter is required. It specifies the function to run when the event occurs. When the event occurs, an event object is passed as the first parameter to the function. The type depends on the specified event. For example, the “click” event belongs to the MouseEvent object." }, { "code": null, "e": 1692, "s": 1413, "text": "useCapture: This parameter is optional. It specifies a boolean value which means whether the event should be executed in the capturing or in the bubbling phase.true: The event handler is executed in the capturing phase.false: The event handler is executed in the bubbling phase." }, { "code": null, "e": 1752, "s": 1692, "text": "true: The event handler is executed in the capturing phase." }, { "code": null, "e": 1812, "s": 1752, "text": "false: The event handler is executed in the bubbling phase." }, { "code": null, "e": 2015, "s": 1812, "text": "Example 1: This example adds a event listener to the document and when it happens it calls an anonymous function to handle this. Which checks if it CAPS LOCK or SHIFT key by using keyCode of the button." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Check caps lock is on or not </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); up.innerHTML = \"Type anywhere on the page to check if CAPS LOCK is ON\"; var down = document.getElementById('GFG_DOWN'); document.addEventListener('keypress', function(e) { e = (e) ? e : window.event; var charCode = false; if (e.which) { charCode = e.which; } else if (e.keyCode) { charCode = e.keyCode; } var shifton = false; if (e.shiftKey) { shifton = e.shiftKey; } else if (e.modifiers) { shifton = !!(e.modifiers & 4); } if (charCode >= 97 && charCode <= 122 && shifton) { down.innerHTML = \"Caps Lock is On\"; return; } if (charCode >= 65 && charCode <= 90 && !shifton) { down.innerHTML = \"Caps Lock is On\"; return; } down.innerHTML = \"Caps Lock is Off\"; return; }); </script> </body> </html> ", "e": 3895, "s": 2015, "text": null }, { "code": null, "e": 3903, "s": 3895, "text": "Output:" }, { "code": null, "e": 3936, "s": 3903, "text": "Before clicking on the document:" }, { "code": null, "e": 3968, "s": 3936, "text": "After clicking on the document:" }, { "code": null, "e": 4106, "s": 3968, "text": "Example 2: This example adds an event listener to the document and when it happens it checks for whether the CAPS LOCK is pressed or not." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Check caps lock is on or not </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); up.innerHTML = \"Press the CAPS LOCK\"; var down = document.getElementById('GFG_DOWN'); document.addEventListener(\"keyup\", function(event) { if (event.getModifierState(\"CapsLock\")) { down.innerHTML = \"CAPS LOCK is On\"; } else { down.innerHTML = \"CAPS LOCK is Off\"; } }); </script> </body> </html> ", "e": 5139, "s": 4106, "text": null }, { "code": null, "e": 5147, "s": 5139, "text": "Output:" }, { "code": null, "e": 5180, "s": 5147, "text": "Before clicking on the document:" }, { "code": null, "e": 5212, "s": 5180, "text": "After clicking on the document:" }, { "code": null, "e": 5252, "s": 5212, "text": "Check caps lock is on/off using jQuery:" }, { "code": null, "e": 6125, "s": 5252, "text": "jQuery on() Method: This method adds one or more event handlers for the selected elements and child elements.Syntax:$(selector).on(event, childSelector, data, function, map)Parameters:event: This parameter is required. It specifies one or more event(s) or namespaces to attach to the selected elements. In case of multiple event values, those are separated by space. Event must be a valid.childSelector: This parameter is optional. It specifies that the event handler should only be attached to the defined child elements.data: This parameter is optional. It specifies additional data to pass to the function.function: This parameter is required. It specifies the function to run when the event occurs.map: It specifies an event map ({event:func(), event:func(), ...}) having one or more event to add to the selected elements, and functions to run when the events happens." }, { "code": null, "e": 6133, "s": 6125, "text": "Syntax:" }, { "code": null, "e": 6191, "s": 6133, "text": "$(selector).on(event, childSelector, data, function, map)" }, { "code": null, "e": 6203, "s": 6191, "text": "Parameters:" }, { "code": null, "e": 6409, "s": 6203, "text": "event: This parameter is required. It specifies one or more event(s) or namespaces to attach to the selected elements. In case of multiple event values, those are separated by space. Event must be a valid." }, { "code": null, "e": 6543, "s": 6409, "text": "childSelector: This parameter is optional. It specifies that the event handler should only be attached to the defined child elements." }, { "code": null, "e": 6631, "s": 6543, "text": "data: This parameter is optional. It specifies additional data to pass to the function." }, { "code": null, "e": 6725, "s": 6631, "text": "function: This parameter is required. It specifies the function to run when the event occurs." }, { "code": null, "e": 6896, "s": 6725, "text": "map: It specifies an event map ({event:func(), event:func(), ...}) having one or more event to add to the selected elements, and functions to run when the events happens." }, { "code": null, "e": 7108, "s": 6896, "text": "JavaScript String toUpperCase() Method: This method converts a string to uppercase letters.Syntax:string.toUpperCase()Return Value: It returns a string, representing the value of a string converted to uppercase." }, { "code": null, "e": 7116, "s": 7108, "text": "Syntax:" }, { "code": null, "e": 7137, "s": 7116, "text": "string.toUpperCase()" }, { "code": null, "e": 7231, "s": 7137, "text": "Return Value: It returns a string, representing the value of a string converted to uppercase." }, { "code": null, "e": 7443, "s": 7231, "text": "JavaScript String toLowerCase() Method: This method converts a string to lowercase letters.Syntax:string.toLowerCase()Return Value: It returns a string, representing the value of a string converted to lowercase." }, { "code": null, "e": 7451, "s": 7443, "text": "Syntax:" }, { "code": null, "e": 7472, "s": 7451, "text": "string.toLowerCase()" }, { "code": null, "e": 7566, "s": 7472, "text": "Return Value: It returns a string, representing the value of a string converted to lowercase." }, { "code": null, "e": 7796, "s": 7566, "text": "Example 1: This example adds a event listener to the body of document and when it occurs it calls an anonymous function to handle this. Which checks if it CAPS LOCK or SHIFT key by using toUpperCase(), toLowerCase() and shiftkey." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Check caps lock is on or not </title> <script src =\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> </head> <body style = \"text-align:center;\" id = \"body\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> $('#GFG_UP'). text(\"Type anywhere on the page to check if CAPS LOCK is ON\"); $(\"#body\").on('keypress', function(e) { var s = String.fromCharCode( e.which ); if ((s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey) || (s.toUpperCase() !== s && s.toLowerCase() === s && e.shiftKey)) { $('#GFG_DOWN').text(\"Caps Lock is ON\"); } else if ((s.toLowerCase() === s && s.toUpperCase() !== s && !e.shiftKey) || (s.toLowerCase() !== s && s.toUpperCase() === s && e.shiftKey)) { $('#GFG_DOWN').text(\"Caps Lock is OFF\"); } }); </script> </body> </html> ", "e": 9244, "s": 7796, "text": null }, { "code": null, "e": 9252, "s": 9244, "text": "Output:" }, { "code": null, "e": 9283, "s": 9252, "text": "Before typing on the document:" }, { "code": null, "e": 9313, "s": 9283, "text": "After typing on the document:" }, { "code": null, "e": 9521, "s": 9313, "text": "Example 2: This example does the same as of the previous example but by a different approach. Adds an event listener to the document and when it happens it checks for whether the CAPS LOCK is pressed or not." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Check caps lock is on or not </title> <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> </head> <body style = \"text-align:center;\" id = \"body\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> $('#GFG_UP').text(\"Turn On the Caps Lock and type on screen\"); $('#body').on('keypress', function(e) { var s = String.fromCharCode( e.which ); if ( (s.toUpperCase() === s && !e.shiftKey) || (s.toLowerCase() === s && e.shiftKey) ) { alert('Caps Lock is on'); } else { alert('Caps Lock is off'); } }); </script> </body> </html> ", "e": 10661, "s": 9521, "text": null }, { "code": null, "e": 10669, "s": 10661, "text": "Output:" }, { "code": null, "e": 10700, "s": 10669, "text": "Before typing on the document:" }, { "code": null, "e": 10730, "s": 10700, "text": "After typing on the document:" }, { "code": null, "e": 10746, "s": 10730, "text": "JavaScript-Misc" }, { "code": null, "e": 10758, "s": 10746, "text": "jQuery-Misc" }, { "code": null, "e": 10769, "s": 10758, "text": "JavaScript" }, { "code": null, "e": 10776, "s": 10769, "text": "JQuery" }, { "code": null, "e": 10793, "s": 10776, "text": "Web Technologies" }, { "code": null, "e": 10820, "s": 10793, "text": "Web technologies Questions" }, { "code": null, "e": 10918, "s": 10820, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10979, "s": 10918, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 11019, "s": 10979, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 11060, "s": 11019, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 11102, "s": 11060, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 11124, "s": 11102, "text": "JavaScript | Promises" }, { "code": null, "e": 11170, "s": 11124, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 11199, "s": 11170, "text": "Form validation using jQuery" }, { "code": null, "e": 11262, "s": 11199, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 11315, "s": 11262, "text": "How to add options to a select element using jQuery?" } ]
Bootstrap | Close Icon for dismissing content with Examples
17 Jul, 2021 The close icon in bootstrap is a utility that is used to dismiss any content (e.g., Alerts, Modals, Popovers). It is represented by a generic cross/close icon.Below is a sample HTML code including a close icon for dismissing content in bootstrap: html <!doctype html><html> <head> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> <title>Close Icon!</title> </head> <body class="container mt-5"> <!--Close Icon--> <button type="button" class="close"> <span>×</span> </button> </body></html> Note: The data-dismiss attribute can be used with a button tag to target the component to dismiss such as a modal or an alert. Example: html <!DOCTYPE html><html lang="en"> <head> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <!-- Include JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> <style media="screen"> h1{ color:green; font-weight: bold;} </style> <title>Close Icon!</title> </head> <body class="container"> <h1>This is GeeksforGeeks!</h1> <!--Alert--> <div class="alert alert-success alert-dismissible fade show w-50" role="alert"> <strong>Hello geeks!</strong> <!--Close Icon--> <button type="button" class="btn close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> </body></html> Output: Before: After: Example: html <!DOCTYPE html><html> <head> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <style media="screen"> h1{ color:green; font-weight: bold;} </style> <title>Close Icon!</title> <!-- Include JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> </head> <body class="container mt-5"> <!-- Button trigger modal --> <button type="button" class="btn btn-success" data-toggle="modal" data-target="#geekymodal"> Click here to launch modal! </button> <!-- Modal --> <div class="modal fade" id="geekymodal" tabindex="-1" role="dialog" aria-labelledby="geekymodal" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title"> GeeksforGeeks! </h1> <!--Close Icon--> <button type="button" class="btn close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> Hey geeks, You're Welcome! </div> </div> </div> </div> </body></html> Output: Before: After: Supported Browser: Google Chrome Internet Explorer Firefox Opera Safari ysachin2314 Picked Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jul, 2021" }, { "code": null, "e": 276, "s": 28, "text": "The close icon in bootstrap is a utility that is used to dismiss any content (e.g., Alerts, Modals, Popovers). It is represented by a generic cross/close icon.Below is a sample HTML code including a close icon for dismissing content in bootstrap: " }, { "code": null, "e": 281, "s": 276, "text": "html" }, { "code": "<!doctype html><html> <head> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\"> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" integrity=\"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" integrity=\"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" crossorigin=\"anonymous\"></script> <title>Close Icon!</title> </head> <body class=\"container mt-5\"> <!--Close Icon--> <button type=\"button\" class=\"close\"> <span>×</span> </button> </body></html> ", "e": 1540, "s": 281, "text": null }, { "code": null, "e": 1668, "s": 1540, "text": "Note: The data-dismiss attribute can be used with a button tag to target the component to dismiss such as a modal or an alert. " }, { "code": null, "e": 1679, "s": 1668, "text": "Example: " }, { "code": null, "e": 1684, "s": 1679, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" integrity=\"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" crossorigin=\"anonymous\"> <!-- Include JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" integrity=\"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" integrity=\"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" crossorigin=\"anonymous\"></script> <style media=\"screen\"> h1{ color:green; font-weight: bold;} </style> <title>Close Icon!</title> </head> <body class=\"container\"> <h1>This is GeeksforGeeks!</h1> <!--Alert--> <div class=\"alert alert-success alert-dismissible fade show w-50\" role=\"alert\"> <strong>Hello geeks!</strong> <!--Close Icon--> <button type=\"button\" class=\"btn close\" data-dismiss=\"alert\" aria-label=\"Close\"> <span aria-hidden=\"true\">×</span> </button> </div> </body></html> ", "e": 3405, "s": 1684, "text": null }, { "code": null, "e": 3423, "s": 3405, "text": "Output: Before: " }, { "code": null, "e": 3432, "s": 3423, "text": "After: " }, { "code": null, "e": 3445, "s": 3434, "text": "Example: " }, { "code": null, "e": 3450, "s": 3445, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" integrity=\"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" crossorigin=\"anonymous\"> <style media=\"screen\"> h1{ color:green; font-weight: bold;} </style> <title>Close Icon!</title> <!-- Include JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" integrity=\"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" integrity=\"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" crossorigin=\"anonymous\"></script> </head> <body class=\"container mt-5\"> <!-- Button trigger modal --> <button type=\"button\" class=\"btn btn-success\" data-toggle=\"modal\" data-target=\"#geekymodal\"> Click here to launch modal! </button> <!-- Modal --> <div class=\"modal fade\" id=\"geekymodal\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"geekymodal\" aria-hidden=\"true\"> <div class=\"modal-dialog\" role=\"document\"> <div class=\"modal-content\"> <div class=\"modal-header\"> <h1 class=\"modal-title\"> GeeksforGeeks! </h1> <!--Close Icon--> <button type=\"button\" class=\"btn close\" data-dismiss=\"modal\" aria-label=\"Close\"> <span aria-hidden=\"true\">×</span> </button> </div> <div class=\"modal-body\"> Hey geeks, You're Welcome! </div> </div> </div> </div> </body></html> ", "e": 5897, "s": 3450, "text": null }, { "code": null, "e": 5915, "s": 5897, "text": "Output: Before: " }, { "code": null, "e": 5924, "s": 5915, "text": "After: " }, { "code": null, "e": 5943, "s": 5924, "text": "Supported Browser:" }, { "code": null, "e": 5957, "s": 5943, "text": "Google Chrome" }, { "code": null, "e": 5975, "s": 5957, "text": "Internet Explorer" }, { "code": null, "e": 5983, "s": 5975, "text": "Firefox" }, { "code": null, "e": 5989, "s": 5983, "text": "Opera" }, { "code": null, "e": 5996, "s": 5989, "text": "Safari" }, { "code": null, "e": 6008, "s": 5996, "text": "ysachin2314" }, { "code": null, "e": 6015, "s": 6008, "text": "Picked" }, { "code": null, "e": 6025, "s": 6015, "text": "Bootstrap" }, { "code": null, "e": 6042, "s": 6025, "text": "Web Technologies" } ]
How to fade in and fade out background with bootstrap text carousel ?
12 May, 2021 In this article, we will show you how to fade in and fade out the background with a bootstrap text carousel. Carousel is a slideshow, and it is used for cycling components like images or text. Approach: To create a fade-in and fade-out background with a bootstrap text carousel we have followed some basic steps. Step 1: Add bootstrap CDN to your HTML code. Step 1: Add bootstrap CDN to your HTML code. Step 2: For making a bootstrap carousel you have to add class = “carousel” in your HTML div box. Step 2: For making a bootstrap carousel you have to add class = “carousel” in your HTML div box. Step 3: To create the carousel fade in and fade out transition instead of a slider you have to add a class=”carousel-fade”. Step 3: To create the carousel fade in and fade out transition instead of a slider you have to add a class=”carousel-fade”. Step 4: Finally add text in your div box which you want to play in the carousel with a class=”carousel-item”. Step 4: Finally add text in your div box which you want to play in the carousel with a class=”carousel-item”. Example: HTML <!DOCTYPE html><html> <head> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <style> h1 { color: green; } *, *::before, *::after { margin: 0; padding: 0; } html { box-sizing: border-box; } body { box-sizing: inherit; color: #fff !important; } h1 { margin-top: 0; text-align: center; font-weight: 600; } .carousel { margin-top: 10%; width: 100%; background-color: black; } </style> </head> <body> <h1>GeeksforGeeks</h1> <div id="carouselExampleFade" class="carousel slide carousel-fade" data-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <h1>Hii GeeksforGeeks</h1> </div> <div class="carousel-item"> <h1>Hello there</h1> </div> <div class="carousel-item"> <h1>GFG</h1> </div> </div> <a class="carousel-control-prev" href="#carouselExampleFade" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"> </span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleFade" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"> </span> <span class="sr-only">Next</span> </a> </div> </body></html> Output : Carousel Bootstrap-Questions Picked Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show Images on Click using HTML ? How to Use Bootstrap with React? How to set vertical alignment in Bootstrap ? Tailwind CSS vs Bootstrap How to toggle password visibility in forms using Bootstrap-icons ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n12 May, 2021" }, { "code": null, "e": 221, "s": 28, "text": "In this article, we will show you how to fade in and fade out the background with a bootstrap text carousel. Carousel is a slideshow, and it is used for cycling components like images or text." }, { "code": null, "e": 341, "s": 221, "text": "Approach: To create a fade-in and fade-out background with a bootstrap text carousel we have followed some basic steps." }, { "code": null, "e": 386, "s": 341, "text": "Step 1: Add bootstrap CDN to your HTML code." }, { "code": null, "e": 431, "s": 386, "text": "Step 1: Add bootstrap CDN to your HTML code." }, { "code": null, "e": 529, "s": 431, "text": "Step 2: For making a bootstrap carousel you have to add class = “carousel” in your HTML div box." }, { "code": null, "e": 627, "s": 529, "text": "Step 2: For making a bootstrap carousel you have to add class = “carousel” in your HTML div box." }, { "code": null, "e": 751, "s": 627, "text": "Step 3: To create the carousel fade in and fade out transition instead of a slider you have to add a class=”carousel-fade”." }, { "code": null, "e": 875, "s": 751, "text": "Step 3: To create the carousel fade in and fade out transition instead of a slider you have to add a class=”carousel-fade”." }, { "code": null, "e": 985, "s": 875, "text": "Step 4: Finally add text in your div box which you want to play in the carousel with a class=”carousel-item”." }, { "code": null, "e": 1095, "s": 985, "text": "Step 4: Finally add text in your div box which you want to play in the carousel with a class=”carousel-item”." }, { "code": null, "e": 1104, "s": 1095, "text": "Example:" }, { "code": null, "e": 1109, "s": 1104, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <link href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" rel=\"stylesheet\" /> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> <style> h1 { color: green; } *, *::before, *::after { margin: 0; padding: 0; } html { box-sizing: border-box; } body { box-sizing: inherit; color: #fff !important; } h1 { margin-top: 0; text-align: center; font-weight: 600; } .carousel { margin-top: 10%; width: 100%; background-color: black; } </style> </head> <body> <h1>GeeksforGeeks</h1> <div id=\"carouselExampleFade\" class=\"carousel slide carousel-fade\" data-ride=\"carousel\"> <div class=\"carousel-inner\"> <div class=\"carousel-item active\"> <h1>Hii GeeksforGeeks</h1> </div> <div class=\"carousel-item\"> <h1>Hello there</h1> </div> <div class=\"carousel-item\"> <h1>GFG</h1> </div> </div> <a class=\"carousel-control-prev\" href=\"#carouselExampleFade\" role=\"button\" data-slide=\"prev\"> <span class=\"carousel-control-prev-icon\" aria-hidden=\"true\"> </span> <span class=\"sr-only\">Previous</span> </a> <a class=\"carousel-control-next\" href=\"#carouselExampleFade\" role=\"button\" data-slide=\"next\"> <span class=\"carousel-control-next-icon\" aria-hidden=\"true\"> </span> <span class=\"sr-only\">Next</span> </a> </div> </body></html>", "e": 3486, "s": 1109, "text": null }, { "code": null, "e": 3495, "s": 3486, "text": "Output :" }, { "code": null, "e": 3504, "s": 3495, "text": "Carousel" }, { "code": null, "e": 3524, "s": 3504, "text": "Bootstrap-Questions" }, { "code": null, "e": 3531, "s": 3524, "text": "Picked" }, { "code": null, "e": 3541, "s": 3531, "text": "Bootstrap" }, { "code": null, "e": 3558, "s": 3541, "text": "Web Technologies" }, { "code": null, "e": 3656, "s": 3558, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3697, "s": 3656, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 3730, "s": 3697, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 3775, "s": 3730, "text": "How to set vertical alignment in Bootstrap ?" }, { "code": null, "e": 3801, "s": 3775, "text": "Tailwind CSS vs Bootstrap" }, { "code": null, "e": 3868, "s": 3801, "text": "How to toggle password visibility in forms using Bootstrap-icons ?" }, { "code": null, "e": 3901, "s": 3868, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3963, "s": 3901, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4024, "s": 3963, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4074, "s": 4024, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Java Arrays - GeeksforGeeks
07 Mar, 2018 0 0 garbage value garbage value class Test { public static void main(String args[]) { int arr[5]; //Error } } 0 0 garbage value garbage value 0 1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 0 0 0 0 9 7 8 4 5 6 0 1 2 3 for(j = 0; j < 4; ++j){ t = M[i][j]; M[i][j] = M[j][i]; M[j][i] = t; } for(j = 0; j < 4; ++j){ M[i][j] = t; t = M[j][i]; M[j][i] = M[i][j]; } for(j = i; j < 4; ++j){ t = M[i][j]; M[i][j] = M[j][i]; M[j][i] = t; } for(j = i; j < 4; ++j){ M[i][j] = t; t = M[j][i]; M[j][i] = M[i][j]; } To compute transpose j needs to be started with i,so A and B are WRONG In D, given statement is wrong as temporary variable t needs to be assigned some value and NOT vice versa M[i][j] = t; M[i][j] = t; Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 29577, "s": 29549, "text": "\n07 Mar, 2018" }, { "code": null, "e": 29581, "s": 29577, "text": "0\n0" }, { "code": null, "e": 29609, "s": 29581, "text": "garbage value\ngarbage value" }, { "code": null, "e": 29700, "s": 29609, "text": "class Test {\n public static void main(String args[]) {\n int arr[5]; //Error\n }\n}" }, { "code": null, "e": 29704, "s": 29700, "text": "0\n0" }, { "code": null, "e": 29732, "s": 29704, "text": "garbage value\ngarbage value" }, { "code": null, "e": 29757, "s": 29732, "text": " 0\n 1 2\n 3 4 5\n 6 7 8 9 " }, { "code": null, "e": 29782, "s": 29757, "text": " 0\n 0 0\n 0 0 0\n 0 0 0 0 " }, { "code": null, "e": 29807, "s": 29782, "text": " 9\n 7 8\n 4 5 6\n 0 1 2 3 " }, { "code": null, "e": 29893, "s": 29807, "text": "for(j = 0; j < 4; ++j){\n t = M[i][j];\n M[i][j] = M[j][i];\n M[j][i] = t;\n}" }, { "code": null, "e": 29979, "s": 29893, "text": "for(j = 0; j < 4; ++j){\n M[i][j] = t;\n t = M[j][i];\n M[j][i] = M[i][j];\n}" }, { "code": null, "e": 30065, "s": 29979, "text": "for(j = i; j < 4; ++j){\n t = M[i][j];\n M[i][j] = M[j][i];\n M[j][i] = t;\n}" }, { "code": null, "e": 30151, "s": 30065, "text": "for(j = i; j < 4; ++j){\n M[i][j] = t;\n t = M[j][i];\n M[j][i] = M[i][j];\n}" }, { "code": null, "e": 30222, "s": 30151, "text": "To compute transpose j needs to be started with i,so A and B are WRONG" }, { "code": null, "e": 30342, "s": 30222, "text": "In D, given statement is wrong as temporary variable t needs to be assigned some value and NOT vice versa M[i][j] = t; " }, { "code": null, "e": 30357, "s": 30342, "text": " M[i][j] = t; " } ]
Remove first node of the linked list
24 Jun, 2022 Given a linked list, the task is to remove the first node of the linked list and update the head pointer of the linked list. Examples: Input : 1 -> 2 -> 3 -> 4 -> 5 -> NULL Output : 2 -> 3 -> 4 -> 5 -> NULL Input : 2 -> 4 -> 6 -> 8 -> 33 -> 67 -> NULL Output : 4 -> 6 -> 8 -> 33 -> 67 -> NULL To remove first node, we need to make second node as head and delete memory allocated for first node. C++ Java Python3 C# Javascript // CPP program to remove first node of// linked list.#include <iostream>using namespace std; /* Link list node */struct Node { int data; struct Node* next;}; /* Function to remove the first node of the linked list */Node* removeFirstNode(struct Node* head){ if (head == NULL) return NULL; // Move the head pointer to the next node Node* temp = head; head = head->next; delete temp; return head;} // Function to push node at headvoid push(struct Node** head_ref, int new_data){ struct Node* new_node = new Node; new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Driver codeint main(){ /* Start with the empty list */ Node* head = NULL; /* Use push() function to construct the below list 8 -> 23 -> 11 -> 29 -> 12 */ push(&head, 12); push(&head, 29); push(&head, 11); push(&head, 23); push(&head, 8); head = removeFirstNode(head); for (Node* temp = head; temp != NULL; temp = temp->next) cout << temp->data << " "; return 0;} // Java program to remove first node of// linked list.class GFG { // Link list node / static class Node { int data; Node next; }; // Function to remove the first node // of the linked list / static Node removeFirstNode(Node head) { if (head == null) return null; // Move the head pointer to the next node Node temp = head; head = head.next; return head; } // Function to push node at head static Node push(Node head_ref, int new_data) { Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref; } // Driver code public static void main(String args[]) { // Start with the empty list / Node head = null; // Use push() function to con // the below list 8 . 23 . 11 . 29 . 12 / head = push(head, 12); head = push(head, 29); head = push(head, 11); head = push(head, 23); head = push(head, 8); head = removeFirstNode(head); for (Node temp = head; temp != null; temp = temp.next) System.out.print(temp.data + " "); }} // This code is contributed by Arnab Kundu # Python3 program to remove first node of # linked list.import sys # Link list node class Node: def __init__(self, data): self.data = data self.next = None # Function to remove the first node # of the linked list def removeFirstNode(head): if not head: return None temp = head # Move the head pointer to the next node head = head.next temp = None return head # Function to push node at head def push(head, data): if not head: return Node(data) temp = Node(data) temp.next = head head = temp return head # Driver codeif __name__=='__main__': # Start with the empty list head = None # Use push() function to construct # the below list 8 -> 23 -> 11 -> 29 -> 12 head = push(head, 12) head = push(head, 29) head = push(head, 11) head = push(head, 23) head = push(head, 8) head = removeFirstNode(head) while(head): print("{} ".format(head.data), end ="") head = head.next # This code is Contributed by Vikash Kumar 37 // C# program to remove first node of// linked list.using System; class GFG { // Link list node / public class Node { public int data; public Node next; }; // Function to remove the first node // of the linked list / static Node removeFirstNode(Node head) { if (head == null) return null; // Move the head pointer to the next node Node temp = head; head = head.next; return head; } // Function to push node at head static Node push(Node head_ref, int new_data) { Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref; } // Driver code public static void Main(String []args) { // Start with the empty list / Node head = null; // Use push() function to con // the below list 8 . 23 . 11 . 29 . 12 / head = push(head, 12); head = push(head, 29); head = push(head, 11); head = push(head, 23); head = push(head, 8); head = removeFirstNode(head); for (Node temp = head; temp != null; temp = temp.next) Console.Write(temp.data + " "); }} /* This code contributed by PrinciRaj1992 */ <script>// javascript program to remove first node of// linked list. // Link list node /class Node { constructor(val) { this.data = val; this.next = null; }} // Function to remove the first node // of the linked list / function removeFirstNode( head) { if (head == null) return null; // Move the head pointer to the next node temp = head; head = head.next; return head; } // Function to push node at head function push( head_ref , new_data) { new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref; } // Driver code // Start with the empty list / head = null; // Use push() function to con // the below list 8 . 23 . 11 . 29 . 12 / head = push(head, 12); head = push(head, 29); head = push(head, 11); head = push(head, 23); head = push(head, 8); head = removeFirstNode(head); for ( temp = head; temp != null; temp = temp.next) document.write(temp.data + " "); // This code is contributed by todaysgaurav </script> 23 11 29 12 Time complexity : O(1) VishalBachchas andrew1234 Vikash Kumar 37 princiraj1992 mohabmagdy79 todaysgaurav Technical Scripter 2018 Linked List Technical Scripter Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. LinkedList in Java Introduction to Data Structures Doubly Linked List | Set 1 (Introduction and Insertion) Merge two sorted linked lists What is Data Structure: Types, Classifications and Applications Linked List vs Array Merge Sort for Linked Lists Implementing a Linked List in Java using Class Function to check if a singly linked list is palindrome Queue - Linked List Implementation
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Jun, 2022" }, { "code": null, "e": 189, "s": 52, "text": "Given a linked list, the task is to remove the first node of the linked list and update the head pointer of the linked list. Examples: " }, { "code": null, "e": 348, "s": 189, "text": "Input : 1 -> 2 -> 3 -> 4 -> 5 -> NULL\nOutput : 2 -> 3 -> 4 -> 5 -> NULL\n\nInput : 2 -> 4 -> 6 -> 8 -> 33 -> 67 -> NULL\nOutput : 4 -> 6 -> 8 -> 33 -> 67 -> NULL" }, { "code": null, "e": 454, "s": 350, "text": "To remove first node, we need to make second node as head and delete memory allocated for first node. " }, { "code": null, "e": 458, "s": 454, "text": "C++" }, { "code": null, "e": 463, "s": 458, "text": "Java" }, { "code": null, "e": 471, "s": 463, "text": "Python3" }, { "code": null, "e": 474, "s": 471, "text": "C#" }, { "code": null, "e": 485, "s": 474, "text": "Javascript" }, { "code": "// CPP program to remove first node of// linked list.#include <iostream>using namespace std; /* Link list node */struct Node { int data; struct Node* next;}; /* Function to remove the first node of the linked list */Node* removeFirstNode(struct Node* head){ if (head == NULL) return NULL; // Move the head pointer to the next node Node* temp = head; head = head->next; delete temp; return head;} // Function to push node at headvoid push(struct Node** head_ref, int new_data){ struct Node* new_node = new Node; new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Driver codeint main(){ /* Start with the empty list */ Node* head = NULL; /* Use push() function to construct the below list 8 -> 23 -> 11 -> 29 -> 12 */ push(&head, 12); push(&head, 29); push(&head, 11); push(&head, 23); push(&head, 8); head = removeFirstNode(head); for (Node* temp = head; temp != NULL; temp = temp->next) cout << temp->data << \" \"; return 0;}", "e": 1554, "s": 485, "text": null }, { "code": "// Java program to remove first node of// linked list.class GFG { // Link list node / static class Node { int data; Node next; }; // Function to remove the first node // of the linked list / static Node removeFirstNode(Node head) { if (head == null) return null; // Move the head pointer to the next node Node temp = head; head = head.next; return head; } // Function to push node at head static Node push(Node head_ref, int new_data) { Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref; } // Driver code public static void main(String args[]) { // Start with the empty list / Node head = null; // Use push() function to con // the below list 8 . 23 . 11 . 29 . 12 / head = push(head, 12); head = push(head, 29); head = push(head, 11); head = push(head, 23); head = push(head, 8); head = removeFirstNode(head); for (Node temp = head; temp != null; temp = temp.next) System.out.print(temp.data + \" \"); }} // This code is contributed by Arnab Kundu", "e": 2820, "s": 1554, "text": null }, { "code": "# Python3 program to remove first node of # linked list.import sys # Link list node class Node: def __init__(self, data): self.data = data self.next = None # Function to remove the first node # of the linked list def removeFirstNode(head): if not head: return None temp = head # Move the head pointer to the next node head = head.next temp = None return head # Function to push node at head def push(head, data): if not head: return Node(data) temp = Node(data) temp.next = head head = temp return head # Driver codeif __name__=='__main__': # Start with the empty list head = None # Use push() function to construct # the below list 8 -> 23 -> 11 -> 29 -> 12 head = push(head, 12) head = push(head, 29) head = push(head, 11) head = push(head, 23) head = push(head, 8) head = removeFirstNode(head) while(head): print(\"{} \".format(head.data), end =\"\") head = head.next # This code is Contributed by Vikash Kumar 37", "e": 3870, "s": 2820, "text": null }, { "code": "// C# program to remove first node of// linked list.using System; class GFG { // Link list node / public class Node { public int data; public Node next; }; // Function to remove the first node // of the linked list / static Node removeFirstNode(Node head) { if (head == null) return null; // Move the head pointer to the next node Node temp = head; head = head.next; return head; } // Function to push node at head static Node push(Node head_ref, int new_data) { Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref; } // Driver code public static void Main(String []args) { // Start with the empty list / Node head = null; // Use push() function to con // the below list 8 . 23 . 11 . 29 . 12 / head = push(head, 12); head = push(head, 29); head = push(head, 11); head = push(head, 23); head = push(head, 8); head = removeFirstNode(head); for (Node temp = head; temp != null; temp = temp.next) Console.Write(temp.data + \" \"); }} /* This code contributed by PrinciRaj1992 */", "e": 5167, "s": 3870, "text": null }, { "code": "<script>// javascript program to remove first node of// linked list. // Link list node /class Node { constructor(val) { this.data = val; this.next = null; }} // Function to remove the first node // of the linked list / function removeFirstNode( head) { if (head == null) return null; // Move the head pointer to the next node temp = head; head = head.next; return head; } // Function to push node at head function push( head_ref , new_data) { new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref; } // Driver code // Start with the empty list / head = null; // Use push() function to con // the below list 8 . 23 . 11 . 29 . 12 / head = push(head, 12); head = push(head, 29); head = push(head, 11); head = push(head, 23); head = push(head, 8); head = removeFirstNode(head); for ( temp = head; temp != null; temp = temp.next) document.write(temp.data + \" \"); // This code is contributed by todaysgaurav </script>", "e": 6382, "s": 5167, "text": null }, { "code": null, "e": 6394, "s": 6382, "text": "23 11 29 12" }, { "code": null, "e": 6420, "s": 6396, "text": "Time complexity : O(1) " }, { "code": null, "e": 6435, "s": 6420, "text": "VishalBachchas" }, { "code": null, "e": 6446, "s": 6435, "text": "andrew1234" }, { "code": null, "e": 6462, "s": 6446, "text": "Vikash Kumar 37" }, { "code": null, "e": 6476, "s": 6462, "text": "princiraj1992" }, { "code": null, "e": 6489, "s": 6476, "text": "mohabmagdy79" }, { "code": null, "e": 6502, "s": 6489, "text": "todaysgaurav" }, { "code": null, "e": 6526, "s": 6502, "text": "Technical Scripter 2018" }, { "code": null, "e": 6538, "s": 6526, "text": "Linked List" }, { "code": null, "e": 6557, "s": 6538, "text": "Technical Scripter" }, { "code": null, "e": 6569, "s": 6557, "text": "Linked List" }, { "code": null, "e": 6667, "s": 6569, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6686, "s": 6667, "text": "LinkedList in Java" }, { "code": null, "e": 6718, "s": 6686, "text": "Introduction to Data Structures" }, { "code": null, "e": 6774, "s": 6718, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" }, { "code": null, "e": 6804, "s": 6774, "text": "Merge two sorted linked lists" }, { "code": null, "e": 6868, "s": 6804, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 6889, "s": 6868, "text": "Linked List vs Array" }, { "code": null, "e": 6917, "s": 6889, "text": "Merge Sort for Linked Lists" }, { "code": null, "e": 6964, "s": 6917, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 7020, "s": 6964, "text": "Function to check if a singly linked list is palindrome" } ]
How to Fetch Device ID in Android Programmatically?
12 Jan, 2022 Android Device ID is a unique code, string combinations of alphabets and numbers, given to every manufactured android device. This code is used to identify and track each android device present in the world. In Android, the Device ID is typically related to the Google Play Services and is most commonly used in ad personalization. These IDs are collected and are used for displaying particular types of ads. This type is calculated upon user search and navigation tracking. One can root the device to erase the Device ID and avoid tracking and ad personalization. In this article, we will show you how you could fetch the Device ID of your Android device. Follow the below steps once the IDE is ready. Step 1: Create a New Project in Android Studio To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project. Step 2: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- This TextView will display the Device ID --> <TextView android:id="@+id/textview_1" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 3: Working with the MainActivity.kt file Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Kotlin package org.geeksforgeeks.deviceid import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.provider.Settingsimport android.widget.TextView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declaring and initializing a constant for // the TextView from the layout file (activity_main.xml) val mTextView1 = findViewById<TextView>(R.id.textview_1) // Fetching Android ID and storing it into a constant val mId = Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID) // Displaying the Android ID into the TextView mTextView1.text = mId }} Output: You would see that when the app launches, the device ID is fetched and is displayed in the TextView. Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components How to Communicate Between Fragments in Android? Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android How to Add Views Dynamically and Store Data in Arraylist in Android? Android UI Layouts Kotlin Array How to Communicate Between Fragments in Android? Retrofit with Kotlin Coroutine in Android
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Jan, 2022" }, { "code": null, "e": 731, "s": 28, "text": "Android Device ID is a unique code, string combinations of alphabets and numbers, given to every manufactured android device. This code is used to identify and track each android device present in the world. In Android, the Device ID is typically related to the Google Play Services and is most commonly used in ad personalization. These IDs are collected and are used for displaying particular types of ads. This type is calculated upon user search and navigation tracking. One can root the device to erase the Device ID and avoid tracking and ad personalization. In this article, we will show you how you could fetch the Device ID of your Android device. Follow the below steps once the IDE is ready." }, { "code": null, "e": 778, "s": 731, "text": "Step 1: Create a New Project in Android Studio" }, { "code": null, "e": 1017, "s": 778, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project." }, { "code": null, "e": 1065, "s": 1017, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 1208, "s": 1065, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 1212, "s": 1208, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!-- This TextView will display the Device ID --> <TextView android:id=\"@+id/textview_1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 2038, "s": 1212, "text": null }, { "code": null, "e": 2084, "s": 2038, "text": "Step 3: Working with the MainActivity.kt file" }, { "code": null, "e": 2270, "s": 2084, "text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 2277, "s": 2270, "text": "Kotlin" }, { "code": "package org.geeksforgeeks.deviceid import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.provider.Settingsimport android.widget.TextView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declaring and initializing a constant for // the TextView from the layout file (activity_main.xml) val mTextView1 = findViewById<TextView>(R.id.textview_1) // Fetching Android ID and storing it into a constant val mId = Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID) // Displaying the Android ID into the TextView mTextView1.text = mId }}", "e": 3060, "s": 2277, "text": null }, { "code": null, "e": 3068, "s": 3060, "text": "Output:" }, { "code": null, "e": 3169, "s": 3068, "text": "You would see that when the app launches, the device ID is fetched and is displayed in the TextView." }, { "code": null, "e": 3177, "s": 3169, "text": "Android" }, { "code": null, "e": 3184, "s": 3177, "text": "Kotlin" }, { "code": null, "e": 3192, "s": 3184, "text": "Android" }, { "code": null, "e": 3290, "s": 3192, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3359, "s": 3290, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 3391, "s": 3359, "text": "Android SDK and it's Components" }, { "code": null, "e": 3440, "s": 3391, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 3479, "s": 3440, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 3521, "s": 3479, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 3590, "s": 3521, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 3609, "s": 3590, "text": "Android UI Layouts" }, { "code": null, "e": 3622, "s": 3609, "text": "Kotlin Array" }, { "code": null, "e": 3671, "s": 3622, "text": "How to Communicate Between Fragments in Android?" } ]
Python program to build flashcard using class in Python
20 Jun, 2022 In this article, we will see how to build a flashcard using class in python. A flashcard is a card having information on both sides, which can be used as an aid in memoization. Flashcards usually have a question on one side and an answer on the other. Particularly in this article, we are going to create flashcards that will be having a word and its meaning. Let’s see some examples of flashcard: Example 1: Approach : Take the word and its meaning as input from the user. Create a class named flashcard, use the __init__() function to assign values for Word and Meaning. Now we use the __str__() function to return a string that contains the word and meaning. Store the returned strings in a list named flash. Use a while loop to print all the stored flashcards. Below is the full implementation: Python3 class flashcard: def __init__(self, word, meaning): self.word = word self.meaning = meaning def __str__(self): #we will return a string return self.word+' ( '+self.meaning+' )' flash = []print("welcome to flashcard application") #the following loop will be repeated until#user stops to add the flashcardswhile(True): word = input("enter the name you want to add to flashcard : ") meaning = input("enter the meaning of the word : ") flash.append(flashcard(word, meaning)) option = int(input("enter 0 , if you want to add another flashcard : ")) if(option): break # printing all the flashcardsprint("\nYour flashcards")for i in flash: print(">", i) Output: Example 2: Approach : Create a class named flashcard. Initialize dictionary fruits using __init__() method. Now randomly choose a pair from fruits using choice() method and store the key in variable fruit and value in variable color. Now prompt the user to answer the color of the randomly chosen fruit. If correct print correct else print wrong. Python3 import random class flashcard: def __init__(self): self.fruits={'apple':'red', 'orange':'orange', 'watermelon':'green', 'banana':'yellow'} def quiz(self): while (True): fruit, color = random.choice(list(self.fruits.items())) print("What is the color of {}".format(fruit)) user_answer = input() if(user_answer.lower() == color): print("Correct answer") else: print("Wrong answer") option = int(input("enter 0 , if you want to play again : ")) if (option): break print("welcome to fruit quiz ")fc=flashcard()fc.quiz() Output: jainlovely450 Picked Python Oops-programs Python-OOP Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Jun, 2022" }, { "code": null, "e": 412, "s": 52, "text": "In this article, we will see how to build a flashcard using class in python. A flashcard is a card having information on both sides, which can be used as an aid in memoization. Flashcards usually have a question on one side and an answer on the other. Particularly in this article, we are going to create flashcards that will be having a word and its meaning." }, { "code": null, "e": 450, "s": 412, "text": "Let’s see some examples of flashcard:" }, { "code": null, "e": 461, "s": 450, "text": "Example 1:" }, { "code": null, "e": 472, "s": 461, "text": "Approach :" }, { "code": null, "e": 526, "s": 472, "text": "Take the word and its meaning as input from the user." }, { "code": null, "e": 625, "s": 526, "text": "Create a class named flashcard, use the __init__() function to assign values for Word and Meaning." }, { "code": null, "e": 714, "s": 625, "text": "Now we use the __str__() function to return a string that contains the word and meaning." }, { "code": null, "e": 764, "s": 714, "text": "Store the returned strings in a list named flash." }, { "code": null, "e": 817, "s": 764, "text": "Use a while loop to print all the stored flashcards." }, { "code": null, "e": 851, "s": 817, "text": "Below is the full implementation:" }, { "code": null, "e": 859, "s": 851, "text": "Python3" }, { "code": "class flashcard: def __init__(self, word, meaning): self.word = word self.meaning = meaning def __str__(self): #we will return a string return self.word+' ( '+self.meaning+' )' flash = []print(\"welcome to flashcard application\") #the following loop will be repeated until#user stops to add the flashcardswhile(True): word = input(\"enter the name you want to add to flashcard : \") meaning = input(\"enter the meaning of the word : \") flash.append(flashcard(word, meaning)) option = int(input(\"enter 0 , if you want to add another flashcard : \")) if(option): break # printing all the flashcardsprint(\"\\nYour flashcards\")for i in flash: print(\">\", i)", "e": 1596, "s": 859, "text": null }, { "code": null, "e": 1604, "s": 1596, "text": "Output:" }, { "code": null, "e": 1615, "s": 1604, "text": "Example 2:" }, { "code": null, "e": 1626, "s": 1615, "text": "Approach :" }, { "code": null, "e": 1658, "s": 1626, "text": "Create a class named flashcard." }, { "code": null, "e": 1712, "s": 1658, "text": "Initialize dictionary fruits using __init__() method." }, { "code": null, "e": 1838, "s": 1712, "text": "Now randomly choose a pair from fruits using choice() method and store the key in variable fruit and value in variable color." }, { "code": null, "e": 1908, "s": 1838, "text": "Now prompt the user to answer the color of the randomly chosen fruit." }, { "code": null, "e": 1951, "s": 1908, "text": "If correct print correct else print wrong." }, { "code": null, "e": 1959, "s": 1951, "text": "Python3" }, { "code": "import random class flashcard: def __init__(self): self.fruits={'apple':'red', 'orange':'orange', 'watermelon':'green', 'banana':'yellow'} def quiz(self): while (True): fruit, color = random.choice(list(self.fruits.items())) print(\"What is the color of {}\".format(fruit)) user_answer = input() if(user_answer.lower() == color): print(\"Correct answer\") else: print(\"Wrong answer\") option = int(input(\"enter 0 , if you want to play again : \")) if (option): break print(\"welcome to fruit quiz \")fc=flashcard()fc.quiz()", "e": 2747, "s": 1959, "text": null }, { "code": null, "e": 2755, "s": 2747, "text": "Output:" }, { "code": null, "e": 2769, "s": 2755, "text": "jainlovely450" }, { "code": null, "e": 2776, "s": 2769, "text": "Picked" }, { "code": null, "e": 2797, "s": 2776, "text": "Python Oops-programs" }, { "code": null, "e": 2808, "s": 2797, "text": "Python-OOP" }, { "code": null, "e": 2815, "s": 2808, "text": "Python" } ]
Convert dataframe column to list in R
23 May, 2021 In this article, we will learn how to convert a dataframe into a list by columns in R Programming language. We will be using as.list() function, this function is used to convert an object to a list. These objects can be Vectors, Matrices, Factors, and data frames. Syntax: as.list( object ) Parameter: Dataframe object in our case After passing the complete dataframe as an input to the function, nothing much has to be done, the function will responsibly convert each column to a separate list, with column elements as elements of the list. Example 1: R df<-data.frame(c1=c(11:15), c2=c(16:20), c3=c(5:9), c4=c(1:5)) print("Sample Dataframe")print (df) list=as.list(df) print("After Conversion of Dataframe into list")print(list) Output: [1] "Sample Dataframe" c1 c2 c3 c4 1 11 16 5 1 2 12 17 6 2 3 13 18 7 3 4 14 19 8 4 5 15 20 9 5 [1] "After Conversion of Dataframe into list" $c1 [1] 11 12 13 14 15 $c2 [1] 16 17 18 19 20 $c3 [1] 5 6 7 8 9 $c4 [1] 1 2 3 4 5 Example 2: R df <- data.frame(sr_num = c(200, 400, 600), memory=c(128,256,1024), text = c("Geeks", "for", "Geeks")) print("Sample Dataframe")print (df) list=as.list(df) print("After Conversion of Dataframe into list")print(list) Output: [1] "Sample Dataframe" sr_num memory text 1 200 128 Geeks 2 400 256 for 3 600 1024 Geeks [1] "After Conversion of Dataframe into list" $sr_num [1] 200 400 600 $memory [1] 128 256 1024 $text [1] Geeks for Geeks Levels: for Geeks Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr How to Replace specific values in column in R DataFrame ? Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Replace specific values in column in R DataFrame ? How to Split Column Into Multiple Columns in R DataFrame? How to change Row Names of DataFrame in R ? How to filter R DataFrame by values in a column? Remove rows with NA in one column of R DataFrame
[ { "code": null, "e": 53, "s": 25, "text": "\n23 May, 2021" }, { "code": null, "e": 318, "s": 53, "text": "In this article, we will learn how to convert a dataframe into a list by columns in R Programming language. We will be using as.list() function, this function is used to convert an object to a list. These objects can be Vectors, Matrices, Factors, and data frames." }, { "code": null, "e": 344, "s": 318, "text": "Syntax: as.list( object )" }, { "code": null, "e": 384, "s": 344, "text": "Parameter: Dataframe object in our case" }, { "code": null, "e": 595, "s": 384, "text": "After passing the complete dataframe as an input to the function, nothing much has to be done, the function will responsibly convert each column to a separate list, with column elements as elements of the list." }, { "code": null, "e": 606, "s": 595, "text": "Example 1:" }, { "code": null, "e": 608, "s": 606, "text": "R" }, { "code": "df<-data.frame(c1=c(11:15), c2=c(16:20), c3=c(5:9), c4=c(1:5)) print(\"Sample Dataframe\")print (df) list=as.list(df) print(\"After Conversion of Dataframe into list\")print(list)", "e": 820, "s": 608, "text": null }, { "code": null, "e": 828, "s": 820, "text": "Output:" }, { "code": null, "e": 1063, "s": 828, "text": "[1] \"Sample Dataframe\"\n c1 c2 c3 c4\n1 11 16 5 1\n2 12 17 6 2\n3 13 18 7 3\n4 14 19 8 4\n5 15 20 9 5\n[1] \"After Conversion of Dataframe into list\"\n$c1\n[1] 11 12 13 14 15\n$c2\n[1] 16 17 18 19 20\n$c3\n[1] 5 6 7 8 9\n$c4\n[1] 1 2 3 4 5" }, { "code": null, "e": 1074, "s": 1063, "text": "Example 2:" }, { "code": null, "e": 1076, "s": 1074, "text": "R" }, { "code": "df <- data.frame(sr_num = c(200, 400, 600), memory=c(128,256,1024), text = c(\"Geeks\", \"for\", \"Geeks\")) print(\"Sample Dataframe\")print (df) list=as.list(df) print(\"After Conversion of Dataframe into list\")print(list)", "e": 1325, "s": 1076, "text": null }, { "code": null, "e": 1333, "s": 1325, "text": "Output:" }, { "code": null, "e": 1587, "s": 1333, "text": "[1] \"Sample Dataframe\"\n sr_num memory text\n1 200 128 Geeks\n2 400 256 for\n3 600 1024 Geeks\n[1] \"After Conversion of Dataframe into list\"\n$sr_num\n[1] 200 400 600\n$memory\n[1] 128 256 1024\n$text\n[1] Geeks for Geeks\nLevels: for Geeks" }, { "code": null, "e": 1594, "s": 1587, "text": "Picked" }, { "code": null, "e": 1615, "s": 1594, "text": "R DataFrame-Programs" }, { "code": null, "e": 1627, "s": 1615, "text": "R-DataFrame" }, { "code": null, "e": 1638, "s": 1627, "text": "R Language" }, { "code": null, "e": 1649, "s": 1638, "text": "R Programs" }, { "code": null, "e": 1747, "s": 1649, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1799, "s": 1747, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 1857, "s": 1799, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 1909, "s": 1857, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 1967, "s": 1909, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2002, "s": 1967, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 2060, "s": 2002, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 2118, "s": 2060, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2162, "s": 2118, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 2211, "s": 2162, "text": "How to filter R DataFrame by values in a column?" } ]
Ruby | String empty? Method
08 Jan, 2020 empty? is a String class method in Ruby which is used to check whether the string length is zero or not. Syntax: str.empty? Parameters: Here, str is the given string which is to be checked. Returns: It returns true if str has a length of zero, otherwise false. Example 1: # Ruby program to demonstrate# the empty? method # Taking a string and# using the methodputs "checking".empty?puts "method".empty? Output: false false Example 2: # Ruby program to demonstrate# the empty? method # Taking a string and# using the methodputs "".empty?puts ".".empty? Output: true false Ruby String-class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Make a Custom Array of Hashes in Ruby? Include v/s Extend in Ruby Global Variable in Ruby Ruby | Enumerator each_with_index function Ruby | Array select() function Ruby | Case Statement Ruby | unless Statement and unless Modifier Ruby | Hash delete() function Ruby | Data Types Ruby | Array class find_index() operation
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jan, 2020" }, { "code": null, "e": 133, "s": 28, "text": "empty? is a String class method in Ruby which is used to check whether the string length is zero or not." }, { "code": null, "e": 152, "s": 133, "text": "Syntax: str.empty?" }, { "code": null, "e": 218, "s": 152, "text": "Parameters: Here, str is the given string which is to be checked." }, { "code": null, "e": 289, "s": 218, "text": "Returns: It returns true if str has a length of zero, otherwise false." }, { "code": null, "e": 300, "s": 289, "text": "Example 1:" }, { "code": "# Ruby program to demonstrate# the empty? method # Taking a string and# using the methodputs \"checking\".empty?puts \"method\".empty?", "e": 433, "s": 300, "text": null }, { "code": null, "e": 441, "s": 433, "text": "Output:" }, { "code": null, "e": 454, "s": 441, "text": "false\nfalse\n" }, { "code": null, "e": 465, "s": 454, "text": "Example 2:" }, { "code": "# Ruby program to demonstrate# the empty? method # Taking a string and# using the methodputs \"\".empty?puts \".\".empty?", "e": 585, "s": 465, "text": null }, { "code": null, "e": 593, "s": 585, "text": "Output:" }, { "code": null, "e": 605, "s": 593, "text": "true\nfalse\n" }, { "code": null, "e": 623, "s": 605, "text": "Ruby String-class" }, { "code": null, "e": 636, "s": 623, "text": "Ruby-Methods" }, { "code": null, "e": 641, "s": 636, "text": "Ruby" }, { "code": null, "e": 739, "s": 641, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 785, "s": 739, "text": "How to Make a Custom Array of Hashes in Ruby?" }, { "code": null, "e": 812, "s": 785, "text": "Include v/s Extend in Ruby" }, { "code": null, "e": 836, "s": 812, "text": "Global Variable in Ruby" }, { "code": null, "e": 879, "s": 836, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 910, "s": 879, "text": "Ruby | Array select() function" }, { "code": null, "e": 932, "s": 910, "text": "Ruby | Case Statement" }, { "code": null, "e": 976, "s": 932, "text": "Ruby | unless Statement and unless Modifier" }, { "code": null, "e": 1006, "s": 976, "text": "Ruby | Hash delete() function" }, { "code": null, "e": 1024, "s": 1006, "text": "Ruby | Data Types" } ]
Create Air Canvas using Python-OpenCV
10 Jan, 2022 Ever wanted to draw your imagination by just waving your finger in the air. In this post, we will learn to build an Air Canvas which can draw anything on it by just capturing the motion of a colored marker with a camera. Here a colored object at the tip of the finger is used as the marker.We will be using the computer vision techniques of OpenCV to build this project. The preferred language is Python due to its exhaustive libraries and easy to use syntax but understanding the basics it can be implemented in any OpenCV supported language.Here Color Detection and tracking are used in order to achieve the objective. The color marker is detected and a mask is produced. It includes the further steps of morphological operations on the mask produced which are Erosion and Dilation. Erosion reduces the impurities present in the mask and dilation further restores the eroded main mask.Requirements: Python3 NumPy OpenCV Algorithm: Start reading the frames and convert the captured frames to HSV color space (Easy for color detection). Prepare the canvas frame and put the respective ink buttons on it. Adjust the track bar values for finding the mask of the colored marker. Preprocess the mask with morphological operations (Eroding and dilation). Detect the contours, find the center coordinates of largest contour and keep storing them in the array for successive frames (Arrays for drawing points on canvas). Finally draw the points stored in an array on the frames and canvas. Start reading the frames and convert the captured frames to HSV color space (Easy for color detection). Prepare the canvas frame and put the respective ink buttons on it. Adjust the track bar values for finding the mask of the colored marker. Preprocess the mask with morphological operations (Eroding and dilation). Detect the contours, find the center coordinates of largest contour and keep storing them in the array for successive frames (Arrays for drawing points on canvas). Finally draw the points stored in an array on the frames and canvas. Below is the implementation. Python3 import numpy as npimport cv2from collections import deque # default called trackbar functiondef setValues(x): print("") # Creating the trackbars needed for# adjusting the marker colour These# trackbars will be used for setting# the upper and lower ranges of the# HSV required for particular colourcv2.namedWindow("Color detectors")cv2.createTrackbar("Upper Hue", "Color detectors", 153, 180, setValues)cv2.createTrackbar("Upper Saturation", "Color detectors", 255, 255, setValues)cv2.createTrackbar("Upper Value", "Color detectors", 255, 255, setValues)cv2.createTrackbar("Lower Hue", "Color detectors", 64, 180, setValues)cv2.createTrackbar("Lower Saturation", "Color detectors", 72, 255, setValues)cv2.createTrackbar("Lower Value", "Color detectors", 49, 255, setValues) # Giving different arrays to handle colour# points of different colour These arrays# will hold the points of a particular colour# in the array which will further be used# to draw on canvasbpoints = [deque(maxlen = 1024)]gpoints = [deque(maxlen = 1024)]rpoints = [deque(maxlen = 1024)]ypoints = [deque(maxlen = 1024)] # These indexes will be used to mark position# of pointers in colour arrayblue_index = 0green_index = 0red_index = 0yellow_index = 0 # The kernel to be used for dilation purposekernel = np.ones((5, 5), np.uint8) # The colours which will be used as ink for# the drawing purposecolors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (0, 255, 255)]colorIndex = 0 # Here is code for Canvas setuppaintWindow = np.zeros((471, 636, 3)) + 255 cv2.namedWindow('Paint', cv2.WINDOW_AUTOSIZE) # Loading the default webcam of PC.cap = cv2.VideoCapture(0) # Keep loopingwhile True: # Reading the frame from the camera ret, frame = cap.read() # Flipping the frame to see same side of yours frame = cv2.flip(frame, 1) hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # Getting the updated positions of the trackbar # and setting the HSV values u_hue = cv2.getTrackbarPos("Upper Hue", "Color detectors") u_saturation = cv2.getTrackbarPos("Upper Saturation", "Color detectors") u_value = cv2.getTrackbarPos("Upper Value", "Color detectors") l_hue = cv2.getTrackbarPos("Lower Hue", "Color detectors") l_saturation = cv2.getTrackbarPos("Lower Saturation", "Color detectors") l_value = cv2.getTrackbarPos("Lower Value", "Color detectors") Upper_hsv = np.array([u_hue, u_saturation, u_value]) Lower_hsv = np.array([l_hue, l_saturation, l_value]) # Adding the colour buttons to the live frame # for colour access frame = cv2.rectangle(frame, (40, 1), (140, 65), (122, 122, 122), -1) frame = cv2.rectangle(frame, (160, 1), (255, 65), colors[0], -1) frame = cv2.rectangle(frame, (275, 1), (370, 65), colors[1], -1) frame = cv2.rectangle(frame, (390, 1), (485, 65), colors[2], -1) frame = cv2.rectangle(frame, (505, 1), (600, 65), colors[3], -1) cv2.putText(frame, "CLEAR ALL", (49, 33), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2, cv2.LINE_AA) cv2.putText(frame, "BLUE", (185, 33), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2, cv2.LINE_AA) cv2.putText(frame, "GREEN", (298, 33), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2, cv2.LINE_AA) cv2.putText(frame, "RED", (420, 33), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2, cv2.LINE_AA) cv2.putText(frame, "YELLOW", (520, 33), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (150, 150, 150), 2, cv2.LINE_AA) # Identifying the pointer by making its # mask Mask = cv2.inRange(hsv, Lower_hsv, Upper_hsv) Mask = cv2.erode(Mask, kernel, iterations = 1) Mask = cv2.morphologyEx(Mask, cv2.MORPH_OPEN, kernel) Mask = cv2.dilate(Mask, kernel, iterations = 1) # Find contours for the pointer after # identifying it cnts, _ = cv2.findContours(Mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) center = None # Ifthe contours are formed if len(cnts) > 0: # sorting the contours to find biggest cnt = sorted(cnts, key = cv2.contourArea, reverse = True)[0] # Get the radius of the enclosing circle # around the found contour ((x, y), radius) = cv2.minEnclosingCircle(cnt) # Draw the circle around the contour cv2.circle(frame, (int(x), int(y)), int(radius), (0, 255, 255), 2) # Calculating the center of the detected contour M = cv2.moments(cnt) center = (int(M['m10'] / M['m00']), int(M['m01'] / M['m00'])) # Now checking if the user wants to click on # any button above the screen if center[1] <= 65: # Clear Button if 40 <= center[0] <= 140: bpoints = [deque(maxlen = 512)] gpoints = [deque(maxlen = 512)] rpoints = [deque(maxlen = 512)] ypoints = [deque(maxlen = 512)] blue_index = 0 green_index = 0 red_index = 0 yellow_index = 0 paintWindow[67:, :, :] = 255 elif 160 <= center[0] <= 255: colorIndex = 0 # Blue elif 275 <= center[0] <= 370: colorIndex = 1 # Green elif 390 <= center[0] <= 485: colorIndex = 2 # Red elif 505 <= center[0] <= 600: colorIndex = 3 # Yellow else : if colorIndex == 0: bpoints[blue_index].appendleft(center) elif colorIndex == 1: gpoints[green_index].appendleft(center) elif colorIndex == 2: rpoints[red_index].appendleft(center) elif colorIndex == 3: ypoints[yellow_index].appendleft(center) # Append the next deques when nothing is # detected to avois messing up else: bpoints.append(deque(maxlen = 512)) blue_index += 1 gpoints.append(deque(maxlen = 512)) green_index += 1 rpoints.append(deque(maxlen = 512)) red_index += 1 ypoints.append(deque(maxlen = 512)) yellow_index += 1 # Draw lines of all the colors on the # canvas and frame points = [bpoints, gpoints, rpoints, ypoints] for i in range(len(points)): for j in range(len(points[i])): for k in range(1, len(points[i][j])): if points[i][j][k - 1] is None or points[i][j][k] is None: continue cv2.line(frame, points[i][j][k - 1], points[i][j][k], colors[i], 2) cv2.line(paintWindow, points[i][j][k - 1], points[i][j][k], colors[i], 2) # Show all the windows cv2.imshow("Tracking", frame) cv2.imshow("Paint", paintWindow) cv2.imshow("mask", Mask) # If the 'q' key is pressed then stop the application if cv2.waitKey(1) & 0xFF == ord("q"): break # Release the camera and all resourcescap.release()cv2.destroyAllWindows() Output: kk9826225 Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Jan, 2022" }, { "code": null, "e": 957, "s": 54, "text": "Ever wanted to draw your imagination by just waving your finger in the air. In this post, we will learn to build an Air Canvas which can draw anything on it by just capturing the motion of a colored marker with a camera. Here a colored object at the tip of the finger is used as the marker.We will be using the computer vision techniques of OpenCV to build this project. The preferred language is Python due to its exhaustive libraries and easy to use syntax but understanding the basics it can be implemented in any OpenCV supported language.Here Color Detection and tracking are used in order to achieve the objective. The color marker is detected and a mask is produced. It includes the further steps of morphological operations on the mask produced which are Erosion and Dilation. Erosion reduces the impurities present in the mask and dilation further restores the eroded main mask.Requirements: " }, { "code": null, "e": 967, "s": 957, "text": "Python3 " }, { "code": null, "e": 975, "s": 967, "text": "NumPy " }, { "code": null, "e": 984, "s": 975, "text": "OpenCV " }, { "code": null, "e": 997, "s": 984, "text": "Algorithm: " }, { "code": null, "e": 1553, "s": 997, "text": "Start reading the frames and convert the captured frames to HSV color space (Easy for color detection). Prepare the canvas frame and put the respective ink buttons on it. Adjust the track bar values for finding the mask of the colored marker. Preprocess the mask with morphological operations (Eroding and dilation). Detect the contours, find the center coordinates of largest contour and keep storing them in the array for successive frames (Arrays for drawing points on canvas). Finally draw the points stored in an array on the frames and canvas. " }, { "code": null, "e": 1659, "s": 1553, "text": "Start reading the frames and convert the captured frames to HSV color space (Easy for color detection). " }, { "code": null, "e": 1728, "s": 1659, "text": "Prepare the canvas frame and put the respective ink buttons on it. " }, { "code": null, "e": 1802, "s": 1728, "text": "Adjust the track bar values for finding the mask of the colored marker. " }, { "code": null, "e": 1878, "s": 1802, "text": "Preprocess the mask with morphological operations (Eroding and dilation). " }, { "code": null, "e": 2044, "s": 1878, "text": "Detect the contours, find the center coordinates of largest contour and keep storing them in the array for successive frames (Arrays for drawing points on canvas). " }, { "code": null, "e": 2114, "s": 2044, "text": "Finally draw the points stored in an array on the frames and canvas. " }, { "code": null, "e": 2144, "s": 2114, "text": "Below is the implementation. " }, { "code": null, "e": 2152, "s": 2144, "text": "Python3" }, { "code": "import numpy as npimport cv2from collections import deque # default called trackbar functiondef setValues(x): print(\"\") # Creating the trackbars needed for# adjusting the marker colour These# trackbars will be used for setting# the upper and lower ranges of the# HSV required for particular colourcv2.namedWindow(\"Color detectors\")cv2.createTrackbar(\"Upper Hue\", \"Color detectors\", 153, 180, setValues)cv2.createTrackbar(\"Upper Saturation\", \"Color detectors\", 255, 255, setValues)cv2.createTrackbar(\"Upper Value\", \"Color detectors\", 255, 255, setValues)cv2.createTrackbar(\"Lower Hue\", \"Color detectors\", 64, 180, setValues)cv2.createTrackbar(\"Lower Saturation\", \"Color detectors\", 72, 255, setValues)cv2.createTrackbar(\"Lower Value\", \"Color detectors\", 49, 255, setValues) # Giving different arrays to handle colour# points of different colour These arrays# will hold the points of a particular colour# in the array which will further be used# to draw on canvasbpoints = [deque(maxlen = 1024)]gpoints = [deque(maxlen = 1024)]rpoints = [deque(maxlen = 1024)]ypoints = [deque(maxlen = 1024)] # These indexes will be used to mark position# of pointers in colour arrayblue_index = 0green_index = 0red_index = 0yellow_index = 0 # The kernel to be used for dilation purposekernel = np.ones((5, 5), np.uint8) # The colours which will be used as ink for# the drawing purposecolors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (0, 255, 255)]colorIndex = 0 # Here is code for Canvas setuppaintWindow = np.zeros((471, 636, 3)) + 255 cv2.namedWindow('Paint', cv2.WINDOW_AUTOSIZE) # Loading the default webcam of PC.cap = cv2.VideoCapture(0) # Keep loopingwhile True: # Reading the frame from the camera ret, frame = cap.read() # Flipping the frame to see same side of yours frame = cv2.flip(frame, 1) hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # Getting the updated positions of the trackbar # and setting the HSV values u_hue = cv2.getTrackbarPos(\"Upper Hue\", \"Color detectors\") u_saturation = cv2.getTrackbarPos(\"Upper Saturation\", \"Color detectors\") u_value = cv2.getTrackbarPos(\"Upper Value\", \"Color detectors\") l_hue = cv2.getTrackbarPos(\"Lower Hue\", \"Color detectors\") l_saturation = cv2.getTrackbarPos(\"Lower Saturation\", \"Color detectors\") l_value = cv2.getTrackbarPos(\"Lower Value\", \"Color detectors\") Upper_hsv = np.array([u_hue, u_saturation, u_value]) Lower_hsv = np.array([l_hue, l_saturation, l_value]) # Adding the colour buttons to the live frame # for colour access frame = cv2.rectangle(frame, (40, 1), (140, 65), (122, 122, 122), -1) frame = cv2.rectangle(frame, (160, 1), (255, 65), colors[0], -1) frame = cv2.rectangle(frame, (275, 1), (370, 65), colors[1], -1) frame = cv2.rectangle(frame, (390, 1), (485, 65), colors[2], -1) frame = cv2.rectangle(frame, (505, 1), (600, 65), colors[3], -1) cv2.putText(frame, \"CLEAR ALL\", (49, 33), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2, cv2.LINE_AA) cv2.putText(frame, \"BLUE\", (185, 33), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2, cv2.LINE_AA) cv2.putText(frame, \"GREEN\", (298, 33), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2, cv2.LINE_AA) cv2.putText(frame, \"RED\", (420, 33), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2, cv2.LINE_AA) cv2.putText(frame, \"YELLOW\", (520, 33), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (150, 150, 150), 2, cv2.LINE_AA) # Identifying the pointer by making its # mask Mask = cv2.inRange(hsv, Lower_hsv, Upper_hsv) Mask = cv2.erode(Mask, kernel, iterations = 1) Mask = cv2.morphologyEx(Mask, cv2.MORPH_OPEN, kernel) Mask = cv2.dilate(Mask, kernel, iterations = 1) # Find contours for the pointer after # identifying it cnts, _ = cv2.findContours(Mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) center = None # Ifthe contours are formed if len(cnts) > 0: # sorting the contours to find biggest cnt = sorted(cnts, key = cv2.contourArea, reverse = True)[0] # Get the radius of the enclosing circle # around the found contour ((x, y), radius) = cv2.minEnclosingCircle(cnt) # Draw the circle around the contour cv2.circle(frame, (int(x), int(y)), int(radius), (0, 255, 255), 2) # Calculating the center of the detected contour M = cv2.moments(cnt) center = (int(M['m10'] / M['m00']), int(M['m01'] / M['m00'])) # Now checking if the user wants to click on # any button above the screen if center[1] <= 65: # Clear Button if 40 <= center[0] <= 140: bpoints = [deque(maxlen = 512)] gpoints = [deque(maxlen = 512)] rpoints = [deque(maxlen = 512)] ypoints = [deque(maxlen = 512)] blue_index = 0 green_index = 0 red_index = 0 yellow_index = 0 paintWindow[67:, :, :] = 255 elif 160 <= center[0] <= 255: colorIndex = 0 # Blue elif 275 <= center[0] <= 370: colorIndex = 1 # Green elif 390 <= center[0] <= 485: colorIndex = 2 # Red elif 505 <= center[0] <= 600: colorIndex = 3 # Yellow else : if colorIndex == 0: bpoints[blue_index].appendleft(center) elif colorIndex == 1: gpoints[green_index].appendleft(center) elif colorIndex == 2: rpoints[red_index].appendleft(center) elif colorIndex == 3: ypoints[yellow_index].appendleft(center) # Append the next deques when nothing is # detected to avois messing up else: bpoints.append(deque(maxlen = 512)) blue_index += 1 gpoints.append(deque(maxlen = 512)) green_index += 1 rpoints.append(deque(maxlen = 512)) red_index += 1 ypoints.append(deque(maxlen = 512)) yellow_index += 1 # Draw lines of all the colors on the # canvas and frame points = [bpoints, gpoints, rpoints, ypoints] for i in range(len(points)): for j in range(len(points[i])): for k in range(1, len(points[i][j])): if points[i][j][k - 1] is None or points[i][j][k] is None: continue cv2.line(frame, points[i][j][k - 1], points[i][j][k], colors[i], 2) cv2.line(paintWindow, points[i][j][k - 1], points[i][j][k], colors[i], 2) # Show all the windows cv2.imshow(\"Tracking\", frame) cv2.imshow(\"Paint\", paintWindow) cv2.imshow(\"mask\", Mask) # If the 'q' key is pressed then stop the application if cv2.waitKey(1) & 0xFF == ord(\"q\"): break # Release the camera and all resourcescap.release()cv2.destroyAllWindows()", "e": 9739, "s": 2152, "text": null }, { "code": null, "e": 9749, "s": 9739, "text": "Output: " }, { "code": null, "e": 9763, "s": 9753, "text": "kk9826225" }, { "code": null, "e": 9777, "s": 9763, "text": "Python-OpenCV" }, { "code": null, "e": 9784, "s": 9777, "text": "Python" }, { "code": null, "e": 9882, "s": 9784, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9914, "s": 9882, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 9941, "s": 9914, "text": "Python Classes and Objects" }, { "code": null, "e": 9962, "s": 9941, "text": "Python OOPs Concepts" }, { "code": null, "e": 9985, "s": 9962, "text": "Introduction To PYTHON" }, { "code": null, "e": 10041, "s": 9985, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 10072, "s": 10041, "text": "Python | os.path.join() method" }, { "code": null, "e": 10114, "s": 10072, "text": "Check if element exists in list in Python" }, { "code": null, "e": 10156, "s": 10114, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 10195, "s": 10156, "text": "Python | Get unique values from a list" } ]
Delete nodes which have a greater value on right side using recursion
30 Mar, 2022 Given a singly linked list, remove all the nodes which have a greater value on the right side. Examples: a) The list 12->15->10->11->5->6->2->3->NULL should be changed to 15->11->6->3->NULL. Note that 12, 10, 5 and 2 have been deleted because there is a greater value on the right side. When we examine 12, we see that after 12 there is one node with a value greater than 12 (i.e. 15), so we delete 12. When we examine 15, we find no node after 15 that has a value greater than 15 so we keep this node. When we go like this, we get 15->6->3b) The list 10->20->30->40->50->60->NULL should be changed to 60->NULL. Note that 10, 20, 30, 40 and 50 have been deleted because they all have a greater value on the right side.c) The list 60->50->40->30->20->10->NULL should not be changed. Approach: We have already solved this problem by using 2 loops and reversing linked list in the post Delete nodes which have a greater value on right sideHere we will discuss the solution without reversing the list. We will use recursion to solve this problem in which the base case would be when the head is pointing to NULL. Else we would be recursively calling function for the next node and updating max value if currentNode->data > currentMax. In this way, the whole list would be updated.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; /* structure of a linked list node */struct Node { int data; struct Node* next;}; /*Utility function to find maximum value*/int maxVal(int a, int b){ if (a > b) return a; return b;} /* Function to delete nodes which havea node with greater value nodeon left side */struct Node* delNodes(struct Node* head, int* max){ // Base case if (head == NULL) { return head; } head->next = delNodes(head->next, max); if (head->data < *max) { return head->next; } *max = maxVal(head->data, *max); return head;} /* Utility function to insert a node at the beginning */void push(struct Node** head, int new_data){ struct Node* new_node = new Node; new_node->data = new_data; new_node->next = *head; *head = new_node;} /* Utility function to print a linked list */void printList(struct Node* head){ while (head != NULL) { cout << head->data << " "; head = head->next; } cout << endl;} /* Driver program to test above functions */int main(){ struct Node* head = NULL; /* Create following linked list 12->15->10->11->5->6->2->3 */ push(&head, 3); push(&head, 2); push(&head, 6); push(&head, 5); push(&head, 11); push(&head, 10); push(&head, 15); push(&head, 12); cout << "Given Linked List" << endl; printList(head); int max = INT_MIN; head = delNodes(head, &max); cout << "Modified Linked List" << endl; printList(head); return 0;} // Java implementation of the approachclass GFG{ /* structure of a linked list node */static class Node{ int data; Node next;};static Node head;static int max; /*Utility function to find maximum value*/static int maxVal(int a, int b){ if (a > b) return a; return b;} /* Function to delete nodes which havea node with greater value nodeon left side */static Node delNodes(Node head){ // Base case if (head == null) { return head; } head.next = delNodes(head.next); if (head.data < max) { return head.next; } max = maxVal(head.data, max); return head;} /* Utility function to insert a nodeat the beginning */static void push(Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; head = head_ref;} /* Utility function to print a linked list */static void printList(Node head){ while (head != null) { System.out.print(head.data + " "); head = head.next; } System.out.println();} // Driver Codepublic static void main(String[] args){ head = null; /* Create following linked list 12.15.10.11.5.6.2.3 */ push(head, 3); push(head, 2); push(head, 6); push(head, 5); push(head, 11); push(head, 10); push(head, 15); push(head, 12); System.out.println("Given Linked List"); printList(head); max = Integer.MIN_VALUE; head = delNodes(head); System.out.println("Modified Linked List"); printList(head);}} // This code is contributed by 29AjayKumar # Python3 program to reverse a linked# list using a stack # Link list nodeclass Node: def __init__(self, data, next): self.data = data self.next = next class LinkedList: def __init__(self): self.head = None # Function to push a new Node in # the linked list def push(self, new_data): new_node = Node(new_data, self.head) self.head = new_node # Function to delete nodes which have a node # with greater value node on left side def delNodes(self, head): # Base case if head == None: return head global Max head.next = self.delNodes(head.next) if head.data < Max: return head.next Max = max(head.data, Max) return head # Function to print the Linked list def printList(self): curr = self.head while curr: print(curr.data, end = " ") curr = curr.next print() # Driver Codeif __name__ == "__main__": # Start with the empty list linkedList = LinkedList() # Create following linked list # 12->15->10->11->5->6->2->3 linkedList.push(3) linkedList.push(2) linkedList.push(6) linkedList.push(5) linkedList.push(11) linkedList.push(10) linkedList.push(15) linkedList.push(12) print("Given Linked List") linkedList.printList() Max = float('-inf') linkedList.head = linkedList.delNodes(linkedList.head) print("Modified Linked List") linkedList.printList() # This code is contributed by Rituraj Jain // C# implementation of the approachusing System; class GFG{ /* structure of a linked list node */public class Node{ public int data; public Node next;};static Node head;static int max; /*Utility function to find maximum value*/static int maxVal(int a, int b){ if (a > b) return a; return b;} /* Function to delete nodes which havea node with greater value nodeon left side */static Node delNodes(Node head){ // Base case if (head == null) { return head; } head.next = delNodes(head.next); if (head.data < max) { return head.next; } max = maxVal(head.data, max); return head;} /* Utility function to insert a nodeat the beginning */static void push(Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; head = head_ref;} /* Utility function to print a linked list */static void printList(Node head){ while (head != null) { Console.Write(head.data + " "); head = head.next; } Console.WriteLine();} // Driver Codepublic static void Main(String[] args){ head = null; /* Create following linked list 12.15.10.11.5.6.2.3 */ push(head, 3); push(head, 2); push(head, 6); push(head, 5); push(head, 11); push(head, 10); push(head, 15); push(head, 12); Console.WriteLine("Given Linked List"); printList(head); max = int.MinValue; head = delNodes(head); Console.WriteLine("Modified Linked List"); printList(head);}} // This code is contributed by PrinciRaj1992 <script> // JavaScript implementation of the approach /* structure of a linked list node */ class Node { constructor() { this.data = 0; this.next = null; } } var head; var max; /*Utility function to find maximum value*/ function maxVal(a, b) { if (a > b) return a; return b; } /* Function to delete nodes which have a node with greater value node on left side */ function delNodes(head) { // Base case if (head == null) { return head; } head.next = delNodes(head.next); if (head.data < max) { return head.next; } max = maxVal(head.data, max); return head; } /* Utility function to insert a node at the beginning */ function push(head_ref, new_data) { var new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; head = head_ref; } /* Utility function to print a linked list */ function printList(head) { while (head != null) { document.write(head.data + " "); head = head.next; } document.write("<br>"); } // Driver Code head = null; /* Create following linked list 12.15.10.11.5.6.2.3 */ push(head, 3); push(head, 2); push(head, 6); push(head, 5); push(head, 11); push(head, 10); push(head, 15); push(head, 12); document.write("Given Linked List <br>"); printList(head); max = -2147483648; head = delNodes(head); document.write("Modified Linked List <br>"); printList(head); </script> Given Linked List 12 15 10 11 5 6 2 3 Modified Linked List 15 11 6 3 Time Complexity: O(N) Auxiliary Space: O(1) rituraj_jain 29AjayKumar princiraj1992 Akanksha_Rai rdtank rohan07 Linked List Recursion Linked List Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures What is Data Structure: Types, Classifications and Applications Types of Linked List Circular Singly Linked List | Insertion Find first node of loop in a linked list 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": 54, "s": 26, "text": "\n30 Mar, 2022" }, { "code": null, "e": 837, "s": 54, "text": "Given a singly linked list, remove all the nodes which have a greater value on the right side. Examples: a) The list 12->15->10->11->5->6->2->3->NULL should be changed to 15->11->6->3->NULL. Note that 12, 10, 5 and 2 have been deleted because there is a greater value on the right side. When we examine 12, we see that after 12 there is one node with a value greater than 12 (i.e. 15), so we delete 12. When we examine 15, we find no node after 15 that has a value greater than 15 so we keep this node. When we go like this, we get 15->6->3b) The list 10->20->30->40->50->60->NULL should be changed to 60->NULL. Note that 10, 20, 30, 40 and 50 have been deleted because they all have a greater value on the right side.c) The list 60->50->40->30->20->10->NULL should not be changed. " }, { "code": null, "e": 1383, "s": 837, "text": "Approach: We have already solved this problem by using 2 loops and reversing linked list in the post Delete nodes which have a greater value on right sideHere we will discuss the solution without reversing the list. We will use recursion to solve this problem in which the base case would be when the head is pointing to NULL. Else we would be recursively calling function for the next node and updating max value if currentNode->data > currentMax. In this way, the whole list would be updated.Below is the implementation of the above approach: " }, { "code": null, "e": 1387, "s": 1383, "text": "C++" }, { "code": null, "e": 1392, "s": 1387, "text": "Java" }, { "code": null, "e": 1400, "s": 1392, "text": "Python3" }, { "code": null, "e": 1403, "s": 1400, "text": "C#" }, { "code": null, "e": 1414, "s": 1403, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; /* structure of a linked list node */struct Node { int data; struct Node* next;}; /*Utility function to find maximum value*/int maxVal(int a, int b){ if (a > b) return a; return b;} /* Function to delete nodes which havea node with greater value nodeon left side */struct Node* delNodes(struct Node* head, int* max){ // Base case if (head == NULL) { return head; } head->next = delNodes(head->next, max); if (head->data < *max) { return head->next; } *max = maxVal(head->data, *max); return head;} /* Utility function to insert a node at the beginning */void push(struct Node** head, int new_data){ struct Node* new_node = new Node; new_node->data = new_data; new_node->next = *head; *head = new_node;} /* Utility function to print a linked list */void printList(struct Node* head){ while (head != NULL) { cout << head->data << \" \"; head = head->next; } cout << endl;} /* Driver program to test above functions */int main(){ struct Node* head = NULL; /* Create following linked list 12->15->10->11->5->6->2->3 */ push(&head, 3); push(&head, 2); push(&head, 6); push(&head, 5); push(&head, 11); push(&head, 10); push(&head, 15); push(&head, 12); cout << \"Given Linked List\" << endl; printList(head); int max = INT_MIN; head = delNodes(head, &max); cout << \"Modified Linked List\" << endl; printList(head); return 0;}", "e": 2963, "s": 1414, "text": null }, { "code": "// Java implementation of the approachclass GFG{ /* structure of a linked list node */static class Node{ int data; Node next;};static Node head;static int max; /*Utility function to find maximum value*/static int maxVal(int a, int b){ if (a > b) return a; return b;} /* Function to delete nodes which havea node with greater value nodeon left side */static Node delNodes(Node head){ // Base case if (head == null) { return head; } head.next = delNodes(head.next); if (head.data < max) { return head.next; } max = maxVal(head.data, max); return head;} /* Utility function to insert a nodeat the beginning */static void push(Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; head = head_ref;} /* Utility function to print a linked list */static void printList(Node head){ while (head != null) { System.out.print(head.data + \" \"); head = head.next; } System.out.println();} // Driver Codepublic static void main(String[] args){ head = null; /* Create following linked list 12.15.10.11.5.6.2.3 */ push(head, 3); push(head, 2); push(head, 6); push(head, 5); push(head, 11); push(head, 10); push(head, 15); push(head, 12); System.out.println(\"Given Linked List\"); printList(head); max = Integer.MIN_VALUE; head = delNodes(head); System.out.println(\"Modified Linked List\"); printList(head);}} // This code is contributed by 29AjayKumar", "e": 4553, "s": 2963, "text": null }, { "code": "# Python3 program to reverse a linked# list using a stack # Link list nodeclass Node: def __init__(self, data, next): self.data = data self.next = next class LinkedList: def __init__(self): self.head = None # Function to push a new Node in # the linked list def push(self, new_data): new_node = Node(new_data, self.head) self.head = new_node # Function to delete nodes which have a node # with greater value node on left side def delNodes(self, head): # Base case if head == None: return head global Max head.next = self.delNodes(head.next) if head.data < Max: return head.next Max = max(head.data, Max) return head # Function to print the Linked list def printList(self): curr = self.head while curr: print(curr.data, end = \" \") curr = curr.next print() # Driver Codeif __name__ == \"__main__\": # Start with the empty list linkedList = LinkedList() # Create following linked list # 12->15->10->11->5->6->2->3 linkedList.push(3) linkedList.push(2) linkedList.push(6) linkedList.push(5) linkedList.push(11) linkedList.push(10) linkedList.push(15) linkedList.push(12) print(\"Given Linked List\") linkedList.printList() Max = float('-inf') linkedList.head = linkedList.delNodes(linkedList.head) print(\"Modified Linked List\") linkedList.printList() # This code is contributed by Rituraj Jain", "e": 6152, "s": 4553, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ /* structure of a linked list node */public class Node{ public int data; public Node next;};static Node head;static int max; /*Utility function to find maximum value*/static int maxVal(int a, int b){ if (a > b) return a; return b;} /* Function to delete nodes which havea node with greater value nodeon left side */static Node delNodes(Node head){ // Base case if (head == null) { return head; } head.next = delNodes(head.next); if (head.data < max) { return head.next; } max = maxVal(head.data, max); return head;} /* Utility function to insert a nodeat the beginning */static void push(Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; head = head_ref;} /* Utility function to print a linked list */static void printList(Node head){ while (head != null) { Console.Write(head.data + \" \"); head = head.next; } Console.WriteLine();} // Driver Codepublic static void Main(String[] args){ head = null; /* Create following linked list 12.15.10.11.5.6.2.3 */ push(head, 3); push(head, 2); push(head, 6); push(head, 5); push(head, 11); push(head, 10); push(head, 15); push(head, 12); Console.WriteLine(\"Given Linked List\"); printList(head); max = int.MinValue; head = delNodes(head); Console.WriteLine(\"Modified Linked List\"); printList(head);}} // This code is contributed by PrinciRaj1992", "e": 7759, "s": 6152, "text": null }, { "code": "<script> // JavaScript implementation of the approach /* structure of a linked list node */ class Node { constructor() { this.data = 0; this.next = null; } } var head; var max; /*Utility function to find maximum value*/ function maxVal(a, b) { if (a > b) return a; return b; } /* Function to delete nodes which have a node with greater value node on left side */ function delNodes(head) { // Base case if (head == null) { return head; } head.next = delNodes(head.next); if (head.data < max) { return head.next; } max = maxVal(head.data, max); return head; } /* Utility function to insert a node at the beginning */ function push(head_ref, new_data) { var new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; head = head_ref; } /* Utility function to print a linked list */ function printList(head) { while (head != null) { document.write(head.data + \" \"); head = head.next; } document.write(\"<br>\"); } // Driver Code head = null; /* Create following linked list 12.15.10.11.5.6.2.3 */ push(head, 3); push(head, 2); push(head, 6); push(head, 5); push(head, 11); push(head, 10); push(head, 15); push(head, 12); document.write(\"Given Linked List <br>\"); printList(head); max = -2147483648; head = delNodes(head); document.write(\"Modified Linked List <br>\"); printList(head); </script>", "e": 9498, "s": 7759, "text": null }, { "code": null, "e": 9568, "s": 9498, "text": "Given Linked List\n12 15 10 11 5 6 2 3 \nModified Linked List\n15 11 6 3" }, { "code": null, "e": 9592, "s": 9570, "text": "Time Complexity: O(N)" }, { "code": null, "e": 9614, "s": 9592, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 9627, "s": 9614, "text": "rituraj_jain" }, { "code": null, "e": 9639, "s": 9627, "text": "29AjayKumar" }, { "code": null, "e": 9653, "s": 9639, "text": "princiraj1992" }, { "code": null, "e": 9666, "s": 9653, "text": "Akanksha_Rai" }, { "code": null, "e": 9673, "s": 9666, "text": "rdtank" }, { "code": null, "e": 9681, "s": 9673, "text": "rohan07" }, { "code": null, "e": 9693, "s": 9681, "text": "Linked List" }, { "code": null, "e": 9703, "s": 9693, "text": "Recursion" }, { "code": null, "e": 9715, "s": 9703, "text": "Linked List" }, { "code": null, "e": 9725, "s": 9715, "text": "Recursion" }, { "code": null, "e": 9823, "s": 9725, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9855, "s": 9823, "text": "Introduction to Data Structures" }, { "code": null, "e": 9919, "s": 9855, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 9940, "s": 9919, "text": "Types of Linked List" }, { "code": null, "e": 9980, "s": 9940, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 10021, "s": 9980, "text": "Find first node of loop in a linked list" }, { "code": null, "e": 10081, "s": 10021, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 10166, "s": 10081, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 10176, "s": 10166, "text": "Recursion" }, { "code": null, "e": 10203, "s": 10176, "text": "Program for Tower of Hanoi" } ]
What is shallow copy? Explain with an example in Java.
Creating an exact copy of an existing object in the memory is known as cloning. The clone() method of the class java.lang.Object accepts an object as a parameter, creates and returns a copy of it (clones). In order to use this method, you need to make sure that your class implements the Cloneable interface. Live Demo import java.util.Scanner; public class CloneExample implements Cloneable { private String name; private int age; public CloneExample(String name, int age){ this.name = name; this.age = age; } public void displayData(){ System.out.println("Name : "+this.name); System.out.println("Age : "+this.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(); CloneExample std = new CloneExample(name, age); System.out.println("Contents of the original object"); std.displayData(); System.out.println("Contents of the copied object"); CloneExample copiedStd = (CloneExample) std.clone(); copiedStd.displayData(); } } Enter your name Krishna Enter your age 20 Contents of the original object Name : Krishna Age : 20 Contents of the copied object Name : Krishna Age : 20 Whenever you try to create a copy of an object using the shallow copy, all fields of the original objects are copied exactly. But, if it contains any objects as fields then, only references to those objects are copied not the compete objects. This implies that, if you perform shallow copy on an object that contains any objects as fields, since only references are copied in a shallow copy, both the original and copied object points to the same reference internally and, if you do any changes to the data using the copied object, they are reflected in the original object too. Note − By default, the clone() method does a shallow copy. In the following example the StudentData class contains a String variable (name), an integer variable (age) and an object (Contact). In the main method we are creating an object of the StudentData class and copying it. From the copied object we are changing the data(field values) of the reference used (Contact object). Then, we are printing the data of copied object first followed by data of the original one. Since we have done a shallow copy (using clone() method), you can observe that the change done is reflected in the original object. Live Demo import java.util.Scanner; class Contact{ private long phoneNo; private String email; private String address; public void setPhoneNo(long phoneNo) { this.phoneNo = phoneNo; } public void setEmail(String email) { this.email = email; } public void setAddress(String address) { this.address = address; } Contact(long phoneNo, String email, String address ){ this.phoneNo = phoneNo; this.email = email; this.address = address; } public void displayContact() { System.out.println("Phone no: "+this.phoneNo); System.out.println("Email: "+this.email); System.out.println("Address: "+this.address); } } public class StudentData implements Cloneable { private String name; private int age; private Contact contact; public StudentData(String name, int age, Contact contact){ this.name = name; this.age = age; this.contact = contact; } public void displayData(){ System.out.println("Name : "+this.name); System.out.println("Age : "+this.age); contact.displayContact(); } 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(); System.out.println("#############Contact details#############"); System.out.println("Enter your phone number: "); long phoneNo = sc.nextLong(); System.out.println("Enter your Email ID: "); String email = sc.next(); System.out.println("Enter your address: "); String address = sc.next(); System.out.println(" "); //Creating an object of the class StudentData std = new StudentData(name, age, new Contact(phoneNo, email, address)); //Creating a clone of the above object StudentData copiedStd = (StudentData) std.clone(); //Modifying the data of the contact object copiedStd.contact.setPhoneNo(000000000); copiedStd.contact.setEmail("XXXXXXXXXX"); copiedStd.contact.setAddress("XXXXXXXXXX"); System.out.println("Contents of the copied object::"); copiedStd.displayData(); System.out.println(" "); System.out.println("Contents of the original object::"); std.displayData(); } } Enter your name Krishna Enter your age 20 #############Contact details############# Enter your phone number: 9848022338 Enter your Email ID: [email protected] Enter your address: Hyderabad Contents of the copied object:: Name : Krishna Age : 20 Phone no: 0 Email: XXXXXXXXXX Address: XXXXXXXXXX Contents of the original object:: Name : Krishna Age : 20 Phone no: 0 Email: XXXXXXXXXX Address: XXXXXXXXXX
[ { "code": null, "e": 1267, "s": 1187, "text": "Creating an exact copy of an existing object in the memory is known as cloning." }, { "code": null, "e": 1393, "s": 1267, "text": "The clone() method of the class java.lang.Object accepts an object as a parameter, creates and returns a copy of it (clones)." }, { "code": null, "e": 1496, "s": 1393, "text": "In order to use this method, you need to make sure that your class implements the Cloneable interface." }, { "code": null, "e": 1507, "s": 1496, "text": " Live Demo" }, { "code": null, "e": 2418, "s": 1507, "text": "import java.util.Scanner;\npublic class CloneExample implements Cloneable {\n private String name;\n private int age;\n public CloneExample(String name, int age){\n this.name = name;\n this.age = age;\n }\n public void displayData(){\n System.out.println(\"Name : \"+this.name);\n System.out.println(\"Age : \"+this.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 CloneExample std = new CloneExample(name, age);\n System.out.println(\"Contents of the original object\");\n std.displayData();\n System.out.println(\"Contents of the copied object\");\n CloneExample copiedStd = (CloneExample) std.clone();\n copiedStd.displayData();\n }\n}" }, { "code": null, "e": 2570, "s": 2418, "text": "Enter your name\nKrishna\nEnter your age\n20\nContents of the original object\nName : Krishna\nAge : 20\nContents of the copied object\nName : Krishna\nAge : 20" }, { "code": null, "e": 2813, "s": 2570, "text": "Whenever you try to create a copy of an object using the shallow copy, all fields of the original objects are copied exactly. But, if it contains any objects as fields then, only references to those objects are copied not the compete objects." }, { "code": null, "e": 3149, "s": 2813, "text": "This implies that, if you perform shallow copy on an object that contains any objects as fields, since only references are copied in a shallow copy, both the original and copied object points to the same reference internally and, if you do any changes to the data using the copied object, they are reflected in the original object too." }, { "code": null, "e": 3208, "s": 3149, "text": "Note − By default, the clone() method does a shallow copy." }, { "code": null, "e": 3341, "s": 3208, "text": "In the following example the StudentData class contains a String variable (name), an integer variable (age) and an object (Contact)." }, { "code": null, "e": 3621, "s": 3341, "text": "In the main method we are creating an object of the StudentData class and copying it. From the copied object we are changing the data(field values) of the reference used (Contact object). Then, we are printing the data of copied object first followed by data of the original one." }, { "code": null, "e": 3753, "s": 3621, "text": "Since we have done a shallow copy (using clone() method), you can observe that the change done is reflected in the original object." }, { "code": null, "e": 3764, "s": 3753, "text": " Live Demo" }, { "code": null, "e": 6149, "s": 3764, "text": "import java.util.Scanner;\nclass Contact{\n private long phoneNo;\n private String email;\n private String address;\n public void setPhoneNo(long phoneNo) {\n this.phoneNo = phoneNo;\n }\n public void setEmail(String email) {\n this.email = email;\n }\n public void setAddress(String address) {\n this.address = address;\n }\n Contact(long phoneNo, String email, String address ){\n this.phoneNo = phoneNo;\n this.email = email;\n this.address = address;\n }\n public void displayContact() {\n System.out.println(\"Phone no: \"+this.phoneNo);\n System.out.println(\"Email: \"+this.email);\n System.out.println(\"Address: \"+this.address);\n }\n}\npublic class StudentData implements Cloneable {\n private String name;\n private int age;\n private Contact contact;\n public StudentData(String name, int age, Contact contact){\n this.name = name;\n this.age = age;\n this.contact = contact;\n }\n public void displayData(){\n System.out.println(\"Name : \"+this.name);\n System.out.println(\"Age : \"+this.age);\n contact.displayContact();\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 System.out.println(\"#############Contact details#############\");\n System.out.println(\"Enter your phone number: \");\n long phoneNo = sc.nextLong();\n System.out.println(\"Enter your Email ID: \");\n String email = sc.next();\n System.out.println(\"Enter your address: \");\n String address = sc.next();\n System.out.println(\" \");\n //Creating an object of the class\n StudentData std = new StudentData(name, age, new Contact(phoneNo, email, address));\n //Creating a clone of the above object\n StudentData copiedStd = (StudentData) std.clone();\n //Modifying the data of the contact object\n copiedStd.contact.setPhoneNo(000000000);\n copiedStd.contact.setEmail(\"XXXXXXXXXX\");\n copiedStd.contact.setAddress(\"XXXXXXXXXX\");\n System.out.println(\"Contents of the copied object::\");\n copiedStd.displayData();\n System.out.println(\" \");\n System.out.println(\"Contents of the original object::\");\n std.displayData();\n }\n}" }, { "code": null, "e": 6562, "s": 6149, "text": "Enter your name\nKrishna\nEnter your age\n20\n#############Contact details#############\nEnter your phone number:\n9848022338\nEnter your Email ID:\[email protected]\nEnter your address:\nHyderabad\n\nContents of the copied object::\nName : Krishna\nAge : 20\nPhone no: 0\nEmail: XXXXXXXXXX\nAddress: XXXXXXXXXX\n\nContents of the original object::\nName : Krishna\nAge : 20\nPhone no: 0\nEmail: XXXXXXXXXX\nAddress: XXXXXXXXXX" } ]
Iterating over all possible combinations in an Array using Bits
03 Jun, 2021 There arise several situations while solving a problem where we need to iterate over all possible combinations of an array. In this article, we will discuss the method of using bits to do so.For the purpose of explaining, consider the following question: Given an array b[] = {2, 1, 4}. The task is to check if there exists any combination of elements of this array whose sum of elements is equal to k = 6. Solution using Bit operations: As there are 3 elements in this array, hence we need 3 bits to represent each of the numbers. A bit set as 1 corresponding to the element means it is included while calculating the sum, and not if it is 0. The possible combinations are: 000 : No element is selected. 001 : 4 is selected. 010 : 1 is selected. 011 : 1 and 4 are selected. 100 : 2 is selected. 101 : 2 and 4 are selected. 110 : 2 and 1 are selected. 111 : All elements are selected. Hence, the range required to access all these bits is 0 – 7. We iterate over each bit of each of the possible combinations, and check for each combination if the sum of chosen elements is equal to the required sum or not. Examples: Input : A = {3, 4, 1, 2} and k = 6 Output : YES Here, the combination of using 3, 1 and 2 yields the required sum. Input : A = {3, 4, 1, 2} and k = 11 Output : NO Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to iterate over all possible// combinations of array elements #include <bits/stdc++.h>using namespace std; // Function to check if any combination of// elements of the array sums to kbool checkSum(int a[], int n, int k){ // Flag variable to check if // sum exists int flag = 0; // Calculate number of bits int range = (1 << n) - 1; // Generate combinations using bits for (int i = 0; i <= range; i++) { int x = 0, y = i, sum = 0; while (y > 0) { if (y & 1 == 1) { // Calculate sum sum = sum + a[x]; } x++; y = y >> 1; } // If sum is found, set flag to 1 // and terminate the loop if (sum == k) return true; } return false;} // Driver Codeint main(){ int k = 6; int a[] = { 3, 4, 1, 2 }; int n = sizeof(a)/sizeof(a[0]); if (checkSum(a, n, k)) cout << "Yes"; else cout << "No"; return 0;} // Java program to iterate over all possible// combinations of array elementsclass GFG{ // Function to check if any combination// of elements of the array sums to kstatic boolean checkSum(int a[], int n, int k){ // Flag variable to check if // sum exists int flag = 0; // Calculate number of bits int range = (1 << n) - 1; // Generate combinations using bits for (int i = 0; i <= range; i++) { int x = 0, y = i, sum = 0; while (y > 0) { if ((y & 1) == 1) { // Calculate sum sum = sum + a[x]; } x++; y = y >> 1; } // If sum is found, set flag to 1 // and terminate the loop if (sum == k) return true; } return false;} // Driver Codepublic static void main(String[] args){ int k = 6; int a[] = { 3, 4, 1, 2 }; int n = a.length; if (checkSum(a, n, k)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed// by Code_Mech # Python 3 program to iterate over all# possible combinations of array elements # Function to check if any combination of# elements of the array sums to kdef checkSum(a, n, k): # Flag variable to check if # sum exists flag = 0 # Calculate number of bits range__ = (1 << n) - 1 # Generate combinations using bits for i in range(range__ + 1): x = 0 y = i sum = 0 while (y > 0): if (y & 1 == 1): # Calculate sum sum = sum + a[x] x += 1 y = y >> 1 # If sum is found, set flag to 1 # and terminate the loop if (sum == k): return True return False # Driver Codeif __name__ == '__main__': k = 6 a = [3, 4, 1, 2] n = len(a) if (checkSum(a, n, k)): print("Yes") else: print("No") # This code is contributed by# Surendra_Gangwar // C# program to iterate over all possible// combinations of array elementsusing System;class GFG{// Function to check if any combination// of elements of the array sums to kstatic bool checkSum(int[] a, int n, int k){ // Flag variable to check if // sum exists int // C# program to iterate over all possible// combinations of array elementsusing System; class GFG{ // Function to check if any combination// of elements of the array sums to kstatic bool checkSum(int[] a, int n, int k){ // Flag variable to check if // sum exists int flag = 0; // Calculate number of bits int range = (1 << n) - 1; // Generate combinations using bits for (int i = 0; i <= range; i++) { int x = 0, y = i, sum = 0; while (y > 0) { if ((y & 1) == 1) { // Calculate sum sum = sum + a[x]; } x++; y = y >> 1; } // If sum is found, set flag to 1 // and terminate the loop if (sum == k) return true; } return false;} // Driver Codepublic static void Main(){ int k = 6; int[] a = { 3, 4, 1, 2 }; int n = a.Length; if (checkSum(a, n, k)) Console.WriteLine("Yes"); else Console.WriteLine("No");}} // This code is contributed// by Code_Mech <?php// PHP program to iterate over all possible// combinations of array elements // Function to check if any combination of// elements of the array sums to kfunction checkSum($a, $n, $k){ // Flag variable to check if // sum exists $flag = 0; // Calculate number of bits $range = (1 << $n) - 1; // Generate combinations using bits for ($i = 0; $i <= $range; $i++) { $x = 0; $y = $i; $sum = 0; while ($y > 0) { if ($y & 1 == 1) { // Calculate sum $sum = $sum + $a[$x]; } $x++; $y = $y >> 1; } // If sum is found, set flag to 1 // and terminate the loop if ($sum == $k) return true; } return false;} // Driver Code $k = 6; $a = array( 3, 4, 1, 2 ); $n = sizeof($a); if (checkSum($a, $n, $k)) echo "Yes"; else echo "No"; // This code is contributed by Ryuga?> <script> // Javascript program to iterate over all possible // combinations of array elements // Function to check if any combination // of elements of the array sums to k function checkSum(a, n, k) { // Flag variable to check if // sum exists let flag = 0; // Calculate number of bits let range = (1 << n) - 1; // Generate combinations using bits for (let i = 0; i <= range; i++) { let x = 0, y = i, sum = 0; while (y > 0) { if ((y & 1) == 1) { // Calculate sum sum = sum + a[x]; } x++; y = y >> 1; } // If sum is found, set flag to 1 // and terminate the loop if (sum == k) return true; } return false; } let k = 6; let a = [ 3, 4, 1, 2 ]; let n = a.length; if (checkSum(a, n, k)) document.write("Yes"); else document.write("No"); </script> Yes Time complexity : 2(number of bits) ankthon Code_Mech SURENDRA_GANGWAR rameshtravel07 Arrays Bit Magic Combinatorial Arrays Bit Magic Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array What is Data Structure: Types, Classifications and Applications Chocolate Distribution Problem Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Count set bits in an integer How to swap two numbers without using a temporary variable?
[ { "code": null, "e": 54, "s": 26, "text": "\n03 Jun, 2021" }, { "code": null, "e": 310, "s": 54, "text": "There arise several situations while solving a problem where we need to iterate over all possible combinations of an array. In this article, we will discuss the method of using bits to do so.For the purpose of explaining, consider the following question: " }, { "code": null, "e": 464, "s": 310, "text": "Given an array b[] = {2, 1, 4}. The task is to check if there exists any combination of elements of this array whose sum of elements is equal to k = 6. " }, { "code": null, "e": 733, "s": 464, "text": "Solution using Bit operations: As there are 3 elements in this array, hence we need 3 bits to represent each of the numbers. A bit set as 1 corresponding to the element means it is included while calculating the sum, and not if it is 0. The possible combinations are: " }, { "code": null, "e": 943, "s": 733, "text": "000 : No element is selected.\n001 : 4 is selected.\n010 : 1 is selected.\n011 : 1 and 4 are selected.\n100 : 2 is selected.\n101 : 2 and 4 are selected.\n110 : 2 and 1 are selected.\n111 : All elements are selected." }, { "code": null, "e": 1166, "s": 943, "text": "Hence, the range required to access all these bits is 0 – 7. We iterate over each bit of each of the possible combinations, and check for each combination if the sum of chosen elements is equal to the required sum or not. " }, { "code": null, "e": 1177, "s": 1166, "text": "Examples: " }, { "code": null, "e": 1343, "s": 1177, "text": "Input : A = {3, 4, 1, 2} and k = 6 \nOutput : YES\nHere, the combination of using 3, 1 and 2 yields \nthe required sum.\n\nInput : A = {3, 4, 1, 2} and k = 11\nOutput : NO" }, { "code": null, "e": 1395, "s": 1343, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1399, "s": 1395, "text": "C++" }, { "code": null, "e": 1404, "s": 1399, "text": "Java" }, { "code": null, "e": 1412, "s": 1404, "text": "Python3" }, { "code": null, "e": 1415, "s": 1412, "text": "C#" }, { "code": null, "e": 1419, "s": 1415, "text": "PHP" }, { "code": null, "e": 1430, "s": 1419, "text": "Javascript" }, { "code": "// C++ program to iterate over all possible// combinations of array elements #include <bits/stdc++.h>using namespace std; // Function to check if any combination of// elements of the array sums to kbool checkSum(int a[], int n, int k){ // Flag variable to check if // sum exists int flag = 0; // Calculate number of bits int range = (1 << n) - 1; // Generate combinations using bits for (int i = 0; i <= range; i++) { int x = 0, y = i, sum = 0; while (y > 0) { if (y & 1 == 1) { // Calculate sum sum = sum + a[x]; } x++; y = y >> 1; } // If sum is found, set flag to 1 // and terminate the loop if (sum == k) return true; } return false;} // Driver Codeint main(){ int k = 6; int a[] = { 3, 4, 1, 2 }; int n = sizeof(a)/sizeof(a[0]); if (checkSum(a, n, k)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 2424, "s": 1430, "text": null }, { "code": "// Java program to iterate over all possible// combinations of array elementsclass GFG{ // Function to check if any combination// of elements of the array sums to kstatic boolean checkSum(int a[], int n, int k){ // Flag variable to check if // sum exists int flag = 0; // Calculate number of bits int range = (1 << n) - 1; // Generate combinations using bits for (int i = 0; i <= range; i++) { int x = 0, y = i, sum = 0; while (y > 0) { if ((y & 1) == 1) { // Calculate sum sum = sum + a[x]; } x++; y = y >> 1; } // If sum is found, set flag to 1 // and terminate the loop if (sum == k) return true; } return false;} // Driver Codepublic static void main(String[] args){ int k = 6; int a[] = { 3, 4, 1, 2 }; int n = a.length; if (checkSum(a, n, k)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed// by Code_Mech", "e": 3479, "s": 2424, "text": null }, { "code": "# Python 3 program to iterate over all# possible combinations of array elements # Function to check if any combination of# elements of the array sums to kdef checkSum(a, n, k): # Flag variable to check if # sum exists flag = 0 # Calculate number of bits range__ = (1 << n) - 1 # Generate combinations using bits for i in range(range__ + 1): x = 0 y = i sum = 0 while (y > 0): if (y & 1 == 1): # Calculate sum sum = sum + a[x] x += 1 y = y >> 1 # If sum is found, set flag to 1 # and terminate the loop if (sum == k): return True return False # Driver Codeif __name__ == '__main__': k = 6 a = [3, 4, 1, 2] n = len(a) if (checkSum(a, n, k)): print(\"Yes\") else: print(\"No\") # This code is contributed by# Surendra_Gangwar", "e": 4410, "s": 3479, "text": null }, { "code": "// C# program to iterate over all possible// combinations of array elementsusing System;class GFG{// Function to check if any combination// of elements of the array sums to kstatic bool checkSum(int[] a, int n, int k){ // Flag variable to check if // sum exists int // C# program to iterate over all possible// combinations of array elementsusing System; class GFG{ // Function to check if any combination// of elements of the array sums to kstatic bool checkSum(int[] a, int n, int k){ // Flag variable to check if // sum exists int flag = 0; // Calculate number of bits int range = (1 << n) - 1; // Generate combinations using bits for (int i = 0; i <= range; i++) { int x = 0, y = i, sum = 0; while (y > 0) { if ((y & 1) == 1) { // Calculate sum sum = sum + a[x]; } x++; y = y >> 1; } // If sum is found, set flag to 1 // and terminate the loop if (sum == k) return true; } return false;} // Driver Codepublic static void Main(){ int k = 6; int[] a = { 3, 4, 1, 2 }; int n = a.Length; if (checkSum(a, n, k)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");}} // This code is contributed// by Code_Mech", "e": 5733, "s": 4410, "text": null }, { "code": "<?php// PHP program to iterate over all possible// combinations of array elements // Function to check if any combination of// elements of the array sums to kfunction checkSum($a, $n, $k){ // Flag variable to check if // sum exists $flag = 0; // Calculate number of bits $range = (1 << $n) - 1; // Generate combinations using bits for ($i = 0; $i <= $range; $i++) { $x = 0; $y = $i; $sum = 0; while ($y > 0) { if ($y & 1 == 1) { // Calculate sum $sum = $sum + $a[$x]; } $x++; $y = $y >> 1; } // If sum is found, set flag to 1 // and terminate the loop if ($sum == $k) return true; } return false;} // Driver Code $k = 6; $a = array( 3, 4, 1, 2 ); $n = sizeof($a); if (checkSum($a, $n, $k)) echo \"Yes\"; else echo \"No\"; // This code is contributed by Ryuga?>", "e": 6720, "s": 5733, "text": null }, { "code": "<script> // Javascript program to iterate over all possible // combinations of array elements // Function to check if any combination // of elements of the array sums to k function checkSum(a, n, k) { // Flag variable to check if // sum exists let flag = 0; // Calculate number of bits let range = (1 << n) - 1; // Generate combinations using bits for (let i = 0; i <= range; i++) { let x = 0, y = i, sum = 0; while (y > 0) { if ((y & 1) == 1) { // Calculate sum sum = sum + a[x]; } x++; y = y >> 1; } // If sum is found, set flag to 1 // and terminate the loop if (sum == k) return true; } return false; } let k = 6; let a = [ 3, 4, 1, 2 ]; let n = a.length; if (checkSum(a, n, k)) document.write(\"Yes\"); else document.write(\"No\"); </script>", "e": 7805, "s": 6720, "text": null }, { "code": null, "e": 7809, "s": 7805, "text": "Yes" }, { "code": null, "e": 7848, "s": 7811, "text": "Time complexity : 2(number of bits) " }, { "code": null, "e": 7856, "s": 7848, "text": "ankthon" }, { "code": null, "e": 7866, "s": 7856, "text": "Code_Mech" }, { "code": null, "e": 7883, "s": 7866, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 7898, "s": 7883, "text": "rameshtravel07" }, { "code": null, "e": 7905, "s": 7898, "text": "Arrays" }, { "code": null, "e": 7915, "s": 7905, "text": "Bit Magic" }, { "code": null, "e": 7929, "s": 7915, "text": "Combinatorial" }, { "code": null, "e": 7936, "s": 7929, "text": "Arrays" }, { "code": null, "e": 7946, "s": 7936, "text": "Bit Magic" }, { "code": null, "e": 7960, "s": 7946, "text": "Combinatorial" }, { "code": null, "e": 8058, "s": 7960, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8090, "s": 8058, "text": "Introduction to Data Structures" }, { "code": null, "e": 8115, "s": 8090, "text": "Window Sliding Technique" }, { "code": null, "e": 8162, "s": 8115, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 8226, "s": 8162, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 8257, "s": 8226, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 8284, "s": 8257, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 8330, "s": 8284, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 8398, "s": 8330, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 8427, "s": 8398, "text": "Count set bits in an integer" } ]
JavaScript | array.flatMap()
29 Oct, 2021 The array.flatMap() is an inbuilt function in JavaScript which is used to flatten the input array element into a new array. This method first of all map every element with the help of mapping function, then flattens the input array element into a new array. Syntax: var A = array.flatMap(function callback(current_value, index, Array)) { // It returns the new array's elements. } Parameters: current_value: It is the input array elements.index:It is optional.It is the index of the input element.Array: It is optional.It is used when array map is called. current_value: It is the input array elements. index:It is optional.It is the index of the input element. It is optional. It is the index of the input element. Array: It is optional.It is used when array map is called. It is optional. It is used when array map is called. Return Values: It returns a new array whose elements are the return value of the callback function. JavaScript code to show the functionality of the above function: Code #1: javascript <script> // Taking input as an array A having some elements.var A = [ 1, 2, 3, 4, 5 ]; // Mapping with map function.b = A.map(x => [x * 3]);document.write(b); // Mapping and flatting with flatMap() function.c = arr1.flatMap(x => [x * 3]);document.write(c); // Mapping and flatting with flatMap() function.d = arr1.flatMap(x => [[ x * 3 ]]);document.write(d);</script> Output: [[3], [6], [9], [12], [15]] [3, 6, 9, 12, 15] [[3], [6], [9], [12], [15]] Code #2: This flatting can also be done with the help of reduce and concat. javascript <script> // Taking input as an array A having some elements.var A = [ 1, 2, 3, 4, 5 ];array.flatMap(x => [x * 3]); // is equivalent tob = A.reduce((acc, x) => acc.concat([ x * 3 ]), []);document.write(b);</script> Output: [3, 6, 9, 12, 15] Supported Browser: Google Chrome 69 and above Edge 79 and above Firefox 62 and above Opera 56 and above Safari 12 and above Note: This function is available in Firefox Nightly only. ysachin2314 javascript-array javascript-math JavaScript 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 Roadmap to Learn JavaScript For Beginners JavaScript | Promises How to filter object array based on attributes? Lodash _.debounce() Method JavaScript String includes() Method JavaScript | fetch() Method Lodash _.groupBy() Method
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Oct, 2021" }, { "code": null, "e": 296, "s": 28, "text": "The array.flatMap() is an inbuilt function in JavaScript which is used to flatten the input array element into a new array. This method first of all map every element with the help of mapping function, then flattens the input array element into a new array. Syntax: " }, { "code": null, "e": 414, "s": 296, "text": "var A = array.flatMap(function callback(current_value, index, Array))\n{\n // It returns the new array's elements.\n}" }, { "code": null, "e": 428, "s": 414, "text": "Parameters: " }, { "code": null, "e": 591, "s": 428, "text": "current_value: It is the input array elements.index:It is optional.It is the index of the input element.Array: It is optional.It is used when array map is called." }, { "code": null, "e": 638, "s": 591, "text": "current_value: It is the input array elements." }, { "code": null, "e": 697, "s": 638, "text": "index:It is optional.It is the index of the input element." }, { "code": null, "e": 713, "s": 697, "text": "It is optional." }, { "code": null, "e": 751, "s": 713, "text": "It is the index of the input element." }, { "code": null, "e": 810, "s": 751, "text": "Array: It is optional.It is used when array map is called." }, { "code": null, "e": 826, "s": 810, "text": "It is optional." }, { "code": null, "e": 863, "s": 826, "text": "It is used when array map is called." }, { "code": null, "e": 1037, "s": 863, "text": "Return Values: It returns a new array whose elements are the return value of the callback function. JavaScript code to show the functionality of the above function: Code #1:" }, { "code": null, "e": 1048, "s": 1037, "text": "javascript" }, { "code": "<script> // Taking input as an array A having some elements.var A = [ 1, 2, 3, 4, 5 ]; // Mapping with map function.b = A.map(x => [x * 3]);document.write(b); // Mapping and flatting with flatMap() function.c = arr1.flatMap(x => [x * 3]);document.write(c); // Mapping and flatting with flatMap() function.d = arr1.flatMap(x => [[ x * 3 ]]);document.write(d);</script>", "e": 1416, "s": 1048, "text": null }, { "code": null, "e": 1426, "s": 1416, "text": "Output: " }, { "code": null, "e": 1500, "s": 1426, "text": "[[3], [6], [9], [12], [15]]\n[3, 6, 9, 12, 15]\n[[3], [6], [9], [12], [15]]" }, { "code": null, "e": 1578, "s": 1500, "text": "Code #2: This flatting can also be done with the help of reduce and concat. " }, { "code": null, "e": 1589, "s": 1578, "text": "javascript" }, { "code": "<script> // Taking input as an array A having some elements.var A = [ 1, 2, 3, 4, 5 ];array.flatMap(x => [x * 3]); // is equivalent tob = A.reduce((acc, x) => acc.concat([ x * 3 ]), []);document.write(b);</script>", "e": 1803, "s": 1589, "text": null }, { "code": null, "e": 1813, "s": 1803, "text": "Output: " }, { "code": null, "e": 1831, "s": 1813, "text": "[3, 6, 9, 12, 15]" }, { "code": null, "e": 1850, "s": 1831, "text": "Supported Browser:" }, { "code": null, "e": 1877, "s": 1850, "text": "Google Chrome 69 and above" }, { "code": null, "e": 1895, "s": 1877, "text": "Edge 79 and above" }, { "code": null, "e": 1916, "s": 1895, "text": "Firefox 62 and above" }, { "code": null, "e": 1935, "s": 1916, "text": "Opera 56 and above" }, { "code": null, "e": 1955, "s": 1935, "text": "Safari 12 and above" }, { "code": null, "e": 2014, "s": 1955, "text": "Note: This function is available in Firefox Nightly only. " }, { "code": null, "e": 2026, "s": 2014, "text": "ysachin2314" }, { "code": null, "e": 2043, "s": 2026, "text": "javascript-array" }, { "code": null, "e": 2059, "s": 2043, "text": "javascript-math" }, { "code": null, "e": 2070, "s": 2059, "text": "JavaScript" }, { "code": null, "e": 2168, "s": 2070, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2229, "s": 2168, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2269, "s": 2229, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2310, "s": 2269, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2352, "s": 2310, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 2374, "s": 2352, "text": "JavaScript | Promises" }, { "code": null, "e": 2422, "s": 2374, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 2449, "s": 2422, "text": "Lodash _.debounce() Method" }, { "code": null, "e": 2485, "s": 2449, "text": "JavaScript String includes() Method" }, { "code": null, "e": 2513, "s": 2485, "text": "JavaScript | fetch() Method" } ]
How to convert an Integer Into a String in PHP ?
30 Apr, 2021 The PHP strval() function is used to convert an Integer Into a String in PHP. There are many other methods to convert an integer into a string. In this article, we will learn many methods. Methods: Using strval() function. Using inline variable parsing. Using explicit Casting. Method 1: Using strval() function. Note: The strval() function is an inbuilt function in PHP and is used to convert any scalar value (string, integer, or double) to a string. We cannot use strval() on arrays or on object, if applied then this function only returns the type name of the value being converted. Syntax: strval( $variable ) Return value: This function returns a string. This string is generated by typecasting the value of the variable passed to it as a parameter. Example: PHP <?php $var_name = 2; // converts integer into string$str = strval($var_name); // prints the value of above variable as a stringecho "Welcome $str GeeksforGeeks"; ?> Welcome 2 GeeksforGeeks Method 2: Using Inline variable parsing. Note: When you use Integer inside a string, then the Integer is first converted into a string and then prints as a string. Syntax: $integer = 2; echo "$integer"; Example: PHP <?php $var_name = 2; // prints the value of above variable// as a stringecho "Welcome $var_name GeeksforGeeks"; ?> Welcome 2 GeeksforGeeks Method 3: Using Explicit Casting. Note: Explicit Casting is the explicit conversion of data type because the user explicitly defines the data type in which he wants to cast. We will convert Integer into String. Syntax: $str = (string)$var_name Example: PHP <?php $var_name = 2; //Typecasting Integer into string$str = (string)$var_name; // prints the value of above variable as a stringecho "Welcome $str GeeksforGeeks"; ?> Welcome 2 GeeksforGeeks PHP-function PHP-Questions PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between HTTP GET and POST Methods PHP Cookies How to generate PDF file using PHP ? How to pass variables and data from PHP to JavaScript ? PHP | strtotime() Function Installation of Node.js on Linux How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to create footer to stay at the bottom of a Web page? How to set the default value for an HTML <select> element ?
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Apr, 2021" }, { "code": null, "e": 173, "s": 28, "text": "The PHP strval() function is used to convert an Integer Into a String in PHP. There are many other methods to convert an integer into a string. " }, { "code": null, "e": 218, "s": 173, "text": "In this article, we will learn many methods." }, { "code": null, "e": 227, "s": 218, "text": "Methods:" }, { "code": null, "e": 252, "s": 227, "text": "Using strval() function." }, { "code": null, "e": 283, "s": 252, "text": "Using inline variable parsing." }, { "code": null, "e": 307, "s": 283, "text": "Using explicit Casting." }, { "code": null, "e": 342, "s": 307, "text": "Method 1: Using strval() function." }, { "code": null, "e": 617, "s": 342, "text": "Note: The strval() function is an inbuilt function in PHP and is used to convert any scalar value (string, integer, or double) to a string. We cannot use strval() on arrays or on object, if applied then this function only returns the type name of the value being converted." }, { "code": null, "e": 625, "s": 617, "text": "Syntax:" }, { "code": null, "e": 646, "s": 625, "text": "strval( $variable ) " }, { "code": null, "e": 787, "s": 646, "text": "Return value: This function returns a string. This string is generated by typecasting the value of the variable passed to it as a parameter." }, { "code": null, "e": 797, "s": 787, "text": "Example: " }, { "code": null, "e": 801, "s": 797, "text": "PHP" }, { "code": "<?php $var_name = 2; // converts integer into string$str = strval($var_name); // prints the value of above variable as a stringecho \"Welcome $str GeeksforGeeks\"; ?>", "e": 973, "s": 801, "text": null }, { "code": null, "e": 997, "s": 973, "text": "Welcome 2 GeeksforGeeks" }, { "code": null, "e": 1038, "s": 997, "text": "Method 2: Using Inline variable parsing." }, { "code": null, "e": 1161, "s": 1038, "text": "Note: When you use Integer inside a string, then the Integer is first converted into a string and then prints as a string." }, { "code": null, "e": 1170, "s": 1161, "text": "Syntax: " }, { "code": null, "e": 1201, "s": 1170, "text": "$integer = 2;\necho \"$integer\";" }, { "code": null, "e": 1210, "s": 1201, "text": "Example:" }, { "code": null, "e": 1214, "s": 1210, "text": "PHP" }, { "code": "<?php $var_name = 2; // prints the value of above variable// as a stringecho \"Welcome $var_name GeeksforGeeks\"; ?>", "e": 1336, "s": 1214, "text": null }, { "code": null, "e": 1360, "s": 1336, "text": "Welcome 2 GeeksforGeeks" }, { "code": null, "e": 1394, "s": 1360, "text": "Method 3: Using Explicit Casting." }, { "code": null, "e": 1571, "s": 1394, "text": "Note: Explicit Casting is the explicit conversion of data type because the user explicitly defines the data type in which he wants to cast. We will convert Integer into String." }, { "code": null, "e": 1579, "s": 1571, "text": "Syntax:" }, { "code": null, "e": 1604, "s": 1579, "text": "$str = (string)$var_name" }, { "code": null, "e": 1613, "s": 1604, "text": "Example:" }, { "code": null, "e": 1617, "s": 1613, "text": "PHP" }, { "code": "<?php $var_name = 2; //Typecasting Integer into string$str = (string)$var_name; // prints the value of above variable as a stringecho \"Welcome $str GeeksforGeeks\"; ?>", "e": 1790, "s": 1617, "text": null }, { "code": null, "e": 1814, "s": 1790, "text": "Welcome 2 GeeksforGeeks" }, { "code": null, "e": 1829, "s": 1816, "text": "PHP-function" }, { "code": null, "e": 1843, "s": 1829, "text": "PHP-Questions" }, { "code": null, "e": 1847, "s": 1843, "text": "PHP" }, { "code": null, "e": 1864, "s": 1847, "text": "Web Technologies" }, { "code": null, "e": 1868, "s": 1864, "text": "PHP" }, { "code": null, "e": 1966, "s": 1868, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2011, "s": 1966, "text": "Difference between HTTP GET and POST Methods" }, { "code": null, "e": 2023, "s": 2011, "text": "PHP Cookies" }, { "code": null, "e": 2060, "s": 2023, "text": "How to generate PDF file using PHP ?" }, { "code": null, "e": 2116, "s": 2060, "text": "How to pass variables and data from PHP to JavaScript ?" }, { "code": null, "e": 2143, "s": 2116, "text": "PHP | strtotime() Function" }, { "code": null, "e": 2176, "s": 2143, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2226, "s": 2176, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2288, "s": 2226, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2346, "s": 2288, "text": "How to create footer to stay at the bottom of a Web page?" } ]
Difference between npm and yarn
02 Mar, 2020 NPM and Yarn are package managers that help to manage a project’s dependencies. A dependency is, as it sounds, something that a project depends on, a piece of code that is required to make the project work properly. We need them because managing the project’s dependencies is a difficult task and it quickly becomes tedious, and out of hand when the project grows. By managing the dependencies, we mean to include, un-include, and update them. npm: It is a package manager for the JavaScript programming language. It is the default package manager for the JavaScript runtime environment Node.js. It consists of a command-line client, also called npm, and an online database of public and paid-for private packages called the npm registry. yarn: It stands for Yet Another Resource Negotiator and it is a package manager just like npm. It was developed by Facebook and is now open-source. The intention behind developing yarn(at that time) was to fix performance and security concerns with npm. The differences between npm and yarn are explained below: Installation procedure npm: npm is installed with Node automatically. yarn: To install yarn npm have to be installed.npm install yarn --global npm install yarn --global The lock file npm: NPM generates a ‘package-lock.json’ file. The package-lock.json file is a little more complex due to a trade-off between determinism and simplicity. Due to this complexity, the package-lock will generate the same node_modules folder for different npm versions. Every dependency will have an exact version number associated with it in the package-lock file. yarn: Yarn generates a ‘yarn.lock’ file. Yarn lock files help in easy merge. The merges are predictable as well, because of the design of the lock file. Output log install: The npm creates massive output logs of npm commands. It is essentially a dump of stack trace of what npm is doing. add: The yarn output logs are clean, visually distinguishable and brief. They are also ordered in a tree form for understandability. Installing global dependencies npm: To install a global package, the command template for npm is:npm install -g package_name@version_number npm install -g package_name@version_number yarn: To install a global package, the command template for yarn is:yarn global add package_name@version_number yarn global add package_name@version_number The ‘why’ command: npm: npm yet doesn’t has a ‘why’ functionality built in. yarn: Yarn comes with a ‘why’ command that tells why a dependency is present in the project. For example, it is a dependency, a native module, or a project dependency. License Checker npm: npm doesn’t has a license checker that can give a handy description of all the licenses that a project is bound with, due to installed dependencies. yarn: Yarn has a neat license checker. To see them, runyarn licenses list yarn licenses list Fetching packages npm: npm fetches dependencies from the npm registry during every ‘npm install‘ command. Yarn: yarn stores dependencies locally, and fetches from the disk during a ‘yarn add‘ command (assuming the dependency(with the specific version) is present locally). Commands changed in yarn after npm Commands same for npm and yarn: Node.js-Misc Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n02 Mar, 2020" }, { "code": null, "e": 498, "s": 54, "text": "NPM and Yarn are package managers that help to manage a project’s dependencies. A dependency is, as it sounds, something that a project depends on, a piece of code that is required to make the project work properly. We need them because managing the project’s dependencies is a difficult task and it quickly becomes tedious, and out of hand when the project grows. By managing the dependencies, we mean to include, un-include, and update them." }, { "code": null, "e": 793, "s": 498, "text": "npm: It is a package manager for the JavaScript programming language. It is the default package manager for the JavaScript runtime environment Node.js. It consists of a command-line client, also called npm, and an online database of public and paid-for private packages called the npm registry." }, { "code": null, "e": 1047, "s": 793, "text": "yarn: It stands for Yet Another Resource Negotiator and it is a package manager just like npm. It was developed by Facebook and is now open-source. The intention behind developing yarn(at that time) was to fix performance and security concerns with npm." }, { "code": null, "e": 1105, "s": 1047, "text": "The differences between npm and yarn are explained below:" }, { "code": null, "e": 1128, "s": 1105, "text": "Installation procedure" }, { "code": null, "e": 1175, "s": 1128, "text": "npm: npm is installed with Node automatically." }, { "code": null, "e": 1248, "s": 1175, "text": "yarn: To install yarn npm have to be installed.npm install yarn --global" }, { "code": null, "e": 1274, "s": 1248, "text": "npm install yarn --global" }, { "code": null, "e": 1288, "s": 1274, "text": "The lock file" }, { "code": null, "e": 1650, "s": 1288, "text": "npm: NPM generates a ‘package-lock.json’ file. The package-lock.json file is a little more complex due to a trade-off between determinism and simplicity. Due to this complexity, the package-lock will generate the same node_modules folder for different npm versions. Every dependency will have an exact version number associated with it in the package-lock file." }, { "code": null, "e": 1803, "s": 1650, "text": "yarn: Yarn generates a ‘yarn.lock’ file. Yarn lock files help in easy merge. The merges are predictable as well, because of the design of the lock file." }, { "code": null, "e": 1814, "s": 1803, "text": "Output log" }, { "code": null, "e": 1938, "s": 1814, "text": "install: The npm creates massive output logs of npm commands. It is essentially a dump of stack trace of what npm is doing." }, { "code": null, "e": 2071, "s": 1938, "text": "add: The yarn output logs are clean, visually distinguishable and brief. They are also ordered in a tree form for understandability." }, { "code": null, "e": 2102, "s": 2071, "text": "Installing global dependencies" }, { "code": null, "e": 2211, "s": 2102, "text": "npm: To install a global package, the command template for npm is:npm install -g package_name@version_number" }, { "code": null, "e": 2254, "s": 2211, "text": "npm install -g package_name@version_number" }, { "code": null, "e": 2366, "s": 2254, "text": "yarn: To install a global package, the command template for yarn is:yarn global add package_name@version_number" }, { "code": null, "e": 2410, "s": 2366, "text": "yarn global add package_name@version_number" }, { "code": null, "e": 2429, "s": 2410, "text": "The ‘why’ command:" }, { "code": null, "e": 2486, "s": 2429, "text": "npm: npm yet doesn’t has a ‘why’ functionality built in." }, { "code": null, "e": 2654, "s": 2486, "text": "yarn: Yarn comes with a ‘why’ command that tells why a dependency is present in the project. For example, it is a dependency, a native module, or a project dependency." }, { "code": null, "e": 2670, "s": 2654, "text": "License Checker" }, { "code": null, "e": 2824, "s": 2670, "text": "npm: npm doesn’t has a license checker that can give a handy description of all the licenses that a project is bound with, due to installed dependencies." }, { "code": null, "e": 2898, "s": 2824, "text": "yarn: Yarn has a neat license checker. To see them, runyarn licenses list" }, { "code": null, "e": 2917, "s": 2898, "text": "yarn licenses list" }, { "code": null, "e": 2935, "s": 2917, "text": "Fetching packages" }, { "code": null, "e": 3023, "s": 2935, "text": "npm: npm fetches dependencies from the npm registry during every ‘npm install‘ command." }, { "code": null, "e": 3190, "s": 3023, "text": "Yarn: yarn stores dependencies locally, and fetches from the disk during a ‘yarn add‘ command (assuming the dependency(with the specific version) is present locally)." }, { "code": null, "e": 3225, "s": 3190, "text": "Commands changed in yarn after npm" }, { "code": null, "e": 3257, "s": 3225, "text": "Commands same for npm and yarn:" }, { "code": null, "e": 3270, "s": 3257, "text": "Node.js-Misc" }, { "code": null, "e": 3278, "s": 3270, "text": "Node.js" }, { "code": null, "e": 3295, "s": 3278, "text": "Web Technologies" } ]
Sum of the series 2^0 + 2^1 + 2^2 +.....+ 2^n
03 Sep, 2021 Given an integer N, the task is to find the sum of series 20 + 21 + 22 + 23 + .... + 2n.Examples: Input: 5 Output: 31 20 + 21 + 22 + 23 + 24 = 1 + 2+ 4 + 8 + 16 = 31Input: 10 Output: 1023 20 + 21 + 2 2 + 23 + 2 4 + 25 + 26 + 27 + 2 8 + 29 = 1 + 2+ 4 + 8 + 16 + 32 +64 + 128 + 256 + 512 = 1023 A naive approach is to calculate the sum is to add every power of 2 form 0 to n.Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // C++ program to find sum#include <bits/stdc++.h>using namespace std; // function to calculate sum of seriesint calculateSum(int n){ // initialize sum as 0 int sum = 0; // loop to calculate sum of series for (int i = 0; i < n; i++) { // calculate 2^i // and add it to sum sum = sum + (1 << i); } return sum;} // Driver codeint main(){ int n = 10; cout << "Sum of series of power of 2 is : " << calculateSum(n);} // Java program to find sumclass GFG { // function to calculate sum of series static int calculate sum(int n) { // initialize sum as 0 int sum = 0; // loop to calculate sum of series for (int i = 0; i < n; i++) { // calculate 2^i // and add it to sum sum = sum + (1 << i); } return sum; } // Main function public static void main(String[] args) { int n = 10; System.out.println("Sum of the series : " + calculateSum(n)); }}; # Python3 program to calculate# sum of series of power of 2 # function to calculate sum of seriesdef calculateSum(n): sum = 0 # loop to calculate sum of series for i in range (0, n): # calculate 2 ^ i sum = sum+ (1 << i) return sum # Driver coden = 10print("Sum of series ", calculateSum(n)) // C# program to find sumusing System; class GFG{ // function to calculate // sum of series static int calculateSum(int n) { // initialize sum as 0 int sum = 0; // loop to calculate // sum of series for (int i = 0; i < n; i++) { // calculate 2^i // and add it to sum sum = sum + (1 << i); } return sum; } // Driver code public static void Main() { int n = 10; Console.WriteLine("Sum of the series : " + calculateSum(n)); }} // This code is contributed// by Akanksha Rai(Abby_akku) <?php// PHP program to find sum of the// series 2^0 + 2^1 + 2^2 +.....+ 2^n // function to calculate// sum of seriesfunction calculateSum($n){ // initialize sum as 0 $sum = 0; // loop to calculate // sum of series for ($i = 0; $i < $n; $i++) { // calculate 2^i // and add it to sum $sum = $sum + (1 << $i); } return $sum;} // Driver code$n = 10;echo "Sum of the series of " . "power 2 is : ", calculateSum($n); // This code is contributed// by Smitha?> <script> // Javascript program to find sum of the// series 2^0 + 2^1 + 2^2 +.....+ 2^n // function to calculate// sum of seriesfunction calculateSum(n){ // initialize sum as 0 let sum = 0; // loop to calculate // sum of series for (let i = 0; i < n; i++) { // calculate 2^i // and add it to sum sum = sum + (1 << i); } return sum;} // Driver codelet n = 10;document.write("Sum of the series of power 2 is : " + calculateSum(n)) //This code is contributed by sravan kumar</script> Sum of series of power of 2 is : 1023 Time Complexity: O(n) An efficient approach is to find the 2^(n+1) and subtract 1 from it since we know that 2^n can be written as: 2n = ( 20+21+22+23+24 +...... 2n-1) +1 Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // C++ program to find sum#include <bits/stdc++.h>using namespace std; int calculateSum(int n){ // calculate and return 2^(n+1) -1 return (1 << (n + 1)) - 1;} int main(){ int n = 10; cout << "Sum of series of power of 2 is :" << calculateSum(n);} // Java program to calculate// sum of series of power of 2 class GFG { // function to calculate sum of series static int calculate sum(int n) { // calculate 2^(n+1) int sum = (1 << (n + 1)); return sum - 1; } // Driver code public static void main(String[] args) { int n = 10; System.out.println("Sum of the series of power 2 is : " + calculateSum(n)); }}; # Python3 program to calculate# sum of series of 2's power # function to calculate sum of seriesdef calculateSum(n): # calculate 2^(n + 1) sum = (1 << (n + 1)) return sum-1 # Driver coden = 10print("Sum of series ", calculateSum(n)) // C# program to calculate// sum of series of power of 2using System;class GFG{ // function to calculate // sum of series static int calculateSum(int n) { // calculate 2^(n+1) int sum = (1 << (n + 1)); return sum - 1; } // Driver code public static void Main() { int n = 10; Console.Write("Sum of the series " + "of power 2 is : " + calculateSum(n)); } // This code is contributed// by Smitha} <?php// PHP program to calculate// sum of series of power of 2 // function to calculate// sum of seriesfunction calculateSum($n){ // calculate 2^(n+1) $sum = (1 << ($n + 1)); return $sum - 1;} // Driver code$n = 10;echo "Sum of the series of " . "power 2 is : ", calculateSum($n); // This code is contributed// by Smitha <script> // Javascript program to calculate// sum of series of power of 2 // function to calculate// sum of seriesfunction calculateSum(n){ // calculate 2^(n+1) let sum = (1 << (n + 1)); return sum - 1;} // Driver codelet n = 10;document.write("Sum of the series of power 2 is : " + calculateSum(n)); // This code is contributed by sravan kumar </script> Sum of series of power of 2 is :2047 Time Complexity: O(1) Smitha Dinesh Semwal Akanksha_Rai litedeveloper24 florida_man sravankumar8128 akshaysingh98088 surindertarika1234 school-programming series-sum Bit Magic School Programming Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bits manipulation (Important tactics) Josephus problem | Set 1 (A O(n) Solution) Divide two integers without using multiplication, division and mod operator Bit Fields in C Find the element that appears once Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Sep, 2021" }, { "code": null, "e": 152, "s": 52, "text": "Given an integer N, the task is to find the sum of series 20 + 21 + 22 + 23 + .... + 2n.Examples: " }, { "code": null, "e": 347, "s": 152, "text": "Input: 5 Output: 31 20 + 21 + 22 + 23 + 24 = 1 + 2+ 4 + 8 + 16 = 31Input: 10 Output: 1023 20 + 21 + 2 2 + 23 + 2 4 + 25 + 26 + 27 + 2 8 + 29 = 1 + 2+ 4 + 8 + 16 + 32 +64 + 128 + 256 + 512 = 1023" }, { "code": null, "e": 477, "s": 349, "text": "A naive approach is to calculate the sum is to add every power of 2 form 0 to n.Below is the implementation of above approach: " }, { "code": null, "e": 481, "s": 477, "text": "C++" }, { "code": null, "e": 486, "s": 481, "text": "Java" }, { "code": null, "e": 494, "s": 486, "text": "Python3" }, { "code": null, "e": 497, "s": 494, "text": "C#" }, { "code": null, "e": 501, "s": 497, "text": "PHP" }, { "code": null, "e": 512, "s": 501, "text": "Javascript" }, { "code": "// C++ program to find sum#include <bits/stdc++.h>using namespace std; // function to calculate sum of seriesint calculateSum(int n){ // initialize sum as 0 int sum = 0; // loop to calculate sum of series for (int i = 0; i < n; i++) { // calculate 2^i // and add it to sum sum = sum + (1 << i); } return sum;} // Driver codeint main(){ int n = 10; cout << \"Sum of series of power of 2 is : \" << calculateSum(n);}", "e": 981, "s": 512, "text": null }, { "code": "// Java program to find sumclass GFG { // function to calculate sum of series static int calculate sum(int n) { // initialize sum as 0 int sum = 0; // loop to calculate sum of series for (int i = 0; i < n; i++) { // calculate 2^i // and add it to sum sum = sum + (1 << i); } return sum; } // Main function public static void main(String[] args) { int n = 10; System.out.println(\"Sum of the series : \" + calculateSum(n)); }};", "e": 1523, "s": 981, "text": null }, { "code": "# Python3 program to calculate# sum of series of power of 2 # function to calculate sum of seriesdef calculateSum(n): sum = 0 # loop to calculate sum of series for i in range (0, n): # calculate 2 ^ i sum = sum+ (1 << i) return sum # Driver coden = 10print(\"Sum of series \", calculateSum(n))", "e": 1853, "s": 1523, "text": null }, { "code": "// C# program to find sumusing System; class GFG{ // function to calculate // sum of series static int calculateSum(int n) { // initialize sum as 0 int sum = 0; // loop to calculate // sum of series for (int i = 0; i < n; i++) { // calculate 2^i // and add it to sum sum = sum + (1 << i); } return sum; } // Driver code public static void Main() { int n = 10; Console.WriteLine(\"Sum of the series : \" + calculateSum(n)); }} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 2504, "s": 1853, "text": null }, { "code": "<?php// PHP program to find sum of the// series 2^0 + 2^1 + 2^2 +.....+ 2^n // function to calculate// sum of seriesfunction calculateSum($n){ // initialize sum as 0 $sum = 0; // loop to calculate // sum of series for ($i = 0; $i < $n; $i++) { // calculate 2^i // and add it to sum $sum = $sum + (1 << $i); } return $sum;} // Driver code$n = 10;echo \"Sum of the series of \" . \"power 2 is : \", calculateSum($n); // This code is contributed// by Smitha?>", "e": 3030, "s": 2504, "text": null }, { "code": "<script> // Javascript program to find sum of the// series 2^0 + 2^1 + 2^2 +.....+ 2^n // function to calculate// sum of seriesfunction calculateSum(n){ // initialize sum as 0 let sum = 0; // loop to calculate // sum of series for (let i = 0; i < n; i++) { // calculate 2^i // and add it to sum sum = sum + (1 << i); } return sum;} // Driver codelet n = 10;document.write(\"Sum of the series of power 2 is : \" + calculateSum(n)) //This code is contributed by sravan kumar</script>", "e": 3585, "s": 3030, "text": null }, { "code": null, "e": 3623, "s": 3585, "text": "Sum of series of power of 2 is : 1023" }, { "code": null, "e": 3759, "s": 3625, "text": "Time Complexity: O(n) An efficient approach is to find the 2^(n+1) and subtract 1 from it since we know that 2^n can be written as: " }, { "code": null, "e": 3798, "s": 3759, "text": "2n = ( 20+21+22+23+24 +...... 2n-1) +1" }, { "code": null, "e": 3846, "s": 3798, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 3850, "s": 3846, "text": "C++" }, { "code": null, "e": 3855, "s": 3850, "text": "Java" }, { "code": null, "e": 3863, "s": 3855, "text": "Python3" }, { "code": null, "e": 3866, "s": 3863, "text": "C#" }, { "code": null, "e": 3870, "s": 3866, "text": "PHP" }, { "code": null, "e": 3881, "s": 3870, "text": "Javascript" }, { "code": "// C++ program to find sum#include <bits/stdc++.h>using namespace std; int calculateSum(int n){ // calculate and return 2^(n+1) -1 return (1 << (n + 1)) - 1;} int main(){ int n = 10; cout << \"Sum of series of power of 2 is :\" << calculateSum(n);}", "e": 4149, "s": 3881, "text": null }, { "code": "// Java program to calculate// sum of series of power of 2 class GFG { // function to calculate sum of series static int calculate sum(int n) { // calculate 2^(n+1) int sum = (1 << (n + 1)); return sum - 1; } // Driver code public static void main(String[] args) { int n = 10; System.out.println(\"Sum of the series of power 2 is : \" + calculateSum(n)); }};", "e": 4595, "s": 4149, "text": null }, { "code": "# Python3 program to calculate# sum of series of 2's power # function to calculate sum of seriesdef calculateSum(n): # calculate 2^(n + 1) sum = (1 << (n + 1)) return sum-1 # Driver coden = 10print(\"Sum of series \", calculateSum(n))", "e": 4844, "s": 4595, "text": null }, { "code": "// C# program to calculate// sum of series of power of 2using System;class GFG{ // function to calculate // sum of series static int calculateSum(int n) { // calculate 2^(n+1) int sum = (1 << (n + 1)); return sum - 1; } // Driver code public static void Main() { int n = 10; Console.Write(\"Sum of the series \" + \"of power 2 is : \" + calculateSum(n)); } // This code is contributed// by Smitha}", "e": 5356, "s": 4844, "text": null }, { "code": "<?php// PHP program to calculate// sum of series of power of 2 // function to calculate// sum of seriesfunction calculateSum($n){ // calculate 2^(n+1) $sum = (1 << ($n + 1)); return $sum - 1;} // Driver code$n = 10;echo \"Sum of the series of \" . \"power 2 is : \", calculateSum($n); // This code is contributed// by Smitha", "e": 5712, "s": 5356, "text": null }, { "code": "<script> // Javascript program to calculate// sum of series of power of 2 // function to calculate// sum of seriesfunction calculateSum(n){ // calculate 2^(n+1) let sum = (1 << (n + 1)); return sum - 1;} // Driver codelet n = 10;document.write(\"Sum of the series of power 2 is : \" + calculateSum(n)); // This code is contributed by sravan kumar </script>", "e": 6103, "s": 5712, "text": null }, { "code": null, "e": 6140, "s": 6103, "text": "Sum of series of power of 2 is :2047" }, { "code": null, "e": 6165, "s": 6142, "text": "Time Complexity: O(1) " }, { "code": null, "e": 6186, "s": 6165, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 6199, "s": 6186, "text": "Akanksha_Rai" }, { "code": null, "e": 6215, "s": 6199, "text": "litedeveloper24" }, { "code": null, "e": 6227, "s": 6215, "text": "florida_man" }, { "code": null, "e": 6243, "s": 6227, "text": "sravankumar8128" }, { "code": null, "e": 6260, "s": 6243, "text": "akshaysingh98088" }, { "code": null, "e": 6279, "s": 6260, "text": "surindertarika1234" }, { "code": null, "e": 6298, "s": 6279, "text": "school-programming" }, { "code": null, "e": 6309, "s": 6298, "text": "series-sum" }, { "code": null, "e": 6319, "s": 6309, "text": "Bit Magic" }, { "code": null, "e": 6338, "s": 6319, "text": "School Programming" }, { "code": null, "e": 6348, "s": 6338, "text": "Bit Magic" }, { "code": null, "e": 6446, "s": 6348, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6484, "s": 6446, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 6527, "s": 6484, "text": "Josephus problem | Set 1 (A O(n) Solution)" }, { "code": null, "e": 6603, "s": 6527, "text": "Divide two integers without using multiplication, division and mod operator" }, { "code": null, "e": 6619, "s": 6603, "text": "Bit Fields in C" }, { "code": null, "e": 6654, "s": 6619, "text": "Find the element that appears once" }, { "code": null, "e": 6672, "s": 6654, "text": "Python Dictionary" }, { "code": null, "e": 6697, "s": 6672, "text": "Reverse a string in Java" }, { "code": null, "e": 6713, "s": 6697, "text": "Arrays in C/C++" }, { "code": null, "e": 6736, "s": 6713, "text": "Introduction To PYTHON" } ]
Prime factors of a big number
08 Jun, 2022 Given a number N, print all the prime factors and their powers. Here N <= 10^18Examples : Input : 250 Output : 2 1 5 3 Explanation: The prime factors of 250 are 2 and 5. 2 appears once in the prime factorization of and 5 is thrice in it. Input : 1000000000000000000 Output : 2 18 5 18 Explanation: The prime factors of 1000000000000000000 are 2 and 5. The prime factor 2 appears 18 times in the prime factorization. 5 appears 18 times. We cannot use Sieve’s implementation for a single large number as it requires proportional space. We first count the number of times 2 is the factor of the given number, then we iterate from 3 to Sqrt(n) to get the number of times a prime number divides a particular number which reduces every time by n/i. We divide our number n (whose prime factorization is to be calculated) by its corresponding smallest prime factor till n becomes 1. And if at the end n>2, it means it’s a prime number, so we print that particular number. C++ Java Python3 C# PHP Javascript // CPP program to print prime factors and their// powers.#include <bits/stdc++.h>using namespace std; // function to calculate all the prime factors and// count of every prime factorvoid factorize(long long n){ int count = 0; // count the number of times 2 divides while (!(n % 2)) { n >>= 1; // equivalent to n=n/2; count++; } // if 2 divides it if (count) cout << 2 << " " << count << endl; // check for all the possible numbers that can // divide it for (long long i = 3; i <= sqrt(n); i += 2) { count = 0; while (n % i == 0) { count++; n = n / i; } if (count) cout << i << " " << count << endl; } // if n at the end is a prime number. if (n > 2) cout << n << " " << 1 << endl;} // driver program to test the above functionint main(){ long long n = 1000000000000000000; factorize(n); return 0;} //Java program to print prime// factors and their powers. class GFG { // function to calculate all the// prime factors and count of// every prime factor static void factorize(long n) { int count = 0; // count the number of times 2 divides while (!(n % 2 > 0)) { // equivalent to n=n/2; n >>= 1; count++; } // if 2 divides it if (count > 0) { System.out.println("2" + " " + count); } // check for all the possible // numbers that can divide it for (long i = 3; i <= (long) Math.sqrt(n); i += 2) { count = 0; while (n % i == 0) { count++; n = n / i; } if (count > 0) { System.out.println(i + " " + count); } } // if n at the end is a prime number. if (n > 2) { System.out.println(n + " " + "1"); } } public static void main(String[] args) { long n = 1000000000000000000L; factorize(n); }} /*This code is contributed by 29AjayKumar*/ # Python3 program to print prime factors# and their powers.import math # Function to calculate all the prime# factors and count of every prime factordef factorize(n): count = 0; # count the number of # times 2 divides while ((n % 2 > 0) == False): # equivalent to n = n / 2; n >>= 1; count += 1; # if 2 divides it if (count > 0): print(2, count); # check for all the possible # numbers that can divide it for i in range(3, int(math.sqrt(n)) + 1): count = 0; while (n % i == 0): count += 1; n = int(n / i); if (count > 0): print(i, count); i += 2; # if n at the end is a prime number. if (n > 2): print(n, 1); # Driver Coden = 1000000000000000000;factorize(n); # This code is contributed by mits // C# program to print prime// factors and their powers.using System; public class GFG{ // function to calculate all the// prime factors and count of// every prime factorstatic void factorize(long n){ int count = 0; // count the number of times 2 divides while (! (n % 2 > 0)) { // equivalent to n=n/2; n >>= 1; count++; } // if 2 divides it if (count > 0) Console.WriteLine("2" + " " +count); // check for all the possible // numbers that can divide it for (long i = 3; i <= (long) Math.Sqrt(n); i += 2) { count = 0; while (n % i == 0) { count++; n = n / i; } if (count > 0) Console.WriteLine(i + " " + count); } // if n at the end is a prime number. if (n > 2) Console.WriteLine(n +" " + "1" );} // Driver Code static public void Main () { long n = 1000000000000000000; factorize(n); }} // This code is contributed by vt_m. <?php// PHP program to print prime// factors and their powers. // function to calculate all// the prime factors and count// of every prime factorfunction factorize($n){ $count = 0; // count the number of // times 2 divides while (!($n % 2)) { // equivalent to n = n / 2; $n >>= 1; $count++; } // if 2 divides it if ($count) echo(2 . " " . $count . "\n"); // check for all the possible // numbers that can divide it for ($i = 3; $i <= sqrt($n); $i += 2) { $count = 0; while ($n % $i == 0) { $count++; $n = $n / $i; } if ($count) echo($i . " " . $count); } // if n at the end is a prime number. if ($n > 2) echo($n . " " . 1);} // Driver Code$n = 1000000000000000000;factorize($n); // This code is contributed by Ajit.?> <script> // JavaScript program to print prime factors and their// powers. // function to calculate all the prime factors and// count of every prime factorfunction factorize(n){ var count = 0; // count the number of times 2 divides while ((n % 2)==0) { n = parseInt(n/2) // equivalent to n=n/2; count++; } // if 2 divides it if (count) document.write( 2 + " " + count + "<br>"); // check for all the possible numbers that can // divide it for (var i = 3; i <= parseInt(Math.sqrt(n)); i += 2) { count = 0; while (n % i == 0) { count++; n = parseInt(n / i); } if (count!=0) document.write( i + " " + count + "<br>"); } // if n at the end is a prime number. if (n > 2) document.write( n + " " + 1 + "<br>");} // driver program to test the above functionvar n = 1000000000000000000;factorize(n); </script> Output: 2 18 5 18 Time Complexity: O(sqrt(N)), as we are using a loop to traverse sqrt(N) times. Auxiliary Space: O(1), as we are not using any extra space. vt_m jit_t 29AjayKumar Mithun Kumar famously rohan07 prime-factor Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operators in C / C++ Prime Numbers Find minimum number of coins that make a given value Minimum number of jumps to reach end Algorithm to solve Rubik's Cube Modulo 10^9+7 (1000000007) The Knight's tour problem | Backtracking-1 Modulo Operator (%) in C/C++ with Examples Program for factorial of a number Program to find sum of elements in a given array
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Jun, 2022" }, { "code": null, "e": 146, "s": 54, "text": "Given a number N, print all the prime factors and their powers. Here N <= 10^18Examples : " }, { "code": null, "e": 520, "s": 146, "text": "Input : 250 \nOutput : 2 1\n 5 3\nExplanation: The prime factors of 250 are 2\nand 5. 2 appears once in the prime factorization \nof and 5 is thrice in it. \n\nInput : 1000000000000000000\nOutput : 2 18\n 5 18\nExplanation: The prime factors of 1000000000000000000\nare 2 and 5. The prime factor 2 appears 18 times in \nthe prime factorization. 5 appears 18 times. " }, { "code": null, "e": 1052, "s": 522, "text": "We cannot use Sieve’s implementation for a single large number as it requires proportional space. We first count the number of times 2 is the factor of the given number, then we iterate from 3 to Sqrt(n) to get the number of times a prime number divides a particular number which reduces every time by n/i. We divide our number n (whose prime factorization is to be calculated) by its corresponding smallest prime factor till n becomes 1. And if at the end n>2, it means it’s a prime number, so we print that particular number. " }, { "code": null, "e": 1056, "s": 1052, "text": "C++" }, { "code": null, "e": 1061, "s": 1056, "text": "Java" }, { "code": null, "e": 1069, "s": 1061, "text": "Python3" }, { "code": null, "e": 1072, "s": 1069, "text": "C#" }, { "code": null, "e": 1076, "s": 1072, "text": "PHP" }, { "code": null, "e": 1087, "s": 1076, "text": "Javascript" }, { "code": "// CPP program to print prime factors and their// powers.#include <bits/stdc++.h>using namespace std; // function to calculate all the prime factors and// count of every prime factorvoid factorize(long long n){ int count = 0; // count the number of times 2 divides while (!(n % 2)) { n >>= 1; // equivalent to n=n/2; count++; } // if 2 divides it if (count) cout << 2 << \" \" << count << endl; // check for all the possible numbers that can // divide it for (long long i = 3; i <= sqrt(n); i += 2) { count = 0; while (n % i == 0) { count++; n = n / i; } if (count) cout << i << \" \" << count << endl; } // if n at the end is a prime number. if (n > 2) cout << n << \" \" << 1 << endl;} // driver program to test the above functionint main(){ long long n = 1000000000000000000; factorize(n); return 0;}", "e": 2026, "s": 1087, "text": null }, { "code": "//Java program to print prime// factors and their powers. class GFG { // function to calculate all the// prime factors and count of// every prime factor static void factorize(long n) { int count = 0; // count the number of times 2 divides while (!(n % 2 > 0)) { // equivalent to n=n/2; n >>= 1; count++; } // if 2 divides it if (count > 0) { System.out.println(\"2\" + \" \" + count); } // check for all the possible // numbers that can divide it for (long i = 3; i <= (long) Math.sqrt(n); i += 2) { count = 0; while (n % i == 0) { count++; n = n / i; } if (count > 0) { System.out.println(i + \" \" + count); } } // if n at the end is a prime number. if (n > 2) { System.out.println(n + \" \" + \"1\"); } } public static void main(String[] args) { long n = 1000000000000000000L; factorize(n); }} /*This code is contributed by 29AjayKumar*/", "e": 3142, "s": 2026, "text": null }, { "code": "# Python3 program to print prime factors# and their powers.import math # Function to calculate all the prime# factors and count of every prime factordef factorize(n): count = 0; # count the number of # times 2 divides while ((n % 2 > 0) == False): # equivalent to n = n / 2; n >>= 1; count += 1; # if 2 divides it if (count > 0): print(2, count); # check for all the possible # numbers that can divide it for i in range(3, int(math.sqrt(n)) + 1): count = 0; while (n % i == 0): count += 1; n = int(n / i); if (count > 0): print(i, count); i += 2; # if n at the end is a prime number. if (n > 2): print(n, 1); # Driver Coden = 1000000000000000000;factorize(n); # This code is contributed by mits", "e": 3979, "s": 3142, "text": null }, { "code": "// C# program to print prime// factors and their powers.using System; public class GFG{ // function to calculate all the// prime factors and count of// every prime factorstatic void factorize(long n){ int count = 0; // count the number of times 2 divides while (! (n % 2 > 0)) { // equivalent to n=n/2; n >>= 1; count++; } // if 2 divides it if (count > 0) Console.WriteLine(\"2\" + \" \" +count); // check for all the possible // numbers that can divide it for (long i = 3; i <= (long) Math.Sqrt(n); i += 2) { count = 0; while (n % i == 0) { count++; n = n / i; } if (count > 0) Console.WriteLine(i + \" \" + count); } // if n at the end is a prime number. if (n > 2) Console.WriteLine(n +\" \" + \"1\" );} // Driver Code static public void Main () { long n = 1000000000000000000; factorize(n); }} // This code is contributed by vt_m.", "e": 5000, "s": 3979, "text": null }, { "code": "<?php// PHP program to print prime// factors and their powers. // function to calculate all// the prime factors and count// of every prime factorfunction factorize($n){ $count = 0; // count the number of // times 2 divides while (!($n % 2)) { // equivalent to n = n / 2; $n >>= 1; $count++; } // if 2 divides it if ($count) echo(2 . \" \" . $count . \"\\n\"); // check for all the possible // numbers that can divide it for ($i = 3; $i <= sqrt($n); $i += 2) { $count = 0; while ($n % $i == 0) { $count++; $n = $n / $i; } if ($count) echo($i . \" \" . $count); } // if n at the end is a prime number. if ($n > 2) echo($n . \" \" . 1);} // Driver Code$n = 1000000000000000000;factorize($n); // This code is contributed by Ajit.?>", "e": 5871, "s": 5000, "text": null }, { "code": "<script> // JavaScript program to print prime factors and their// powers. // function to calculate all the prime factors and// count of every prime factorfunction factorize(n){ var count = 0; // count the number of times 2 divides while ((n % 2)==0) { n = parseInt(n/2) // equivalent to n=n/2; count++; } // if 2 divides it if (count) document.write( 2 + \" \" + count + \"<br>\"); // check for all the possible numbers that can // divide it for (var i = 3; i <= parseInt(Math.sqrt(n)); i += 2) { count = 0; while (n % i == 0) { count++; n = parseInt(n / i); } if (count!=0) document.write( i + \" \" + count + \"<br>\"); } // if n at the end is a prime number. if (n > 2) document.write( n + \" \" + 1 + \"<br>\");} // driver program to test the above functionvar n = 1000000000000000000;factorize(n); </script>", "e": 6808, "s": 5871, "text": null }, { "code": null, "e": 6818, "s": 6808, "text": "Output: " }, { "code": null, "e": 6828, "s": 6818, "text": "2 18\n5 18" }, { "code": null, "e": 6907, "s": 6828, "text": "Time Complexity: O(sqrt(N)), as we are using a loop to traverse sqrt(N) times." }, { "code": null, "e": 6968, "s": 6907, "text": "Auxiliary Space: O(1), as we are not using any extra space. " }, { "code": null, "e": 6973, "s": 6968, "text": "vt_m" }, { "code": null, "e": 6979, "s": 6973, "text": "jit_t" }, { "code": null, "e": 6991, "s": 6979, "text": "29AjayKumar" }, { "code": null, "e": 7004, "s": 6991, "text": "Mithun Kumar" }, { "code": null, "e": 7013, "s": 7004, "text": "famously" }, { "code": null, "e": 7021, "s": 7013, "text": "rohan07" }, { "code": null, "e": 7034, "s": 7021, "text": "prime-factor" }, { "code": null, "e": 7047, "s": 7034, "text": "Mathematical" }, { "code": null, "e": 7060, "s": 7047, "text": "Mathematical" }, { "code": null, "e": 7158, "s": 7060, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7179, "s": 7158, "text": "Operators in C / C++" }, { "code": null, "e": 7193, "s": 7179, "text": "Prime Numbers" }, { "code": null, "e": 7246, "s": 7193, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 7283, "s": 7246, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 7315, "s": 7283, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 7342, "s": 7315, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 7385, "s": 7342, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 7428, "s": 7385, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 7462, "s": 7428, "text": "Program for factorial of a number" } ]
Python program to apply itertools.product to elements of a list of lists
27 Feb, 2020 Itertools is a module that consists of the methods to apply various iteration based operations including combinations, permutations, etc., on the iterable components in Python. It has a set lightweight, memory-efficient and fast tools for performing iterator algebra. Note: For more information, refer to Python Itertools It is used to perform cartesian product within a list or among lists. The nested loops cycle in a way that the rightmost element advancing on every iteration. This pattern creates a lexicographic ordering and thus if the input’s iterables are sorted, the product tuples are also in sorted order. It takes iterables as the parameter. The below example shows a very simple representation of itertools.product() method. Here it is used as a creation of a cartesian product. Example: import itertools def product(str1, str2): # returning the list containing # cartesian product return [x for x in itertools.product(list(str1), list(str2))] print(product("GfG", "GFG")) Output: [(‘G’, ‘G’), (‘G’, ‘F’), (‘G’, ‘G’), (‘f’, ‘G’), (‘f’, ‘F’), (‘f’, ‘G’), (‘G’, ‘G’), (‘G’, ‘F’), (‘G’, ‘G’)] Operating on list of lists To use itertools.product() method on list of lists, perform unpacking operation first. It can be done using two ways: By unpacking the list inside functionThe example below shows that how can unpacking be performed by simple operation within the method.import itertools def product(list_of_str): str1 = list_of_str[0] str2 = list_of_str[1] # returning the list # containing cartesian product return [x for x in itertools.product(list(str1), list(str2))] print(product(["GfG", "GFG"]))Output[(‘G’, ‘G’), (‘G’, ‘F’), (‘G’, ‘G’), (‘f’, ‘G’), (‘f’, ‘F’), (‘f’, ‘G’), (‘G’, ‘G’), (‘G’, ‘F’), (‘G’, ‘G’)]The disadvantage of this way is that, it requires additional information to be known i.e the length of the list inside the lists. The example below shows that how can unpacking be performed by simple operation within the method. import itertools def product(list_of_str): str1 = list_of_str[0] str2 = list_of_str[1] # returning the list # containing cartesian product return [x for x in itertools.product(list(str1), list(str2))] print(product(["GfG", "GFG"])) Output [(‘G’, ‘G’), (‘G’, ‘F’), (‘G’, ‘G’), (‘f’, ‘G’), (‘f’, ‘F’), (‘f’, ‘G’), (‘G’, ‘G’), (‘G’, ‘F’), (‘G’, ‘G’)] The disadvantage of this way is that, it requires additional information to be known i.e the length of the list inside the lists. Using ‘*’ operatorTo overcome the above mentioned disadvantage ‘*’ is used to unpack the lists within the list. So the above code can be optimized as follows:import itertools def product(lst): # Unpack operation performed # by '*' operator and returning # the list containing cartesian # product return [x for x in itertools.product(*lst)] # list of lists being passed in the methodprint(product(["GfG", "GFG"]))Output[(‘G’, ‘G’), (‘G’, ‘F’), (‘G’, ‘G’), (‘f’, ‘G’), (‘f’, ‘F’), (‘f’, ‘G’), (‘G’, ‘G’), (‘G’, ‘F’), (‘G’, ‘G’)] To overcome the above mentioned disadvantage ‘*’ is used to unpack the lists within the list. So the above code can be optimized as follows: import itertools def product(lst): # Unpack operation performed # by '*' operator and returning # the list containing cartesian # product return [x for x in itertools.product(*lst)] # list of lists being passed in the methodprint(product(["GfG", "GFG"])) Output [(‘G’, ‘G’), (‘G’, ‘F’), (‘G’, ‘G’), (‘f’, ‘G’), (‘f’, ‘F’), (‘f’, ‘G’), (‘G’, ‘G’), (‘G’, ‘F’), (‘G’, ‘G’)] Python-itertools Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Feb, 2020" }, { "code": null, "e": 296, "s": 28, "text": "Itertools is a module that consists of the methods to apply various iteration based operations including combinations, permutations, etc., on the iterable components in Python. It has a set lightweight, memory-efficient and fast tools for performing iterator algebra." }, { "code": null, "e": 350, "s": 296, "text": "Note: For more information, refer to Python Itertools" }, { "code": null, "e": 646, "s": 350, "text": "It is used to perform cartesian product within a list or among lists. The nested loops cycle in a way that the rightmost element advancing on every iteration. This pattern creates a lexicographic ordering and thus if the input’s iterables are sorted, the product tuples are also in sorted order." }, { "code": null, "e": 821, "s": 646, "text": "It takes iterables as the parameter. The below example shows a very simple representation of itertools.product() method. Here it is used as a creation of a cartesian product." }, { "code": null, "e": 830, "s": 821, "text": "Example:" }, { "code": "import itertools def product(str1, str2): # returning the list containing # cartesian product return [x for x in itertools.product(list(str1), list(str2))] print(product(\"GfG\", \"GFG\"))", "e": 1075, "s": 830, "text": null }, { "code": null, "e": 1083, "s": 1075, "text": "Output:" }, { "code": null, "e": 1192, "s": 1083, "text": "[(‘G’, ‘G’), (‘G’, ‘F’), (‘G’, ‘G’), (‘f’, ‘G’), (‘f’, ‘F’), (‘f’, ‘G’), (‘G’, ‘G’), (‘G’, ‘F’), (‘G’, ‘G’)]" }, { "code": null, "e": 1219, "s": 1192, "text": "Operating on list of lists" }, { "code": null, "e": 1337, "s": 1219, "text": "To use itertools.product() method on list of lists, perform unpacking operation first. It can be done using two ways:" }, { "code": null, "e": 2019, "s": 1337, "text": "By unpacking the list inside functionThe example below shows that how can unpacking be performed by simple operation within the method.import itertools def product(list_of_str): str1 = list_of_str[0] str2 = list_of_str[1] # returning the list # containing cartesian product return [x for x in itertools.product(list(str1), list(str2))] print(product([\"GfG\", \"GFG\"]))Output[(‘G’, ‘G’), (‘G’, ‘F’), (‘G’, ‘G’), (‘f’, ‘G’), (‘f’, ‘F’), (‘f’, ‘G’), (‘G’, ‘G’), (‘G’, ‘F’), (‘G’, ‘G’)]The disadvantage of this way is that, it requires additional information to be known i.e the length of the list inside the lists." }, { "code": null, "e": 2118, "s": 2019, "text": "The example below shows that how can unpacking be performed by simple operation within the method." }, { "code": "import itertools def product(list_of_str): str1 = list_of_str[0] str2 = list_of_str[1] # returning the list # containing cartesian product return [x for x in itertools.product(list(str1), list(str2))] print(product([\"GfG\", \"GFG\"]))", "e": 2422, "s": 2118, "text": null }, { "code": null, "e": 2429, "s": 2422, "text": "Output" }, { "code": null, "e": 2538, "s": 2429, "text": "[(‘G’, ‘G’), (‘G’, ‘F’), (‘G’, ‘G’), (‘f’, ‘G’), (‘f’, ‘F’), (‘f’, ‘G’), (‘G’, ‘G’), (‘G’, ‘F’), (‘G’, ‘G’)]" }, { "code": null, "e": 2668, "s": 2538, "text": "The disadvantage of this way is that, it requires additional information to be known i.e the length of the list inside the lists." }, { "code": null, "e": 3222, "s": 2668, "text": "Using ‘*’ operatorTo overcome the above mentioned disadvantage ‘*’ is used to unpack the lists within the list. So the above code can be optimized as follows:import itertools def product(lst): # Unpack operation performed # by '*' operator and returning # the list containing cartesian # product return [x for x in itertools.product(*lst)] # list of lists being passed in the methodprint(product([\"GfG\", \"GFG\"]))Output[(‘G’, ‘G’), (‘G’, ‘F’), (‘G’, ‘G’), (‘f’, ‘G’), (‘f’, ‘F’), (‘f’, ‘G’), (‘G’, ‘G’), (‘G’, ‘F’), (‘G’, ‘G’)]" }, { "code": null, "e": 3363, "s": 3222, "text": "To overcome the above mentioned disadvantage ‘*’ is used to unpack the lists within the list. So the above code can be optimized as follows:" }, { "code": "import itertools def product(lst): # Unpack operation performed # by '*' operator and returning # the list containing cartesian # product return [x for x in itertools.product(*lst)] # list of lists being passed in the methodprint(product([\"GfG\", \"GFG\"]))", "e": 3645, "s": 3363, "text": null }, { "code": null, "e": 3652, "s": 3645, "text": "Output" }, { "code": null, "e": 3761, "s": 3652, "text": "[(‘G’, ‘G’), (‘G’, ‘F’), (‘G’, ‘G’), (‘f’, ‘G’), (‘f’, ‘F’), (‘f’, ‘G’), (‘G’, ‘G’), (‘G’, ‘F’), (‘G’, ‘G’)]" }, { "code": null, "e": 3778, "s": 3761, "text": "Python-itertools" }, { "code": null, "e": 3785, "s": 3778, "text": "Python" }, { "code": null, "e": 3883, "s": 3785, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3915, "s": 3883, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3942, "s": 3915, "text": "Python Classes and Objects" }, { "code": null, "e": 3973, "s": 3942, "text": "Python | os.path.join() method" }, { "code": null, "e": 3996, "s": 3973, "text": "Introduction To PYTHON" }, { "code": null, "e": 4017, "s": 3996, "text": "Python OOPs Concepts" }, { "code": null, "e": 4073, "s": 4017, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 4115, "s": 4073, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 4157, "s": 4115, "text": "Check if element exists in list in Python" }, { "code": null, "e": 4196, "s": 4157, "text": "Python | Get unique values from a list" } ]
Python | Ways to concatenate boolean to string
29 Jun, 2019 Given a string and a boolean value, write a Python program to concatenate the string with a boolean value, given below are few methods to solve the task. Method #1: Using format() # Python code to demonstrate # to concatenate boolean value# with string # Initialising string and boolean valueini_string = "Facts are"value = True # Concatenate using formatres = str(ini_string+" {}").format(value) # Printing resultant stringprint ("Resultant String : ", res) Resultant String : Facts are True Method #2: Using str # Python code to demonstrate # to concatenate boolean value# with string # Initialising string and boolean valueini_string = "Facts are"value = True # Concatenate using strres = ini_string +" "+str(value) # Printing resultant stringprint ("Resultant String : ", res) Resultant String : Facts are True Method #3: Using %s # Python code to demonstrate # to concatenate boolean value# with string # Concatenate using % sanswer = Trueres = "Facts are %s" %answer # Printing resultant stringprint ("Resultant String : ", res) Resultant String : Facts are True Python string-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": "\n29 Jun, 2019" }, { "code": null, "e": 182, "s": 28, "text": "Given a string and a boolean value, write a Python program to concatenate the string with a boolean value, given below are few methods to solve the task." }, { "code": null, "e": 208, "s": 182, "text": "Method #1: Using format()" }, { "code": "# Python code to demonstrate # to concatenate boolean value# with string # Initialising string and boolean valueini_string = \"Facts are\"value = True # Concatenate using formatres = str(ini_string+\" {}\").format(value) # Printing resultant stringprint (\"Resultant String : \", res)", "e": 490, "s": 208, "text": null }, { "code": null, "e": 526, "s": 490, "text": "Resultant String : Facts are True\n" }, { "code": null, "e": 548, "s": 526, "text": " Method #2: Using str" }, { "code": "# Python code to demonstrate # to concatenate boolean value# with string # Initialising string and boolean valueini_string = \"Facts are\"value = True # Concatenate using strres = ini_string +\" \"+str(value) # Printing resultant stringprint (\"Resultant String : \", res) ", "e": 829, "s": 548, "text": null }, { "code": null, "e": 865, "s": 829, "text": "Resultant String : Facts are True\n" }, { "code": null, "e": 886, "s": 865, "text": " Method #3: Using %s" }, { "code": "# Python code to demonstrate # to concatenate boolean value# with string # Concatenate using % sanswer = Trueres = \"Facts are %s\" %answer # Printing resultant stringprint (\"Resultant String : \", res) ", "e": 1099, "s": 886, "text": null }, { "code": null, "e": 1135, "s": 1099, "text": "Resultant String : Facts are True\n" }, { "code": null, "e": 1158, "s": 1135, "text": "Python string-programs" }, { "code": null, "e": 1165, "s": 1158, "text": "Python" }, { "code": null, "e": 1181, "s": 1165, "text": "Python Programs" } ]
How to show/hide an element using jQuery ?
23 Sep, 2021 In this article, we will learn how to show/hide an element using jQuery. We can do these using jQuery methods like css(), show(), hide(), and toggle() methods. Approach: Create an HTML file in your local system “index.html“Create an HTML element inside the <body> tag for example paragraph <p>, image <img>, etc.Create a button using a <button> tag and attach an event listener to it.We use this button to toggle the show and hide animation. It means when the selected element is shown and you click the hide button then the code inside your event listener should hide the element that you selected and change the text of that element or vice-versa. Create an HTML file in your local system “index.html“ Create an HTML element inside the <body> tag for example paragraph <p>, image <img>, etc. Create a button using a <button> tag and attach an event listener to it. We use this button to toggle the show and hide animation. It means when the selected element is shown and you click the hide button then the code inside your event listener should hide the element that you selected and change the text of that element or vice-versa. Method 1: Using css() methods – It takes two parameters where the first parameter is the property name and the second parameter is the value of the property. $(selector).css(property, value); It takes one parameter type JSON string object and the object contains the properties along with their values. $(selector).css(property); HTML <!DOCTYPE html><html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"> </script> <style> body { border: 2px solid green; min-height: 240px; text-align: center; } h1 { color: green; } div { display: flex; justify-content: center; } .button-container { display: flex; justify-content: center; margin-top: 20px; } </style></head> <body> <h1>GeeksforGeeks</h1> <div id="element"> Hello Geeks Welcome to GeeksforGeeks </div> <div class="button-container"> <button id="click"> hide </button> </div> <script> $('#click').on('click', function () { if ($('#click').text() === 'show') { // This block is executed when // you click the show button $('#click').text('hide'); $('#element').css('display', 'flex'); } else { // This block is executed when // you click the hide button $('#click').text('show'); $('#element').css('display', 'none'); } }); </script></body> </html> Output: output Method 2: This method is used to show the hidden element and the parameter that it takes are optional. $(selector).show(optional); This method is used to hide the visible element and the parameter that it takes are optional. $(selector).hide(optional); HTML <!DOCTYPE html><html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"> </script> <style> body { border: 2px solid green; min-height: 240px; text-align: center; } h1 { color: green; } div { display: flex; justify-content: center; } .button-container { display: flex; justify-content: center; margin-top: 20px; } </style></head> <body> <h1>GeeksforGeeks</h1> <div id="element"> Hello Geeks Welcome to GeeksforGeeks </div> <div class="button-container"> <button id="click"> hide </button> </div> <script> $('#click').on('click', function () { if ($('#click').text() === 'show') { // This block is executed when // you click the show button $('#click').text('hide'); $('#element').show(); } else { // This block is executed when // you click the hide button $('#click').text('show'); $('#element').hide(); } }); </script></body> </html> Output: The output of the show/hide method Method 3: This method hides the element if it is visible and shows the element if it is hidden. This method can do both functionalities of the show and hide method and the parameter is optional. $(selector).toggle(optional) HTML <!DOCTYPE html><html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"> </script> <style> body { border: 2px solid green; min-height: 240px; text-align: center; } h1 { color: green; } div { display: flex; justify-content: center; } .button-container { display: flex; justify-content: center; margin-top: 20px; } </style></head> <body> <h1>GeeksforGeeks</h1> <div id="element"> Hello Geeks Welcome to GeeksforGeeks </div> <div class="button-container"> <button id="click"> hide </button> </div> <script> $('#click').on('click', function () { if ($('#click').text() === 'show') { // This block is executed when // you click the show button $('#click').text('hide'); } else { // This block is executed when // you click the hide button $('#click').text('show'); } $('#element').toggle(); }); </script></body> </html> Output: the output of toggle method Blogathon-2021 CSS-Properties HTML-Questions jQuery-Methods jQuery-Questions Picked Blogathon CSS HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Import JSON Data into SQL Server? SQL Query to Convert Datetime to Date Python program to convert XML to Dictionary Scrape LinkedIn Using Selenium And Beautiful Soup in Python How to toggle password visibility in forms using Bootstrap-icons ? How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Sep, 2021" }, { "code": null, "e": 188, "s": 28, "text": "In this article, we will learn how to show/hide an element using jQuery. We can do these using jQuery methods like css(), show(), hide(), and toggle() methods." }, { "code": null, "e": 198, "s": 188, "text": "Approach:" }, { "code": null, "e": 678, "s": 198, "text": "Create an HTML file in your local system “index.html“Create an HTML element inside the <body> tag for example paragraph <p>, image <img>, etc.Create a button using a <button> tag and attach an event listener to it.We use this button to toggle the show and hide animation. It means when the selected element is shown and you click the hide button then the code inside your event listener should hide the element that you selected and change the text of that element or vice-versa." }, { "code": null, "e": 732, "s": 678, "text": "Create an HTML file in your local system “index.html“" }, { "code": null, "e": 822, "s": 732, "text": "Create an HTML element inside the <body> tag for example paragraph <p>, image <img>, etc." }, { "code": null, "e": 895, "s": 822, "text": "Create a button using a <button> tag and attach an event listener to it." }, { "code": null, "e": 1161, "s": 895, "text": "We use this button to toggle the show and hide animation. It means when the selected element is shown and you click the hide button then the code inside your event listener should hide the element that you selected and change the text of that element or vice-versa." }, { "code": null, "e": 1319, "s": 1161, "text": "Method 1: Using css() methods – It takes two parameters where the first parameter is the property name and the second parameter is the value of the property." }, { "code": null, "e": 1353, "s": 1319, "text": "$(selector).css(property, value);" }, { "code": null, "e": 1464, "s": 1353, "text": "It takes one parameter type JSON string object and the object contains the properties along with their values." }, { "code": null, "e": 1491, "s": 1464, "text": "$(selector).css(property);" }, { "code": null, "e": 1496, "s": 1491, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js\"> </script> <style> body { border: 2px solid green; min-height: 240px; text-align: center; } h1 { color: green; } div { display: flex; justify-content: center; } .button-container { display: flex; justify-content: center; margin-top: 20px; } </style></head> <body> <h1>GeeksforGeeks</h1> <div id=\"element\"> Hello Geeks Welcome to GeeksforGeeks </div> <div class=\"button-container\"> <button id=\"click\"> hide </button> </div> <script> $('#click').on('click', function () { if ($('#click').text() === 'show') { // This block is executed when // you click the show button $('#click').text('hide'); $('#element').css('display', 'flex'); } else { // This block is executed when // you click the hide button $('#click').text('show'); $('#element').css('display', 'none'); } }); </script></body> </html>", "e": 2823, "s": 1496, "text": null }, { "code": null, "e": 2833, "s": 2825, "text": "Output:" }, { "code": null, "e": 2840, "s": 2833, "text": "output" }, { "code": null, "e": 2943, "s": 2840, "text": "Method 2: This method is used to show the hidden element and the parameter that it takes are optional." }, { "code": null, "e": 2971, "s": 2943, "text": "$(selector).show(optional);" }, { "code": null, "e": 3065, "s": 2971, "text": "This method is used to hide the visible element and the parameter that it takes are optional." }, { "code": null, "e": 3093, "s": 3065, "text": "$(selector).hide(optional);" }, { "code": null, "e": 3098, "s": 3093, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js\"> </script> <style> body { border: 2px solid green; min-height: 240px; text-align: center; } h1 { color: green; } div { display: flex; justify-content: center; } .button-container { display: flex; justify-content: center; margin-top: 20px; } </style></head> <body> <h1>GeeksforGeeks</h1> <div id=\"element\"> Hello Geeks Welcome to GeeksforGeeks </div> <div class=\"button-container\"> <button id=\"click\"> hide </button> </div> <script> $('#click').on('click', function () { if ($('#click').text() === 'show') { // This block is executed when // you click the show button $('#click').text('hide'); $('#element').show(); } else { // This block is executed when // you click the hide button $('#click').text('show'); $('#element').hide(); } }); </script></body> </html>", "e": 4395, "s": 3098, "text": null }, { "code": null, "e": 4403, "s": 4395, "text": "Output:" }, { "code": null, "e": 4438, "s": 4403, "text": "The output of the show/hide method" }, { "code": null, "e": 4633, "s": 4438, "text": "Method 3: This method hides the element if it is visible and shows the element if it is hidden. This method can do both functionalities of the show and hide method and the parameter is optional." }, { "code": null, "e": 4662, "s": 4633, "text": "$(selector).toggle(optional)" }, { "code": null, "e": 4667, "s": 4662, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js\"> </script> <style> body { border: 2px solid green; min-height: 240px; text-align: center; } h1 { color: green; } div { display: flex; justify-content: center; } .button-container { display: flex; justify-content: center; margin-top: 20px; } </style></head> <body> <h1>GeeksforGeeks</h1> <div id=\"element\"> Hello Geeks Welcome to GeeksforGeeks </div> <div class=\"button-container\"> <button id=\"click\"> hide </button> </div> <script> $('#click').on('click', function () { if ($('#click').text() === 'show') { // This block is executed when // you click the show button $('#click').text('hide'); } else { // This block is executed when // you click the hide button $('#click').text('show'); } $('#element').toggle(); }); </script></body> </html>", "e": 5923, "s": 4667, "text": null }, { "code": null, "e": 5931, "s": 5923, "text": "Output:" }, { "code": null, "e": 5959, "s": 5931, "text": "the output of toggle method" }, { "code": null, "e": 5974, "s": 5959, "text": "Blogathon-2021" }, { "code": null, "e": 5989, "s": 5974, "text": "CSS-Properties" }, { "code": null, "e": 6004, "s": 5989, "text": "HTML-Questions" }, { "code": null, "e": 6019, "s": 6004, "text": "jQuery-Methods" }, { "code": null, "e": 6036, "s": 6019, "text": "jQuery-Questions" }, { "code": null, "e": 6043, "s": 6036, "text": "Picked" }, { "code": null, "e": 6053, "s": 6043, "text": "Blogathon" }, { "code": null, "e": 6057, "s": 6053, "text": "CSS" }, { "code": null, "e": 6062, "s": 6057, "text": "HTML" }, { "code": null, "e": 6069, "s": 6062, "text": "JQuery" }, { "code": null, "e": 6086, "s": 6069, "text": "Web Technologies" }, { "code": null, "e": 6091, "s": 6086, "text": "HTML" }, { "code": null, "e": 6189, "s": 6091, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6230, "s": 6189, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 6268, "s": 6230, "text": "SQL Query to Convert Datetime to Date" }, { "code": null, "e": 6312, "s": 6268, "text": "Python program to convert XML to Dictionary" }, { "code": null, "e": 6372, "s": 6312, "text": "Scrape LinkedIn Using Selenium And Beautiful Soup in Python" }, { "code": null, "e": 6439, "s": 6372, "text": "How to toggle password visibility in forms using Bootstrap-icons ?" }, { "code": null, "e": 6487, "s": 6439, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 6549, "s": 6487, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 6599, "s": 6549, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 6657, "s": 6599, "text": "How to create footer to stay at the bottom of a Web page?" } ]
Subsequence of size k with maximum possible GCD
11 May, 2021 We are given an array of positive integers and an integer k. Find the maximum possible GCD of a subsequence of size k. Examples: Input : arr[] = [2, 1, 4, 6] k = 3 Output : 2 GCD of [2, 4, 6] is 2 Input : arr[] = [1, 2, 3] k = 3 Output : 1 GCD of [1, 2, 3] is 1 Method 1 Generate all the subsequences of size k one by one and then find the GCD of all such generated subsequences. Print the largest found GCD. Method 2 In this method, we maintain a count array to store the count of divisors of every element. We will traverse the given array and for every element, we will calculate its divisors and increment at the index of the count array. The process of computing divisors will take O(sqrt(arr[i])) time, where arr[i] is element in the given array at index i. After the whole traversal, we can simply traverse the count array from the last index to index 1. If we find an index with a value equal to or greater than k, then this means that it is a divisor of at least k elements and also the max GCD. C++ Java Python 3 C# Javascript // CPP program to find subsequence of size// k with maximum possible GCD.#include <bits/stdc++.h>using namespace std; // function to find GCD of sub sequence of// size k with max GCD in the arrayint findMaxGCD(int arr[], int n, int k){ // Computing highest element int high = *max_element(arr, arr+n); // Array to store the count of divisors // i.e. Potential GCDs int divisors[high + 1] = { 0 }; // Iterating over every element for (int i = 0; i < n; i++) { // Calculating all the divisors for (int j = 1; j <= sqrt(arr[i]); j++) { // Divisor found if (arr[i] % j == 0) { // Incrementing count for divisor divisors[j]++; // Element/divisor is also a divisor // Checking if both divisors are // not same if (j != arr[i] / j) divisors[arr[i] / j]++; } } } // Checking the highest potential GCD for (int i = high; i >= 1; i--) // If this divisor can divide at least k // numbers, it is a GCD of at least one // sub sequence of size k if (divisors[i] >= k) return i;} // Driver codeint main(){ // Array in which sub sequence with size // k with max GCD is to be found int arr[] = { 1, 2, 4, 8, 8, 12 }; int k = 3; int n = sizeof(arr) / sizeof(arr[0]); cout << findMaxGCD(arr, n, k); return 0;} // Java program to find// subsequence of size// k with maximum possible GCDimport java .io.*;import java .util.*; class GFG{ // function to find GCD of// sub sequence of size k// with max GCD in the arraystatic int findMaxGCD(int []arr, int n, int k){ Arrays.sort(arr); // Computing highest element int high = arr[n - 1]; // Array to store the // count of divisors // i.e. Potential GCDs int []divisors = new int[high + 1]; // Iterating over // every element for (int i = 0; i < n; i++) { // Calculating all the divisors for (int j = 1; j <= Math.sqrt(arr[i]); j++) { // Divisor found if (arr[i] % j == 0) { // Incrementing count // for divisor divisors[j]++; // Element/divisor is // also a divisor Checking // if both divisors are // not same if (j != arr[i] / j) divisors[arr[i] / j]++; } } } // Checking the highest // potential GCD for (int i = high; i >= 1; i--) // If this divisor can divide // at least k numbers, it is // a GCD of at least one sub // sequence of size k if (divisors[i] >= k) return i; return 0 ;} // Driver codestatic public void main (String[] args){ // Array in which sub sequence // with size k with max GCD is // to be found int []arr = { 1, 2, 4, 8, 8, 12 }; int k = 3; int n = arr.length; System.out.println(findMaxGCD(arr, n, k));}} // This code is contributed// by anuj_67. # Python 3 program to find subsequence# of size k with maximum possible GCD.import math # function to find GCD of sub sequence# of size k with max GCD in the arraydef findMaxGCD(arr, n, k): # Computing highest element high = max(arr) # Array to store the count of # divisors i.e. Potential GCDs divisors = [0] * (high + 1) # Iterating over every element for i in range(n) : # Calculating all the divisors for j in range(1, int(math.sqrt(arr[i])) + 1): # Divisor found if (arr[i] % j == 0) : # Incrementing count for divisor divisors[j] += 1 # Element/divisor is also a divisor # Checking if both divisors are # not same if (j != arr[i] // j): divisors[arr[i] // j] += 1 # Checking the highest potential GCD for i in range(high, 0, -1): # If this divisor can divide at least k # numbers, it is a GCD of at least one # sub sequence of size k if (divisors[i] >= k): return i # Driver codeif __name__ == "__main__": # Array in which sub sequence with size # k with max GCD is to be found arr = [ 1, 2, 4, 8, 8, 12 ] k = 3 n = len(arr) print(findMaxGCD(arr, n, k)) # This code is contributed by ita_c // C# program to find subsequence of size// k with maximum possible GCDusing System;using System.Linq; public class GFG { // function to find GCD of sub sequence of // size k with max GCD in the array static int findMaxGCD(int []arr, int n, int k) { // Computing highest element int high = arr.Max(); // Array to store the count of divisors // i.e. Potential GCDs int []divisors = new int[high+1]; // Iterating over every element for (int i = 0; i < n; i++) { // Calculating all the divisors for (int j = 1; j <= Math.Sqrt(arr[i]); j++) { // Divisor found if (arr[i] % j == 0) { // Incrementing count for divisor divisors[j]++; // Element/divisor is also a divisor // Checking if both divisors are // not same if (j != arr[i] / j) divisors[arr[i] / j]++; } } } // Checking the highest potential GCD for (int i = high; i >= 1; i--) // If this divisor can divide at least k // numbers, it is a GCD of at least one // sub sequence of size k if (divisors[i] >= k) return i; return 0 ; } // Driver code static public void Main () { // Array in which sub sequence with // size k with max GCD is to be found int []arr = { 1, 2, 4, 8, 8, 12 }; int k = 3; int n = arr.Length; Console.WriteLine(findMaxGCD(arr, n, k)); }} // This code is contributed by anuj_67. <script>// Javascript program to find// subsequence of size// k with maximum possible GCD // function to find GCD of// sub sequence of size k// with max GCD in the array function findMaxGCD(arr,n,k) { arr.sort(function(a,b){return a-b;}); // Computing highest element let high = arr[n - 1]; // Array to store the // count of divisors // i.e. Potential GCDs let divisors = new Array(high + 1); for(let i=0;i<divisors.length;i++) { divisors[i]=0; } // Iterating over // every element for (let i = 0; i < n; i++) { // Calculating all the divisors for (let j = 1; j <= Math.sqrt(arr[i]); j++) { // Divisor found if (arr[i] % j == 0) { // Incrementing count // for divisor divisors[j]++; // Element/divisor is // also a divisor Checking // if both divisors are // not same if (j != Math.floor(arr[i] / j)) divisors[Math.floor(arr[i] / j)]++; } } } // Checking the highest // potential GCD for (let i = high; i >= 1; i--) // If this divisor can divide // at least k numbers, it is // a GCD of at least one sub // sequence of size k if (divisors[i] >= k) return i; return 0 ; } // Driver code let arr=[1, 2, 4, 8, 8, 12]; let k = 3; let n = arr.length; document.write(findMaxGCD(arr, n, k)); // This code is contributed by rag2127</script> 4 vt_m ukasp Code_r Akanksha_Rai rag2127 GCD-LCM Arrays Mathematical Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Linear Search Introduction to Arrays Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 54, "s": 26, "text": "\n11 May, 2021" }, { "code": null, "e": 173, "s": 54, "text": "We are given an array of positive integers and an integer k. Find the maximum possible GCD of a subsequence of size k." }, { "code": null, "e": 184, "s": 173, "text": "Examples: " }, { "code": null, "e": 319, "s": 184, "text": "Input : arr[] = [2, 1, 4, 6] k = 3\nOutput : 2\nGCD of [2, 4, 6] is 2\n\nInput : arr[] = [1, 2, 3] k = 3\nOutput : 1\nGCD of [1, 2, 3] is 1 " }, { "code": null, "e": 466, "s": 319, "text": "Method 1 Generate all the subsequences of size k one by one and then find the GCD of all such generated subsequences. Print the largest found GCD." }, { "code": null, "e": 1064, "s": 466, "text": "Method 2 In this method, we maintain a count array to store the count of divisors of every element. We will traverse the given array and for every element, we will calculate its divisors and increment at the index of the count array. The process of computing divisors will take O(sqrt(arr[i])) time, where arr[i] is element in the given array at index i. After the whole traversal, we can simply traverse the count array from the last index to index 1. If we find an index with a value equal to or greater than k, then this means that it is a divisor of at least k elements and also the max GCD. " }, { "code": null, "e": 1068, "s": 1064, "text": "C++" }, { "code": null, "e": 1073, "s": 1068, "text": "Java" }, { "code": null, "e": 1082, "s": 1073, "text": "Python 3" }, { "code": null, "e": 1085, "s": 1082, "text": "C#" }, { "code": null, "e": 1096, "s": 1085, "text": "Javascript" }, { "code": "// CPP program to find subsequence of size// k with maximum possible GCD.#include <bits/stdc++.h>using namespace std; // function to find GCD of sub sequence of// size k with max GCD in the arrayint findMaxGCD(int arr[], int n, int k){ // Computing highest element int high = *max_element(arr, arr+n); // Array to store the count of divisors // i.e. Potential GCDs int divisors[high + 1] = { 0 }; // Iterating over every element for (int i = 0; i < n; i++) { // Calculating all the divisors for (int j = 1; j <= sqrt(arr[i]); j++) { // Divisor found if (arr[i] % j == 0) { // Incrementing count for divisor divisors[j]++; // Element/divisor is also a divisor // Checking if both divisors are // not same if (j != arr[i] / j) divisors[arr[i] / j]++; } } } // Checking the highest potential GCD for (int i = high; i >= 1; i--) // If this divisor can divide at least k // numbers, it is a GCD of at least one // sub sequence of size k if (divisors[i] >= k) return i;} // Driver codeint main(){ // Array in which sub sequence with size // k with max GCD is to be found int arr[] = { 1, 2, 4, 8, 8, 12 }; int k = 3; int n = sizeof(arr) / sizeof(arr[0]); cout << findMaxGCD(arr, n, k); return 0;}", "e": 2549, "s": 1096, "text": null }, { "code": "// Java program to find// subsequence of size// k with maximum possible GCDimport java .io.*;import java .util.*; class GFG{ // function to find GCD of// sub sequence of size k// with max GCD in the arraystatic int findMaxGCD(int []arr, int n, int k){ Arrays.sort(arr); // Computing highest element int high = arr[n - 1]; // Array to store the // count of divisors // i.e. Potential GCDs int []divisors = new int[high + 1]; // Iterating over // every element for (int i = 0; i < n; i++) { // Calculating all the divisors for (int j = 1; j <= Math.sqrt(arr[i]); j++) { // Divisor found if (arr[i] % j == 0) { // Incrementing count // for divisor divisors[j]++; // Element/divisor is // also a divisor Checking // if both divisors are // not same if (j != arr[i] / j) divisors[arr[i] / j]++; } } } // Checking the highest // potential GCD for (int i = high; i >= 1; i--) // If this divisor can divide // at least k numbers, it is // a GCD of at least one sub // sequence of size k if (divisors[i] >= k) return i; return 0 ;} // Driver codestatic public void main (String[] args){ // Array in which sub sequence // with size k with max GCD is // to be found int []arr = { 1, 2, 4, 8, 8, 12 }; int k = 3; int n = arr.length; System.out.println(findMaxGCD(arr, n, k));}} // This code is contributed// by anuj_67.", "e": 4287, "s": 2549, "text": null }, { "code": "# Python 3 program to find subsequence# of size k with maximum possible GCD.import math # function to find GCD of sub sequence# of size k with max GCD in the arraydef findMaxGCD(arr, n, k): # Computing highest element high = max(arr) # Array to store the count of # divisors i.e. Potential GCDs divisors = [0] * (high + 1) # Iterating over every element for i in range(n) : # Calculating all the divisors for j in range(1, int(math.sqrt(arr[i])) + 1): # Divisor found if (arr[i] % j == 0) : # Incrementing count for divisor divisors[j] += 1 # Element/divisor is also a divisor # Checking if both divisors are # not same if (j != arr[i] // j): divisors[arr[i] // j] += 1 # Checking the highest potential GCD for i in range(high, 0, -1): # If this divisor can divide at least k # numbers, it is a GCD of at least one # sub sequence of size k if (divisors[i] >= k): return i # Driver codeif __name__ == \"__main__\": # Array in which sub sequence with size # k with max GCD is to be found arr = [ 1, 2, 4, 8, 8, 12 ] k = 3 n = len(arr) print(findMaxGCD(arr, n, k)) # This code is contributed by ita_c", "e": 5623, "s": 4287, "text": null }, { "code": "// C# program to find subsequence of size// k with maximum possible GCDusing System;using System.Linq; public class GFG { // function to find GCD of sub sequence of // size k with max GCD in the array static int findMaxGCD(int []arr, int n, int k) { // Computing highest element int high = arr.Max(); // Array to store the count of divisors // i.e. Potential GCDs int []divisors = new int[high+1]; // Iterating over every element for (int i = 0; i < n; i++) { // Calculating all the divisors for (int j = 1; j <= Math.Sqrt(arr[i]); j++) { // Divisor found if (arr[i] % j == 0) { // Incrementing count for divisor divisors[j]++; // Element/divisor is also a divisor // Checking if both divisors are // not same if (j != arr[i] / j) divisors[arr[i] / j]++; } } } // Checking the highest potential GCD for (int i = high; i >= 1; i--) // If this divisor can divide at least k // numbers, it is a GCD of at least one // sub sequence of size k if (divisors[i] >= k) return i; return 0 ; } // Driver code static public void Main () { // Array in which sub sequence with // size k with max GCD is to be found int []arr = { 1, 2, 4, 8, 8, 12 }; int k = 3; int n = arr.Length; Console.WriteLine(findMaxGCD(arr, n, k)); }} // This code is contributed by anuj_67.", "e": 7369, "s": 5623, "text": null }, { "code": "<script>// Javascript program to find// subsequence of size// k with maximum possible GCD // function to find GCD of// sub sequence of size k// with max GCD in the array function findMaxGCD(arr,n,k) { arr.sort(function(a,b){return a-b;}); // Computing highest element let high = arr[n - 1]; // Array to store the // count of divisors // i.e. Potential GCDs let divisors = new Array(high + 1); for(let i=0;i<divisors.length;i++) { divisors[i]=0; } // Iterating over // every element for (let i = 0; i < n; i++) { // Calculating all the divisors for (let j = 1; j <= Math.sqrt(arr[i]); j++) { // Divisor found if (arr[i] % j == 0) { // Incrementing count // for divisor divisors[j]++; // Element/divisor is // also a divisor Checking // if both divisors are // not same if (j != Math.floor(arr[i] / j)) divisors[Math.floor(arr[i] / j)]++; } } } // Checking the highest // potential GCD for (let i = high; i >= 1; i--) // If this divisor can divide // at least k numbers, it is // a GCD of at least one sub // sequence of size k if (divisors[i] >= k) return i; return 0 ; } // Driver code let arr=[1, 2, 4, 8, 8, 12]; let k = 3; let n = arr.length; document.write(findMaxGCD(arr, n, k)); // This code is contributed by rag2127</script>", "e": 9082, "s": 7369, "text": null }, { "code": null, "e": 9084, "s": 9082, "text": "4" }, { "code": null, "e": 9091, "s": 9086, "text": "vt_m" }, { "code": null, "e": 9097, "s": 9091, "text": "ukasp" }, { "code": null, "e": 9104, "s": 9097, "text": "Code_r" }, { "code": null, "e": 9117, "s": 9104, "text": "Akanksha_Rai" }, { "code": null, "e": 9125, "s": 9117, "text": "rag2127" }, { "code": null, "e": 9133, "s": 9125, "text": "GCD-LCM" }, { "code": null, "e": 9140, "s": 9133, "text": "Arrays" }, { "code": null, "e": 9153, "s": 9140, "text": "Mathematical" }, { "code": null, "e": 9160, "s": 9153, "text": "Arrays" }, { "code": null, "e": 9173, "s": 9160, "text": "Mathematical" }, { "code": null, "e": 9271, "s": 9173, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9339, "s": 9271, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 9383, "s": 9339, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 9415, "s": 9383, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 9429, "s": 9415, "text": "Linear Search" }, { "code": null, "e": 9452, "s": 9429, "text": "Introduction to Arrays" }, { "code": null, "e": 9482, "s": 9452, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 9525, "s": 9482, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 9585, "s": 9525, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 9600, "s": 9585, "text": "C++ Data Types" } ]
How to Install Pygame on Windows ?
05 Oct, 2021 In this article, we will learn how to Install PyGame module of Python on Windows. PyGame is a library of python language. It is used to develop 2-D games and is a platform where you can set python modules to develop a game. It is a user-friendly platform that helps to build games quickly and easily. In order to install Pygame, Python must be installed already in your system. To check whether Python is installed or not in your system, open the command prompt and give the command as shown below. If this command runs successfully, and we are able to get a Python version then we are good to go. Otherwise, we have to install Python in our system, to do this refer How to install Python on Windows? PIP is a tool that is used to install python packages. PIP is automatically installed with Python 2.7. 9+ and Python 3.4+. Open the command prompt and enter the command shown below to check whether pip is installed or not. Note: Refer to How to install PIP on Windows ? for detailed information. To install Pygame, open the command prompt and give the command as shown below: pip install pygame Pygame is successfully installed as shown in the image above. Now open a new terminal and import the Pygame library to see whether it is working fine or not in our system. The library is imported successfully means we got success. In this way, we can install the pygame module in Python. how-to-install Picked Python-PyGame Installation Guide Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install and Use NVM on Windows? Installation of Node.js on Windows How to Install and Run Apache Kafka on Windows? How to Install FFmpeg on Windows? How to Install Flutter on Visual Studio Code? Iterate over a list in Python Read JSON file using Python Python map() function How to iterate through Excel rows in Python? Taking input in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Oct, 2021" }, { "code": null, "e": 354, "s": 52, "text": "In this article, we will learn how to Install PyGame module of Python on Windows. PyGame is a library of python language. It is used to develop 2-D games and is a platform where you can set python modules to develop a game. It is a user-friendly platform that helps to build games quickly and easily. " }, { "code": null, "e": 552, "s": 354, "text": "In order to install Pygame, Python must be installed already in your system. To check whether Python is installed or not in your system, open the command prompt and give the command as shown below." }, { "code": null, "e": 754, "s": 552, "text": "If this command runs successfully, and we are able to get a Python version then we are good to go. Otherwise, we have to install Python in our system, to do this refer How to install Python on Windows?" }, { "code": null, "e": 978, "s": 754, "text": "PIP is a tool that is used to install python packages. PIP is automatically installed with Python 2.7. 9+ and Python 3.4+. Open the command prompt and enter the command shown below to check whether pip is installed or not. " }, { "code": null, "e": 1051, "s": 978, "text": "Note: Refer to How to install PIP on Windows ? for detailed information." }, { "code": null, "e": 1131, "s": 1051, "text": "To install Pygame, open the command prompt and give the command as shown below:" }, { "code": null, "e": 1150, "s": 1131, "text": "pip install pygame" }, { "code": null, "e": 1212, "s": 1150, "text": "Pygame is successfully installed as shown in the image above." }, { "code": null, "e": 1381, "s": 1212, "text": "Now open a new terminal and import the Pygame library to see whether it is working fine or not in our system. The library is imported successfully means we got success." }, { "code": null, "e": 1438, "s": 1381, "text": "In this way, we can install the pygame module in Python." }, { "code": null, "e": 1453, "s": 1438, "text": "how-to-install" }, { "code": null, "e": 1460, "s": 1453, "text": "Picked" }, { "code": null, "e": 1474, "s": 1460, "text": "Python-PyGame" }, { "code": null, "e": 1493, "s": 1474, "text": "Installation Guide" }, { "code": null, "e": 1500, "s": 1493, "text": "Python" }, { "code": null, "e": 1598, "s": 1500, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1637, "s": 1598, "text": "How to Install and Use NVM on Windows?" }, { "code": null, "e": 1672, "s": 1637, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 1720, "s": 1672, "text": "How to Install and Run Apache Kafka on Windows?" }, { "code": null, "e": 1754, "s": 1720, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 1800, "s": 1754, "text": "How to Install Flutter on Visual Studio Code?" }, { "code": null, "e": 1830, "s": 1800, "text": "Iterate over a list in Python" }, { "code": null, "e": 1858, "s": 1830, "text": "Read JSON file using Python" }, { "code": null, "e": 1880, "s": 1858, "text": "Python map() function" }, { "code": null, "e": 1925, "s": 1880, "text": "How to iterate through Excel rows in Python?" } ]
Map every character of one string to another such that all occurrences are mapped to the same character
10 Jun, 2021 Given two string s1 and s2, the task is to check if characters of the first string can be mapped with the character of the second string such that if a character ch1 is mapped with some character ch2 then all the occurrences of ch1 will only be mapped with ch2 for both the strings. Examples: Input: s1 = “axx”, s2 = “cbc” Output: Yes ‘a’ in s1 can be mapped to ‘b’ in s2 and ‘x’ in s1 can be mapped to ‘c’ in s2. Input: s1 = “a”, s2 = “df” Output: No Approach: If the lengths of both the strings are unequal then the strings cannot be mapped else create two frequency arrays freq1[] and freq2[] which will store the frequencies of all the characters of the given strings s1 and s2 respectively. Now, for every non-zero value in freq1[] find an equal value in freq2[]. If all the non-zero values from freq1[] can be mapped to some value in freq2[] then the answer is possible else not. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define MAX 26 // Function that returns true if the mapping is possiblebool canBeMapped(string s1, int l1, string s2, int l2){ // Both the strings are of un-equal lengths if (l1 != l2) return false; // To store the frequencies of the // characters in both the string int freq1[MAX] = { 0 }; int freq2[MAX] = { 0 }; // Update frequencies of the characters for (int i = 0; i < l1; i++) freq1[s1[i] - 'a']++; for (int i = 0; i < l2; i++) freq2[s2[i] - 'a']++; // For every character of s1 for (int i = 0; i < MAX; i++) { // If current character is // not present in s1 if (freq1[i] == 0) continue; bool found = false; // Find a character in s2 that has frequency // equal to the current character's // frequency in s1 for (int j = 0; j < MAX; j++) { // If such character is found if (freq1[i] == freq2[j]) { // Set the frequency to -1 so that // it doesn't get picked again freq2[j] = -1; // Set found to true found = true; break; } } // If there is no character in s2 // that could be mapped to the // current character in s1 if (!found) return false; } return true;} // Driver codeint main(){ string s1 = "axx"; string s2 = "cbc"; int l1 = s1.length(); int l2 = s2.length(); if (canBeMapped(s1, l1, s2, l2)) cout << "Yes"; else cout << "No"; return 0;} // Java implementation of the approachclass GFG{ static int MAX = 26; // Function that returns true if the mapping is possible public static boolean canBeMapped(String s1, int l1, String s2, int l2) { // Both the strings are of un-equal lengths if (l1 != l2) return false; // To store the frequencies of the // characters in both the string int[] freq1 = new int[MAX]; int[] freq2 = new int[MAX]; // Update frequencies of the characters for (int i = 0; i < l1; i++) freq1[s1.charAt(i) - 'a']++; for (int i = 0; i < l2; i++) freq2[s2.charAt(i) - 'a']++; // For every character of s1 for (int i = 0; i < MAX; i++) { // If current character is // not present in s1 if (freq1[i] == 0) continue; boolean found = false; // Find a character in s2 that has frequency // equal to the current character's // frequency in s1 for (int j = 0; j < MAX; j++) { // If such character is found if (freq1[i] == freq2[j]) { // Set the frequency to -1 so that // it doesn't get picked again freq2[j] = -1; // Set found to true found = true; break; } } // If there is no character in s2 // that could be mapped to the // current character in s1 if (!found) return false; } return true; } // Driver code public static void main(String[] args) { String s1 = "axx"; String s2 = "cbc"; int l1 = s1.length(); int l2 = s2.length(); if (canBeMapped(s1, l1, s2, l2)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by// sanjeev2552 # Python 3 implementation of the approach MAX = 26 # Function that returns true if the mapping is possibledef canBeMapped(s1, l1, s2, l2): # Both the strings are of un-equal lengths if (l1 != l2): return False # To store the frequencies of the # characters in both the string freq1 = [0 for i in range(MAX)] freq2 = [0 for i in range(MAX)] # Update frequencies of the characters for i in range(l1): freq1[ord(s1[i]) - ord('a')] += 1 for i in range(l2): freq2[ord(s2[i]) - ord('a')] += 1 # For every character of s1 for i in range(MAX): # If current character is # not present in s1 if (freq1[i] == 0): continue found = False # Find a character in s2 that has frequency # equal to the current character's # frequency in s1 for j in range(MAX): # If such character is found if (freq1[i] == freq2[j]): # Set the frequency to -1 so that # it doesn't get picked again freq2[j] = -1 # Set found to true found = True break # If there is no character in s2 # that could be mapped to the # current character in s1 if (found==False): return False return True # Driver codeif __name__ == '__main__': s1 = "axx" s2 = "cbc" l1 = len(s1) l2 = len(s2) if (canBeMapped(s1, l1, s2, l2)): print("Yes") else: print("No") # This code is contributed by# Surendra_Gangwar // C# implementation of the approachusing System; class GFG{ static int MAX = 26; // Function that returns true // if the mapping is possible public static Boolean canBeMapped(String s1, int l1, String s2, int l2) { // Both the strings are of un-equal lengths if (l1 != l2) return false; // To store the frequencies of the // characters in both the string int[] freq1 = new int[MAX]; int[] freq2 = new int[MAX]; // Update frequencies of the characters for (int i = 0; i < l1; i++) freq1[s1[i] - 'a']++; for (int i = 0; i < l2; i++) freq2[s2[i] - 'a']++; // For every character of s1 for (int i = 0; i < MAX; i++) { // If current character is // not present in s1 if (freq1[i] == 0) continue; Boolean found = false; // Find a character in s2 that has frequency // equal to the current character's // frequency in s1 for (int j = 0; j < MAX; j++) { // If such character is found if (freq1[i] == freq2[j]) { // Set the frequency to -1 so that // it doesn't get picked again freq2[j] = -1; // Set found to true found = true; break; } } // If there is no character in s2 // that could be mapped to the // current character in s1 if (!found) return false; } return true; } // Driver code public static void Main(String[] args) { String s1 = "axx"; String s2 = "cbc"; int l1 = s1.Length; int l2 = s2.Length; if (canBeMapped(s1, l1, s2, l2)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed// by PrinciRaj1992 <script> // Javascript implementation of the approach var MAX = 26; // Function that returns true if the mapping is possiblefunction canBeMapped(s1, l1, s2, l2){ // Both the strings are of un-equal lengths if (l1 != l2) return false; // To store the frequencies of the // characters in both the string var freq1 = Array(MAX).fill(0); var freq2 = Array(MAX).fill(0); // Update frequencies of the characters for (var i = 0; i < l1; i++) freq1[s1[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; for (var i = 0; i < l2; i++) freq2[s2[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; // For every character of s1 for (var i = 0; i < MAX; i++) { // If current character is // not present in s1 if (freq1[i] == 0) continue; var found = false; // Find a character in s2 that has frequency // equal to the current character's // frequency in s1 for (var j = 0; j < MAX; j++) { // If such character is found if (freq1[i] == freq2[j]) { // Set the frequency to -1 so that // it doesn't get picked again freq2[j] = -1; // Set found to true found = true; break; } } // If there is no character in s2 // that could be mapped to the // current character in s1 if (!found) return false; } return true;} // Driver codevar s1 = "axx";var s2 = "cbc";var l1 = s1.length;var l2 = s2.length;if (canBeMapped(s1, l1, s2, l2)) document.write( "Yes");else document.write( "No"); </script> Yes SURENDRA_GANGWAR sanjeev2552 princiraj1992 rrrtnx arorakashish0911 frequency-counting Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 String Coding Problems for Interviews Print all the duplicates in the input string What is Data Structure: Types, Classifications and Applications Print all subsequences of a string A Program to check if strings are rotations of each other or not String class in Java | Set 1 Find the smallest window in a string containing all characters of another string Program to count occurrence of a given character in a string Return maximum occurring character in an input string String in Switch Case in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n10 Jun, 2021" }, { "code": null, "e": 336, "s": 53, "text": "Given two string s1 and s2, the task is to check if characters of the first string can be mapped with the character of the second string such that if a character ch1 is mapped with some character ch2 then all the occurrences of ch1 will only be mapped with ch2 for both the strings." }, { "code": null, "e": 347, "s": 336, "text": "Examples: " }, { "code": null, "e": 468, "s": 347, "text": "Input: s1 = “axx”, s2 = “cbc” Output: Yes ‘a’ in s1 can be mapped to ‘b’ in s2 and ‘x’ in s1 can be mapped to ‘c’ in s2." }, { "code": null, "e": 508, "s": 468, "text": "Input: s1 = “a”, s2 = “df” Output: No " }, { "code": null, "e": 942, "s": 508, "text": "Approach: If the lengths of both the strings are unequal then the strings cannot be mapped else create two frequency arrays freq1[] and freq2[] which will store the frequencies of all the characters of the given strings s1 and s2 respectively. Now, for every non-zero value in freq1[] find an equal value in freq2[]. If all the non-zero values from freq1[] can be mapped to some value in freq2[] then the answer is possible else not." }, { "code": null, "e": 995, "s": 942, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 999, "s": 995, "text": "C++" }, { "code": null, "e": 1004, "s": 999, "text": "Java" }, { "code": null, "e": 1012, "s": 1004, "text": "Python3" }, { "code": null, "e": 1015, "s": 1012, "text": "C#" }, { "code": null, "e": 1026, "s": 1015, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define MAX 26 // Function that returns true if the mapping is possiblebool canBeMapped(string s1, int l1, string s2, int l2){ // Both the strings are of un-equal lengths if (l1 != l2) return false; // To store the frequencies of the // characters in both the string int freq1[MAX] = { 0 }; int freq2[MAX] = { 0 }; // Update frequencies of the characters for (int i = 0; i < l1; i++) freq1[s1[i] - 'a']++; for (int i = 0; i < l2; i++) freq2[s2[i] - 'a']++; // For every character of s1 for (int i = 0; i < MAX; i++) { // If current character is // not present in s1 if (freq1[i] == 0) continue; bool found = false; // Find a character in s2 that has frequency // equal to the current character's // frequency in s1 for (int j = 0; j < MAX; j++) { // If such character is found if (freq1[i] == freq2[j]) { // Set the frequency to -1 so that // it doesn't get picked again freq2[j] = -1; // Set found to true found = true; break; } } // If there is no character in s2 // that could be mapped to the // current character in s1 if (!found) return false; } return true;} // Driver codeint main(){ string s1 = \"axx\"; string s2 = \"cbc\"; int l1 = s1.length(); int l2 = s2.length(); if (canBeMapped(s1, l1, s2, l2)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 2704, "s": 1026, "text": null }, { "code": "// Java implementation of the approachclass GFG{ static int MAX = 26; // Function that returns true if the mapping is possible public static boolean canBeMapped(String s1, int l1, String s2, int l2) { // Both the strings are of un-equal lengths if (l1 != l2) return false; // To store the frequencies of the // characters in both the string int[] freq1 = new int[MAX]; int[] freq2 = new int[MAX]; // Update frequencies of the characters for (int i = 0; i < l1; i++) freq1[s1.charAt(i) - 'a']++; for (int i = 0; i < l2; i++) freq2[s2.charAt(i) - 'a']++; // For every character of s1 for (int i = 0; i < MAX; i++) { // If current character is // not present in s1 if (freq1[i] == 0) continue; boolean found = false; // Find a character in s2 that has frequency // equal to the current character's // frequency in s1 for (int j = 0; j < MAX; j++) { // If such character is found if (freq1[i] == freq2[j]) { // Set the frequency to -1 so that // it doesn't get picked again freq2[j] = -1; // Set found to true found = true; break; } } // If there is no character in s2 // that could be mapped to the // current character in s1 if (!found) return false; } return true; } // Driver code public static void main(String[] args) { String s1 = \"axx\"; String s2 = \"cbc\"; int l1 = s1.length(); int l2 = s2.length(); if (canBeMapped(s1, l1, s2, l2)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by// sanjeev2552", "e": 4783, "s": 2704, "text": null }, { "code": "# Python 3 implementation of the approach MAX = 26 # Function that returns true if the mapping is possibledef canBeMapped(s1, l1, s2, l2): # Both the strings are of un-equal lengths if (l1 != l2): return False # To store the frequencies of the # characters in both the string freq1 = [0 for i in range(MAX)] freq2 = [0 for i in range(MAX)] # Update frequencies of the characters for i in range(l1): freq1[ord(s1[i]) - ord('a')] += 1 for i in range(l2): freq2[ord(s2[i]) - ord('a')] += 1 # For every character of s1 for i in range(MAX): # If current character is # not present in s1 if (freq1[i] == 0): continue found = False # Find a character in s2 that has frequency # equal to the current character's # frequency in s1 for j in range(MAX): # If such character is found if (freq1[i] == freq2[j]): # Set the frequency to -1 so that # it doesn't get picked again freq2[j] = -1 # Set found to true found = True break # If there is no character in s2 # that could be mapped to the # current character in s1 if (found==False): return False return True # Driver codeif __name__ == '__main__': s1 = \"axx\" s2 = \"cbc\" l1 = len(s1) l2 = len(s2) if (canBeMapped(s1, l1, s2, l2)): print(\"Yes\") else: print(\"No\") # This code is contributed by# Surendra_Gangwar", "e": 6356, "s": 4783, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ static int MAX = 26; // Function that returns true // if the mapping is possible public static Boolean canBeMapped(String s1, int l1, String s2, int l2) { // Both the strings are of un-equal lengths if (l1 != l2) return false; // To store the frequencies of the // characters in both the string int[] freq1 = new int[MAX]; int[] freq2 = new int[MAX]; // Update frequencies of the characters for (int i = 0; i < l1; i++) freq1[s1[i] - 'a']++; for (int i = 0; i < l2; i++) freq2[s2[i] - 'a']++; // For every character of s1 for (int i = 0; i < MAX; i++) { // If current character is // not present in s1 if (freq1[i] == 0) continue; Boolean found = false; // Find a character in s2 that has frequency // equal to the current character's // frequency in s1 for (int j = 0; j < MAX; j++) { // If such character is found if (freq1[i] == freq2[j]) { // Set the frequency to -1 so that // it doesn't get picked again freq2[j] = -1; // Set found to true found = true; break; } } // If there is no character in s2 // that could be mapped to the // current character in s1 if (!found) return false; } return true; } // Driver code public static void Main(String[] args) { String s1 = \"axx\"; String s2 = \"cbc\"; int l1 = s1.Length; int l2 = s2.Length; if (canBeMapped(s1, l1, s2, l2)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed// by PrinciRaj1992", "e": 8441, "s": 6356, "text": null }, { "code": "<script> // Javascript implementation of the approach var MAX = 26; // Function that returns true if the mapping is possiblefunction canBeMapped(s1, l1, s2, l2){ // Both the strings are of un-equal lengths if (l1 != l2) return false; // To store the frequencies of the // characters in both the string var freq1 = Array(MAX).fill(0); var freq2 = Array(MAX).fill(0); // Update frequencies of the characters for (var i = 0; i < l1; i++) freq1[s1[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; for (var i = 0; i < l2; i++) freq2[s2[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; // For every character of s1 for (var i = 0; i < MAX; i++) { // If current character is // not present in s1 if (freq1[i] == 0) continue; var found = false; // Find a character in s2 that has frequency // equal to the current character's // frequency in s1 for (var j = 0; j < MAX; j++) { // If such character is found if (freq1[i] == freq2[j]) { // Set the frequency to -1 so that // it doesn't get picked again freq2[j] = -1; // Set found to true found = true; break; } } // If there is no character in s2 // that could be mapped to the // current character in s1 if (!found) return false; } return true;} // Driver codevar s1 = \"axx\";var s2 = \"cbc\";var l1 = s1.length;var l2 = s2.length;if (canBeMapped(s1, l1, s2, l2)) document.write( \"Yes\");else document.write( \"No\"); </script>", "e": 10102, "s": 8441, "text": null }, { "code": null, "e": 10106, "s": 10102, "text": "Yes" }, { "code": null, "e": 10125, "s": 10108, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 10137, "s": 10125, "text": "sanjeev2552" }, { "code": null, "e": 10151, "s": 10137, "text": "princiraj1992" }, { "code": null, "e": 10158, "s": 10151, "text": "rrrtnx" }, { "code": null, "e": 10175, "s": 10158, "text": "arorakashish0911" }, { "code": null, "e": 10194, "s": 10175, "text": "frequency-counting" }, { "code": null, "e": 10202, "s": 10194, "text": "Strings" }, { "code": null, "e": 10210, "s": 10202, "text": "Strings" }, { "code": null, "e": 10308, "s": 10210, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10353, "s": 10308, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 10398, "s": 10353, "text": "Print all the duplicates in the input string" }, { "code": null, "e": 10462, "s": 10398, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 10497, "s": 10462, "text": "Print all subsequences of a string" }, { "code": null, "e": 10562, "s": 10497, "text": "A Program to check if strings are rotations of each other or not" }, { "code": null, "e": 10591, "s": 10562, "text": "String class in Java | Set 1" }, { "code": null, "e": 10672, "s": 10591, "text": "Find the smallest window in a string containing all characters of another string" }, { "code": null, "e": 10733, "s": 10672, "text": "Program to count occurrence of a given character in a string" }, { "code": null, "e": 10787, "s": 10733, "text": "Return maximum occurring character in an input string" } ]
NumberFormat getInstance() method in Java with Examples
01 Apr, 2019 The getInstance() method is a built-in method of the java.text.NumberFormat returns a number format for the current default FORMAT locale.Syntax:public static final NumberFormat getInstance()Parameters: The function does not accepts any parameter.Return Value: The function returns the NumberFormat instance for general purpose formatting.Below is the implementation of the above function:Program 1:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat.getInstance(); // Sets the currency to Canadian Dollar nF.setCurrency( Currency.getInstance( Locale.CANADA)); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar Program 2:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat.getInstance(); // Stores the values String values = nF.getCurrency().getDisplayName(); // Prints the currency System.out.println(values); }}Output:US Dollar Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getInstance()The getInstance(Locale inLocale) method is a built-in method of the java.text.NumberFormat returns a number format for any specifies locale.Syntax:public static NumberFormat getIntegerInstance(Locale inLocale)Parameters: The function accepts a single mandatory parameter inLocale which describes the locale which is to specifies.Return Value: The function returns the NumberFormat instance for number formatting of integer values.Below is the implementation of the above function:Program 1:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat.getInstance( Locale.CANADA); // Stores the values String values = nF.getCurrency().getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getIntegerInstance(java.util.Locale) The getInstance() method is a built-in method of the java.text.NumberFormat returns a number format for the current default FORMAT locale.Syntax:public static final NumberFormat getInstance()Parameters: The function does not accepts any parameter.Return Value: The function returns the NumberFormat instance for general purpose formatting.Below is the implementation of the above function:Program 1:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat.getInstance(); // Sets the currency to Canadian Dollar nF.setCurrency( Currency.getInstance( Locale.CANADA)); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar Program 2:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat.getInstance(); // Stores the values String values = nF.getCurrency().getDisplayName(); // Prints the currency System.out.println(values); }}Output:US Dollar Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getInstance() Syntax: public static final NumberFormat getInstance() Parameters: The function does not accepts any parameter. Return Value: The function returns the NumberFormat instance for general purpose formatting. Below is the implementation of the above function: Program 1: // Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat.getInstance(); // Sets the currency to Canadian Dollar nF.setCurrency( Currency.getInstance( Locale.CANADA)); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }} Canadian Dollar Program 2: // Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat.getInstance(); // Stores the values String values = nF.getCurrency().getDisplayName(); // Prints the currency System.out.println(values); }} US Dollar Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getInstance() The getInstance(Locale inLocale) method is a built-in method of the java.text.NumberFormat returns a number format for any specifies locale.Syntax:public static NumberFormat getIntegerInstance(Locale inLocale)Parameters: The function accepts a single mandatory parameter inLocale which describes the locale which is to specifies.Return Value: The function returns the NumberFormat instance for number formatting of integer values.Below is the implementation of the above function:Program 1:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat.getInstance( Locale.CANADA); // Stores the values String values = nF.getCurrency().getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getIntegerInstance(java.util.Locale) Syntax: public static NumberFormat getIntegerInstance(Locale inLocale) Parameters: The function accepts a single mandatory parameter inLocale which describes the locale which is to specifies. Return Value: The function returns the NumberFormat instance for number formatting of integer values. Below is the implementation of the above function: Program 1: // Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat.getInstance( Locale.CANADA); // Stores the values String values = nF.getCurrency().getDisplayName(); // Prints the currency System.out.println(values); }} Canadian Dollar Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getIntegerInstance(java.util.Locale) Java-Functions Java-NumberFormat Java-text package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Stream In Java Collections in Java Multidimensional Arrays in Java Singleton Class in Java Stack Class in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Apr, 2019" }, { "code": null, "e": 2852, "s": 28, "text": "The getInstance() method is a built-in method of the java.text.NumberFormat returns a number format for the current default FORMAT locale.Syntax:public static final NumberFormat getInstance()Parameters: The function does not accepts any parameter.Return Value: The function returns the NumberFormat instance for general purpose formatting.Below is the implementation of the above function:Program 1:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat.getInstance(); // Sets the currency to Canadian Dollar nF.setCurrency( Currency.getInstance( Locale.CANADA)); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar\nProgram 2:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat.getInstance(); // Stores the values String values = nF.getCurrency().getDisplayName(); // Prints the currency System.out.println(values); }}Output:US Dollar\nReference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getInstance()The getInstance(Locale inLocale) method is a built-in method of the java.text.NumberFormat returns a number format for any specifies locale.Syntax:public static NumberFormat getIntegerInstance(Locale inLocale)Parameters: The function accepts a single mandatory parameter inLocale which describes the locale which is to specifies.Return Value: The function returns the NumberFormat instance for number formatting of integer values.Below is the implementation of the above function:Program 1:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat.getInstance( Locale.CANADA); // Stores the values String values = nF.getCurrency().getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar\nReference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getIntegerInstance(java.util.Locale)" }, { "code": null, "e": 4528, "s": 2852, "text": "The getInstance() method is a built-in method of the java.text.NumberFormat returns a number format for the current default FORMAT locale.Syntax:public static final NumberFormat getInstance()Parameters: The function does not accepts any parameter.Return Value: The function returns the NumberFormat instance for general purpose formatting.Below is the implementation of the above function:Program 1:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat.getInstance(); // Sets the currency to Canadian Dollar nF.setCurrency( Currency.getInstance( Locale.CANADA)); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar\nProgram 2:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat.getInstance(); // Stores the values String values = nF.getCurrency().getDisplayName(); // Prints the currency System.out.println(values); }}Output:US Dollar\nReference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getInstance()" }, { "code": null, "e": 4536, "s": 4528, "text": "Syntax:" }, { "code": null, "e": 4583, "s": 4536, "text": "public static final NumberFormat getInstance()" }, { "code": null, "e": 4640, "s": 4583, "text": "Parameters: The function does not accepts any parameter." }, { "code": null, "e": 4733, "s": 4640, "text": "Return Value: The function returns the NumberFormat instance for general purpose formatting." }, { "code": null, "e": 4784, "s": 4733, "text": "Below is the implementation of the above function:" }, { "code": null, "e": 4795, "s": 4784, "text": "Program 1:" }, { "code": "// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat.getInstance(); // Sets the currency to Canadian Dollar nF.setCurrency( Currency.getInstance( Locale.CANADA)); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}", "e": 5439, "s": 4795, "text": null }, { "code": null, "e": 5456, "s": 5439, "text": "Canadian Dollar\n" }, { "code": null, "e": 5467, "s": 5456, "text": "Program 2:" }, { "code": "// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat.getInstance(); // Stores the values String values = nF.getCurrency().getDisplayName(); // Prints the currency System.out.println(values); }}", "e": 5956, "s": 5467, "text": null }, { "code": null, "e": 5967, "s": 5956, "text": "US Dollar\n" }, { "code": null, "e": 6063, "s": 5967, "text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getInstance()" }, { "code": null, "e": 7212, "s": 6063, "text": "The getInstance(Locale inLocale) method is a built-in method of the java.text.NumberFormat returns a number format for any specifies locale.Syntax:public static NumberFormat getIntegerInstance(Locale inLocale)Parameters: The function accepts a single mandatory parameter inLocale which describes the locale which is to specifies.Return Value: The function returns the NumberFormat instance for number formatting of integer values.Below is the implementation of the above function:Program 1:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat.getInstance( Locale.CANADA); // Stores the values String values = nF.getCurrency().getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar\nReference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getIntegerInstance(java.util.Locale)" }, { "code": null, "e": 7220, "s": 7212, "text": "Syntax:" }, { "code": null, "e": 7283, "s": 7220, "text": "public static NumberFormat getIntegerInstance(Locale inLocale)" }, { "code": null, "e": 7404, "s": 7283, "text": "Parameters: The function accepts a single mandatory parameter inLocale which describes the locale which is to specifies." }, { "code": null, "e": 7506, "s": 7404, "text": "Return Value: The function returns the NumberFormat instance for number formatting of integer values." }, { "code": null, "e": 7557, "s": 7506, "text": "Below is the implementation of the above function:" }, { "code": null, "e": 7568, "s": 7557, "text": "Program 1:" }, { "code": "// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat.getInstance( Locale.CANADA); // Stores the values String values = nF.getCurrency().getDisplayName(); // Prints the currency System.out.println(values); }}", "e": 8086, "s": 7568, "text": null }, { "code": null, "e": 8103, "s": 8086, "text": "Canadian Dollar\n" }, { "code": null, "e": 8222, "s": 8103, "text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getIntegerInstance(java.util.Locale)" }, { "code": null, "e": 8237, "s": 8222, "text": "Java-Functions" }, { "code": null, "e": 8255, "s": 8237, "text": "Java-NumberFormat" }, { "code": null, "e": 8273, "s": 8255, "text": "Java-text package" }, { "code": null, "e": 8278, "s": 8273, "text": "Java" }, { "code": null, "e": 8283, "s": 8278, "text": "Java" }, { "code": null, "e": 8381, "s": 8283, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8432, "s": 8381, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 8463, "s": 8432, "text": "How to iterate any Map in Java" }, { "code": null, "e": 8482, "s": 8463, "text": "Interfaces in Java" }, { "code": null, "e": 8512, "s": 8482, "text": "HashMap in Java with Examples" }, { "code": null, "e": 8530, "s": 8512, "text": "ArrayList in Java" }, { "code": null, "e": 8545, "s": 8530, "text": "Stream In Java" }, { "code": null, "e": 8565, "s": 8545, "text": "Collections in Java" }, { "code": null, "e": 8597, "s": 8565, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 8621, "s": 8597, "text": "Singleton Class in Java" } ]
How to style the Drop-Down List in ComboBox in C#? - GeeksforGeeks
30 Jun, 2019 In Windows Forms, ComboBox provides two different features in a single control, it means ComboBox works as both TextBox and ListBox. In ComboBox, only one item is displayed at a time and the rest of the items are present in the drop-down menu. You are allowed to style drop-down list in your ComboBox by using the DropDownStyle Property. The value of this property is provided by the ComboBoxStyle enumeration and the values are: Simple: In this style, the list is visible and the text can be editable. DropDown: In this style, the list is visible when you click on the drop-down arrow and the list is editable. DropDownList: In this style, the list is visible when you click on the drop-down arrow and the list is not-editable. The default value of this property is DropDown. You can set this property using two different methods: 1. Design-Time: It is the easiest method to set the DropDownStyle property of the ComboBox control using the following steps: Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Drag the ComboBox control from the ToolBox and drop it on the windows form. You are allowed to place a ComboBox control anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the ComboBox control to set the DropDownStyle property of the ComboBox.Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can style the drop-down list in the ComboBox programmatically with the help of given syntax: public System.Windows.Forms.ComboBoxStyle DropDownStyle { get; set; } Here, the style values are provided by the ComboBoxStyle. It will throw an InvalidEnumArgumentException if the value assigned to this property does not belong to ComboBoxStyle. Following steps are used to set the DropDownStyle property of the ComboBox elements: Step 1: Create a combobox using the ComboBox() constructor is provided by the ComboBox class.// Creating ComboBox using ComboBox class ComboBox mybox = new ComboBox(); // Creating ComboBox using ComboBox class ComboBox mybox = new ComboBox(); Step 2: After creating ComboBox, set the DropDownStyle property of the ComboBox provided by the ComboBox class.// Set DropDownStyle property of the combobox mybox.DropDownStyle = ComboBoxStyle.DropDown; // Set DropDownStyle property of the combobox mybox.DropDownStyle = ComboBoxStyle.DropDown; Step 3: And last add this combobox control to form using Add() method.// Add this ComboBox to form this.Controls.Add(mybox); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp14 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Location = new Point(222, 80); l.Size = new Size(99, 18); l.Text = "Select Id"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the properties of comboBox ComboBox mybox = new ComboBox(); mybox.Location = new Point(327, 77); mybox.Size = new Size(216, 26); mybox.MaxLength = 3; mybox.DropDownStyle = ComboBoxStyle.DropDown; mybox.Items.Add(240); mybox.Items.Add(241); mybox.Items.Add(242); mybox.Items.Add(243); mybox.Items.Add(244); // Adding this ComboBox to the form this.Controls.Add(mybox); }}}Output: // Add this ComboBox to form this.Controls.Add(mybox); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp14 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Location = new Point(222, 80); l.Size = new Size(99, 18); l.Text = "Select Id"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the properties of comboBox ComboBox mybox = new ComboBox(); mybox.Location = new Point(327, 77); mybox.Size = new Size(216, 26); mybox.MaxLength = 3; mybox.DropDownStyle = ComboBoxStyle.DropDown; mybox.Items.Add(240); mybox.Items.Add(241); mybox.Items.Add(242); mybox.Items.Add(243); mybox.Items.Add(244); // Adding this ComboBox to the form this.Controls.Add(mybox); }}} Output: C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C# C# | Class and Object C# | Constructors Extension Method in C# Introduction to .NET Framework C# | String.IndexOf( ) Method | Set - 1
[ { "code": null, "e": 25429, "s": 25401, "text": "\n30 Jun, 2019" }, { "code": null, "e": 25859, "s": 25429, "text": "In Windows Forms, ComboBox provides two different features in a single control, it means ComboBox works as both TextBox and ListBox. In ComboBox, only one item is displayed at a time and the rest of the items are present in the drop-down menu. You are allowed to style drop-down list in your ComboBox by using the DropDownStyle Property. The value of this property is provided by the ComboBoxStyle enumeration and the values are:" }, { "code": null, "e": 25932, "s": 25859, "text": "Simple: In this style, the list is visible and the text can be editable." }, { "code": null, "e": 26041, "s": 25932, "text": "DropDown: In this style, the list is visible when you click on the drop-down arrow and the list is editable." }, { "code": null, "e": 26158, "s": 26041, "text": "DropDownList: In this style, the list is visible when you click on the drop-down arrow and the list is not-editable." }, { "code": null, "e": 26261, "s": 26158, "text": "The default value of this property is DropDown. You can set this property using two different methods:" }, { "code": null, "e": 26387, "s": 26261, "text": "1. Design-Time: It is the easiest method to set the DropDownStyle property of the ComboBox control using the following steps:" }, { "code": null, "e": 26503, "s": 26387, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 26684, "s": 26503, "text": "Step 2: Drag the ComboBox control from the ToolBox and drop it on the windows form. You are allowed to place a ComboBox control anywhere on the windows form according to your need." }, { "code": null, "e": 26824, "s": 26684, "text": "Step 3: After drag and drop you will go to the properties of the ComboBox control to set the DropDownStyle property of the ComboBox.Output:" }, { "code": null, "e": 26832, "s": 26824, "text": "Output:" }, { "code": null, "e": 27009, "s": 26832, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can style the drop-down list in the ComboBox programmatically with the help of given syntax:" }, { "code": null, "e": 27079, "s": 27009, "text": "public System.Windows.Forms.ComboBoxStyle DropDownStyle { get; set; }" }, { "code": null, "e": 27341, "s": 27079, "text": "Here, the style values are provided by the ComboBoxStyle. It will throw an InvalidEnumArgumentException if the value assigned to this property does not belong to ComboBoxStyle. Following steps are used to set the DropDownStyle property of the ComboBox elements:" }, { "code": null, "e": 27510, "s": 27341, "text": "Step 1: Create a combobox using the ComboBox() constructor is provided by the ComboBox class.// Creating ComboBox using ComboBox class\nComboBox mybox = new ComboBox();\n" }, { "code": null, "e": 27586, "s": 27510, "text": "// Creating ComboBox using ComboBox class\nComboBox mybox = new ComboBox();\n" }, { "code": null, "e": 27791, "s": 27586, "text": "Step 2: After creating ComboBox, set the DropDownStyle property of the ComboBox provided by the ComboBox class.// Set DropDownStyle property of the combobox\n mybox.DropDownStyle = ComboBoxStyle.DropDown;\n" }, { "code": null, "e": 27885, "s": 27791, "text": "// Set DropDownStyle property of the combobox\n mybox.DropDownStyle = ComboBoxStyle.DropDown;\n" }, { "code": null, "e": 29174, "s": 27885, "text": "Step 3: And last add this combobox control to form using Add() method.// Add this ComboBox to form\nthis.Controls.Add(mybox);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp14 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Location = new Point(222, 80); l.Size = new Size(99, 18); l.Text = \"Select Id\"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the properties of comboBox ComboBox mybox = new ComboBox(); mybox.Location = new Point(327, 77); mybox.Size = new Size(216, 26); mybox.MaxLength = 3; mybox.DropDownStyle = ComboBoxStyle.DropDown; mybox.Items.Add(240); mybox.Items.Add(241); mybox.Items.Add(242); mybox.Items.Add(243); mybox.Items.Add(244); // Adding this ComboBox to the form this.Controls.Add(mybox); }}}Output:" }, { "code": null, "e": 29230, "s": 29174, "text": "// Add this ComboBox to form\nthis.Controls.Add(mybox);\n" }, { "code": null, "e": 29239, "s": 29230, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp14 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Location = new Point(222, 80); l.Size = new Size(99, 18); l.Text = \"Select Id\"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the properties of comboBox ComboBox mybox = new ComboBox(); mybox.Location = new Point(327, 77); mybox.Size = new Size(216, 26); mybox.MaxLength = 3; mybox.DropDownStyle = ComboBoxStyle.DropDown; mybox.Items.Add(240); mybox.Items.Add(241); mybox.Items.Add(242); mybox.Items.Add(243); mybox.Items.Add(244); // Adding this ComboBox to the form this.Controls.Add(mybox); }}}", "e": 30388, "s": 29239, "text": null }, { "code": null, "e": 30396, "s": 30388, "text": "Output:" }, { "code": null, "e": 30399, "s": 30396, "text": "C#" }, { "code": null, "e": 30497, "s": 30399, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30525, "s": 30497, "text": "C# Dictionary with examples" }, { "code": null, "e": 30540, "s": 30525, "text": "C# | Delegates" }, { "code": null, "e": 30563, "s": 30540, "text": "C# | Method Overriding" }, { "code": null, "e": 30585, "s": 30563, "text": "C# | Abstract Classes" }, { "code": null, "e": 30631, "s": 30585, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 30653, "s": 30631, "text": "C# | Class and Object" }, { "code": null, "e": 30671, "s": 30653, "text": "C# | Constructors" }, { "code": null, "e": 30694, "s": 30671, "text": "Extension Method in C#" }, { "code": null, "e": 30725, "s": 30694, "text": "Introduction to .NET Framework" } ]
Count of pairs in an Array whose sum is Prime - GeeksforGeeks
17 May, 2021 Given an array arr of size N elements, the task is to count the number of pairs of elements in the array whose sum is prime. Examples: Input: arr = {1, 2, 3, 4, 5} Output: 5 Explanation: Pairs with sum as a prime number are: {1, 2}, {1, 4}, {2, 3}, {2, 5} and {3, 4} Input: arr = {10, 20, 30, 40} Output: 0 Explanation: No pair whose sum is a prime number exists. Naive Approach: Calculate the sum of every pair of elements in the array and check if that sum is a prime number or not. Below code is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ code to count of pairs// of elements in an array// whose sum is prime#include <bits/stdc++.h>using namespace std; // Function to check whether a// number is prime or notbool isPrime(int num){ if (num == 0 || num == 1) { return false; } for (int i = 2; i * i <= num; i++) { if (num % i == 0) { return false; } } return true;} // Function to count total number of pairs// of elements whose sum is primeint numPairsWithPrimeSum(int* arr, int n){ int count = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int sum = arr[i] + arr[j]; if (isPrime(sum)) { count++; } } } return count;} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << numPairsWithPrimeSum(arr, n); return 0;} // Java code to find number of pairs of// elements in an array whose sum is primeimport java.io.*;import java.util.*; class GFG { // Function to check whether a number // is prime or not public static boolean isPrime(int num) { if (num == 0 || num == 1) { return false; } for (int i = 2; i * i <= num; i++) { if (num % i == 0) { return false; } } return true; } // Function to count total number of pairs // of elements whose sum is prime public static int numPairsWithPrimeSum( int[] arr, int n) { int count = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int sum = arr[i] + arr[j]; if (isPrime(sum)) { count++; } } } return count; } // Driver code public static void main(String[] args) { int[] arr = { 1, 2, 3, 4, 5 }; int n = arr.length; System.out.println( numPairsWithPrimeSum(arr, n)); }} # Python3 code to find number of pairs of# elements in an array whose sum is primeimport math # Function to check whether a# number is prime or notdef isPrime(num): sq = int(math.ceil(math.sqrt(num))) if num == 0 or num == 1: return False for i in range(2, sq + 1): if num % i == 0: return False return True # Function to count total number of pairs# of elements whose sum is primedef numPairsWithPrimeSum(arr, n): count = 0 for i in range(n): for j in range(i + 1, n): sum = arr[i] + arr[j] if isPrime(sum): count += 1 return count # Driver Codearr = [ 1, 2, 3, 4, 5 ]n = len(arr) print(numPairsWithPrimeSum(arr, n)) # This code is contributed by grand_master // C# code to find number of pairs of// elements in an array whose sum is primeusing System;class GFG{ // Function to check whether a number// is prime or notpublic static bool isPrime(int num){ if (num == 0 || num == 1) { return false; } for (int i = 2; i * i <= num; i++) { if (num % i == 0) { return false; } } return true;} // Function to count total number of pairs// of elements whose sum is primepublic static int numPairsWithPrimeSum(int[] arr, int n){ int count = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int sum = arr[i] + arr[j]; if (isPrime(sum)) { count++; } } } return count;} // Driver codepublic static void Main(){ int[] arr = { 1, 2, 3, 4, 5 }; int n = arr.Length; Console.Write(numPairsWithPrimeSum(arr, n));}} // This code is contributed by Nidhi_Biet <script>// Javascript code to count of pairs// of elements in an array// whose sum is prime // Function to check whether a// number is prime or notfunction isPrime(num){ if (num == 0 || num == 1) { return false; } for (let i = 2; i * i <= num; i++) { if (num % i == 0) { return false; } } return true;} // Function to count total number of pairs// of elements whose sum is primefunction numPairsWithPrimeSum(arr, n){ let count = 0; for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { let sum = arr[i] + arr[j]; if (isPrime(sum)) { count++; } } } return count;} // Driver Code let arr = [ 1, 2, 3, 4, 5 ];let n = arr.length;document.write(numPairsWithPrimeSum(arr, n)); // This code is contributed by _saurabh_jaiswal</script> 5 Time Complexity: Efficient Approach: Precompute and store the primes by using Sieve of Eratosthenes. Now, for every pair of elements, check whether their sum is prime or not. Below code is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ code to find number of pairs// of elements in an array whose// sum is prime#include <bits/stdc++.h>using namespace std; // Function for Sieve Of Eratosthenesbool* sieveOfEratosthenes(int N){ bool* isPrime = new bool[N + 1]; for (int i = 0; i < N + 1; i++) { isPrime[i] = true; } isPrime[0] = false; isPrime[1] = false; for (int i = 2; i * i <= N; i++) { if (isPrime[i] == true) { int j = 2; while (i * j <= N) { isPrime[i * j] = false; j++; } } } return isPrime;} // Function to count total number of pairs// of elements whose sum is primeint numPairsWithPrimeSum(int* arr, int n){ int N = 2 * 1000000; bool* isPrime = sieveOfEratosthenes(N); int count = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int sum = arr[i] + arr[j]; if (isPrime[sum]) { count++; } } } return count;} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << numPairsWithPrimeSum(arr, n); return 0;} // Java code to find number of pairs of// elements in an array whose sum is primeimport java.io.*;import java.util.*; class GFG { // Function for Sieve Of Eratosthenes public static boolean[] sieveOfEratosthenes(int N) { boolean[] isPrime = new boolean[N + 1]; for (int i = 0; i < N + 1; i++) { isPrime[i] = true; } isPrime[0] = false; isPrime[1] = false; for (int i = 2; i * i <= N; i++) { if (isPrime[i] == true) { int j = 2; while (i * j <= N) { isPrime[i * j] = false; j++; } } } return isPrime; } // Function to count total number of pairs // of elements whose sum is prime public static int numPairsWithPrimeSum( int[] arr, int n) { int N = 2 * 1000000; boolean[] isPrime = sieveOfEratosthenes(N); int count = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int sum = arr[i] + arr[j]; if (isPrime[sum]) { count++; } } } return count; } // Driver code public static void main(String[] args) { int[] arr = { 1, 2, 3, 4, 5 }; int n = arr.length; System.out.println( numPairsWithPrimeSum(arr, n)); }} # Python3 code to find number of pairs of# elements in an array whose sum is prime # Function for Sieve Of Eratosthenesdef sieveOfEratosthenes(N): isPrime = [True for i in range(N + 1)] isPrime[0] = False isPrime[1] = False i = 2 while((i * i) <= N): if (isPrime[i]): j = 2 while (i * j <= N): isPrime[i * j] = False j += 1 i += 1 return isPrime # Function to count total number of pairs# of elements whose sum is primedef numPairsWithPrimeSum(arr, n): N = 2 * 1000000 isPrime = sieveOfEratosthenes(N) count = 0 for i in range(n): for j in range(i + 1, n): sum = arr[i] + arr[j] if (isPrime[sum]): count += 1 return count # Driver code if __name__=="__main__": arr = [ 1, 2, 3, 4, 5 ] n = len(arr) print(numPairsWithPrimeSum(arr, n)) # This code is contributed by rutvik_56 // C# code to find number of pairs of// elements in an array whose sum is primeusing System; class GFG{ // Function for Sieve Of Eratosthenespublic static bool[] sieveOfEratosthenes(int N){ bool[] isPrime = new bool[N + 1]; for (int i = 0; i < N + 1; i++) { isPrime[i] = true; } isPrime[0] = false; isPrime[1] = false; for (int i = 2; i * i <= N; i++) { if (isPrime[i] == true) { int j = 2; while (i * j <= N) { isPrime[i * j] = false; j++; } } } return isPrime;} // Function to count total number of pairs// of elements whose sum is primepublic static int numPairsWithPrimeSum(int[] arr, int n){ int N = 2 * 1000000; bool[] isPrime = sieveOfEratosthenes(N); int count = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int sum = arr[i] + arr[j]; if (isPrime[sum]) { count++; } } } return count;} // Driver codepublic static void Main(String[] args){ int[] arr = { 1, 2, 3, 4, 5 }; int n = arr.Length; Console.WriteLine(numPairsWithPrimeSum(arr, n));}} // This code is contributed by 29AjayKumar <script> // JavaScript code to find number of pairs of// elements in an array whose sum is prime // Function for Sieve Of Eratosthenes function sieveOfEratosthenes(N) { let isPrime = Array.from({length: N+1}, (_, i) => 0); for (let i = 0; i < N + 1; i++) { isPrime[i] = true; } isPrime[0] = false; isPrime[1] = false; for (let i = 2; i * i <= N; i++) { if (isPrime[i] == true) { let j = 2; while (i * j <= N) { isPrime[i * j] = false; j++; } } } return isPrime; } // Function to count total number of pairs // of elements whose sum is prime function numPairsWithPrimeSum( arr, n) { let N = 2 * 1000000; let isPrime = sieveOfEratosthenes(N); let count = 0; for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { let sum = arr[i] + arr[j]; if (isPrime[sum]) { count++; } } } return count; } // Driver Code let arr = [ 1, 2, 3, 4, 5 ]; let n = arr.length; document.write( numPairsWithPrimeSum(arr, n) ); </script> 5 Time complexity: O(N^2) 29AjayKumar nidhi_biet grand_master rutvik_56 code_hunt _saurabh_jaiswal Prime Number sieve Arrays Competitive Programming Mathematical Arrays Mathematical Prime Number sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Count pairs with given sum Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Prefix Sum Array - Implementation and Applications in Competitive Programming Fast I/O for Competitive Programming
[ { "code": null, "e": 26041, "s": 26013, "text": "\n17 May, 2021" }, { "code": null, "e": 26166, "s": 26041, "text": "Given an array arr of size N elements, the task is to count the number of pairs of elements in the array whose sum is prime." }, { "code": null, "e": 26177, "s": 26166, "text": "Examples: " }, { "code": null, "e": 26309, "s": 26177, "text": "Input: arr = {1, 2, 3, 4, 5} Output: 5 Explanation: Pairs with sum as a prime number are: {1, 2}, {1, 4}, {2, 3}, {2, 5} and {3, 4}" }, { "code": null, "e": 26408, "s": 26309, "text": "Input: arr = {10, 20, 30, 40} Output: 0 Explanation: No pair whose sum is a prime number exists. " }, { "code": null, "e": 26529, "s": 26408, "text": "Naive Approach: Calculate the sum of every pair of elements in the array and check if that sum is a prime number or not." }, { "code": null, "e": 26585, "s": 26529, "text": "Below code is the implementation of the above approach:" }, { "code": null, "e": 26589, "s": 26585, "text": "C++" }, { "code": null, "e": 26594, "s": 26589, "text": "Java" }, { "code": null, "e": 26602, "s": 26594, "text": "Python3" }, { "code": null, "e": 26605, "s": 26602, "text": "C#" }, { "code": null, "e": 26616, "s": 26605, "text": "Javascript" }, { "code": "// C++ code to count of pairs// of elements in an array// whose sum is prime#include <bits/stdc++.h>using namespace std; // Function to check whether a// number is prime or notbool isPrime(int num){ if (num == 0 || num == 1) { return false; } for (int i = 2; i * i <= num; i++) { if (num % i == 0) { return false; } } return true;} // Function to count total number of pairs// of elements whose sum is primeint numPairsWithPrimeSum(int* arr, int n){ int count = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int sum = arr[i] + arr[j]; if (isPrime(sum)) { count++; } } } return count;} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << numPairsWithPrimeSum(arr, n); return 0;}", "e": 27499, "s": 26616, "text": null }, { "code": "// Java code to find number of pairs of// elements in an array whose sum is primeimport java.io.*;import java.util.*; class GFG { // Function to check whether a number // is prime or not public static boolean isPrime(int num) { if (num == 0 || num == 1) { return false; } for (int i = 2; i * i <= num; i++) { if (num % i == 0) { return false; } } return true; } // Function to count total number of pairs // of elements whose sum is prime public static int numPairsWithPrimeSum( int[] arr, int n) { int count = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int sum = arr[i] + arr[j]; if (isPrime(sum)) { count++; } } } return count; } // Driver code public static void main(String[] args) { int[] arr = { 1, 2, 3, 4, 5 }; int n = arr.length; System.out.println( numPairsWithPrimeSum(arr, n)); }}", "e": 28597, "s": 27499, "text": null }, { "code": "# Python3 code to find number of pairs of# elements in an array whose sum is primeimport math # Function to check whether a# number is prime or notdef isPrime(num): sq = int(math.ceil(math.sqrt(num))) if num == 0 or num == 1: return False for i in range(2, sq + 1): if num % i == 0: return False return True # Function to count total number of pairs# of elements whose sum is primedef numPairsWithPrimeSum(arr, n): count = 0 for i in range(n): for j in range(i + 1, n): sum = arr[i] + arr[j] if isPrime(sum): count += 1 return count # Driver Codearr = [ 1, 2, 3, 4, 5 ]n = len(arr) print(numPairsWithPrimeSum(arr, n)) # This code is contributed by grand_master", "e": 29396, "s": 28597, "text": null }, { "code": "// C# code to find number of pairs of// elements in an array whose sum is primeusing System;class GFG{ // Function to check whether a number// is prime or notpublic static bool isPrime(int num){ if (num == 0 || num == 1) { return false; } for (int i = 2; i * i <= num; i++) { if (num % i == 0) { return false; } } return true;} // Function to count total number of pairs// of elements whose sum is primepublic static int numPairsWithPrimeSum(int[] arr, int n){ int count = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int sum = arr[i] + arr[j]; if (isPrime(sum)) { count++; } } } return count;} // Driver codepublic static void Main(){ int[] arr = { 1, 2, 3, 4, 5 }; int n = arr.Length; Console.Write(numPairsWithPrimeSum(arr, n));}} // This code is contributed by Nidhi_Biet", "e": 30396, "s": 29396, "text": null }, { "code": "<script>// Javascript code to count of pairs// of elements in an array// whose sum is prime // Function to check whether a// number is prime or notfunction isPrime(num){ if (num == 0 || num == 1) { return false; } for (let i = 2; i * i <= num; i++) { if (num % i == 0) { return false; } } return true;} // Function to count total number of pairs// of elements whose sum is primefunction numPairsWithPrimeSum(arr, n){ let count = 0; for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { let sum = arr[i] + arr[j]; if (isPrime(sum)) { count++; } } } return count;} // Driver Code let arr = [ 1, 2, 3, 4, 5 ];let n = arr.length;document.write(numPairsWithPrimeSum(arr, n)); // This code is contributed by _saurabh_jaiswal</script>", "e": 31255, "s": 30396, "text": null }, { "code": null, "e": 31257, "s": 31255, "text": "5" }, { "code": null, "e": 31277, "s": 31259, "text": "Time Complexity: " }, { "code": null, "e": 31437, "s": 31279, "text": "Efficient Approach: Precompute and store the primes by using Sieve of Eratosthenes. Now, for every pair of elements, check whether their sum is prime or not." }, { "code": null, "e": 31495, "s": 31439, "text": "Below code is the implementation of the above approach:" }, { "code": null, "e": 31501, "s": 31497, "text": "C++" }, { "code": null, "e": 31506, "s": 31501, "text": "Java" }, { "code": null, "e": 31514, "s": 31506, "text": "Python3" }, { "code": null, "e": 31517, "s": 31514, "text": "C#" }, { "code": null, "e": 31528, "s": 31517, "text": "Javascript" }, { "code": "// C++ code to find number of pairs// of elements in an array whose// sum is prime#include <bits/stdc++.h>using namespace std; // Function for Sieve Of Eratosthenesbool* sieveOfEratosthenes(int N){ bool* isPrime = new bool[N + 1]; for (int i = 0; i < N + 1; i++) { isPrime[i] = true; } isPrime[0] = false; isPrime[1] = false; for (int i = 2; i * i <= N; i++) { if (isPrime[i] == true) { int j = 2; while (i * j <= N) { isPrime[i * j] = false; j++; } } } return isPrime;} // Function to count total number of pairs// of elements whose sum is primeint numPairsWithPrimeSum(int* arr, int n){ int N = 2 * 1000000; bool* isPrime = sieveOfEratosthenes(N); int count = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int sum = arr[i] + arr[j]; if (isPrime[sum]) { count++; } } } return count;} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << numPairsWithPrimeSum(arr, n); return 0;}", "e": 32678, "s": 31528, "text": null }, { "code": "// Java code to find number of pairs of// elements in an array whose sum is primeimport java.io.*;import java.util.*; class GFG { // Function for Sieve Of Eratosthenes public static boolean[] sieveOfEratosthenes(int N) { boolean[] isPrime = new boolean[N + 1]; for (int i = 0; i < N + 1; i++) { isPrime[i] = true; } isPrime[0] = false; isPrime[1] = false; for (int i = 2; i * i <= N; i++) { if (isPrime[i] == true) { int j = 2; while (i * j <= N) { isPrime[i * j] = false; j++; } } } return isPrime; } // Function to count total number of pairs // of elements whose sum is prime public static int numPairsWithPrimeSum( int[] arr, int n) { int N = 2 * 1000000; boolean[] isPrime = sieveOfEratosthenes(N); int count = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int sum = arr[i] + arr[j]; if (isPrime[sum]) { count++; } } } return count; } // Driver code public static void main(String[] args) { int[] arr = { 1, 2, 3, 4, 5 }; int n = arr.length; System.out.println( numPairsWithPrimeSum(arr, n)); }}", "e": 34080, "s": 32678, "text": null }, { "code": "# Python3 code to find number of pairs of# elements in an array whose sum is prime # Function for Sieve Of Eratosthenesdef sieveOfEratosthenes(N): isPrime = [True for i in range(N + 1)] isPrime[0] = False isPrime[1] = False i = 2 while((i * i) <= N): if (isPrime[i]): j = 2 while (i * j <= N): isPrime[i * j] = False j += 1 i += 1 return isPrime # Function to count total number of pairs# of elements whose sum is primedef numPairsWithPrimeSum(arr, n): N = 2 * 1000000 isPrime = sieveOfEratosthenes(N) count = 0 for i in range(n): for j in range(i + 1, n): sum = arr[i] + arr[j] if (isPrime[sum]): count += 1 return count # Driver code if __name__==\"__main__\": arr = [ 1, 2, 3, 4, 5 ] n = len(arr) print(numPairsWithPrimeSum(arr, n)) # This code is contributed by rutvik_56", "e": 35108, "s": 34080, "text": null }, { "code": "// C# code to find number of pairs of// elements in an array whose sum is primeusing System; class GFG{ // Function for Sieve Of Eratosthenespublic static bool[] sieveOfEratosthenes(int N){ bool[] isPrime = new bool[N + 1]; for (int i = 0; i < N + 1; i++) { isPrime[i] = true; } isPrime[0] = false; isPrime[1] = false; for (int i = 2; i * i <= N; i++) { if (isPrime[i] == true) { int j = 2; while (i * j <= N) { isPrime[i * j] = false; j++; } } } return isPrime;} // Function to count total number of pairs// of elements whose sum is primepublic static int numPairsWithPrimeSum(int[] arr, int n){ int N = 2 * 1000000; bool[] isPrime = sieveOfEratosthenes(N); int count = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int sum = arr[i] + arr[j]; if (isPrime[sum]) { count++; } } } return count;} // Driver codepublic static void Main(String[] args){ int[] arr = { 1, 2, 3, 4, 5 }; int n = arr.Length; Console.WriteLine(numPairsWithPrimeSum(arr, n));}} // This code is contributed by 29AjayKumar", "e": 36406, "s": 35108, "text": null }, { "code": "<script> // JavaScript code to find number of pairs of// elements in an array whose sum is prime // Function for Sieve Of Eratosthenes function sieveOfEratosthenes(N) { let isPrime = Array.from({length: N+1}, (_, i) => 0); for (let i = 0; i < N + 1; i++) { isPrime[i] = true; } isPrime[0] = false; isPrime[1] = false; for (let i = 2; i * i <= N; i++) { if (isPrime[i] == true) { let j = 2; while (i * j <= N) { isPrime[i * j] = false; j++; } } } return isPrime; } // Function to count total number of pairs // of elements whose sum is prime function numPairsWithPrimeSum( arr, n) { let N = 2 * 1000000; let isPrime = sieveOfEratosthenes(N); let count = 0; for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { let sum = arr[i] + arr[j]; if (isPrime[sum]) { count++; } } } return count; } // Driver Code let arr = [ 1, 2, 3, 4, 5 ]; let n = arr.length; document.write( numPairsWithPrimeSum(arr, n) ); </script>", "e": 37749, "s": 36406, "text": null }, { "code": null, "e": 37751, "s": 37749, "text": "5" }, { "code": null, "e": 37778, "s": 37753, "text": "Time complexity: O(N^2) " }, { "code": null, "e": 37790, "s": 37778, "text": "29AjayKumar" }, { "code": null, "e": 37801, "s": 37790, "text": "nidhi_biet" }, { "code": null, "e": 37814, "s": 37801, "text": "grand_master" }, { "code": null, "e": 37824, "s": 37814, "text": "rutvik_56" }, { "code": null, "e": 37834, "s": 37824, "text": "code_hunt" }, { "code": null, "e": 37851, "s": 37834, "text": "_saurabh_jaiswal" }, { "code": null, "e": 37864, "s": 37851, "text": "Prime Number" }, { "code": null, "e": 37870, "s": 37864, "text": "sieve" }, { "code": null, "e": 37877, "s": 37870, "text": "Arrays" }, { "code": null, "e": 37901, "s": 37877, "text": "Competitive Programming" }, { "code": null, "e": 37914, "s": 37901, "text": "Mathematical" }, { "code": null, "e": 37921, "s": 37914, "text": "Arrays" }, { "code": null, "e": 37934, "s": 37921, "text": "Mathematical" }, { "code": null, "e": 37947, "s": 37934, "text": "Prime Number" }, { "code": null, "e": 37953, "s": 37947, "text": "sieve" }, { "code": null, "e": 38051, "s": 37953, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38082, "s": 38051, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 38109, "s": 38082, "text": "Count pairs with given sum" }, { "code": null, "e": 38134, "s": 38109, "text": "Window Sliding Technique" }, { "code": null, "e": 38172, "s": 38134, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 38193, "s": 38172, "text": "Next Greater Element" }, { "code": null, "e": 38236, "s": 38193, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 38279, "s": 38236, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 38320, "s": 38279, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 38398, "s": 38320, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" } ]
Simple Input/Output Program in MATLAB - GeeksforGeeks
20 Aug, 2020 Let us see how to input and output data in MATLAB. Syntax : input(PROMPT, “s”) Parameters : PROMPT : text prompted “s” : optional, to input a string Returns : the data entered The input() function is used to input data in MATLAB.Example : % entering an integerinput("Enter an integer : ") % entering a stringinput("Enter a string : ", "s") Output : Enter an integer : 10 ans = 10 Enter a string : GeeksforGeeks ans = GeeksforGeeks Syntax : display(OBJ) Parameters : OBJ : the object to be displayed Returns : Nothing The display() function is used to output data in MATLAB. Example : % output a stringdisplay("GeeksforGeeks") % output a variablevar = 10;display(var) Output : GeeksforGeeks var = 10 MATLAB Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Copying Files to and from Docker Containers Markov Decision Process Fuzzy Logic | Introduction Q-Learning in Python Principal Component Analysis with Python Basics of API Testing Using Postman ML | What is Machine Learning ? OpenCV - Overview Deep Learning | Introduction to Long Short Term Memory Getting Started with System Design
[ { "code": null, "e": 25493, "s": 25465, "text": "\n20 Aug, 2020" }, { "code": null, "e": 25544, "s": 25493, "text": "Let us see how to input and output data in MATLAB." }, { "code": null, "e": 25572, "s": 25544, "text": "Syntax : input(PROMPT, “s”)" }, { "code": null, "e": 25585, "s": 25572, "text": "Parameters :" }, { "code": null, "e": 25608, "s": 25585, "text": "PROMPT : text prompted" }, { "code": null, "e": 25642, "s": 25608, "text": "“s” : optional, to input a string" }, { "code": null, "e": 25669, "s": 25642, "text": "Returns : the data entered" }, { "code": null, "e": 25732, "s": 25669, "text": "The input() function is used to input data in MATLAB.Example :" }, { "code": "% entering an integerinput(\"Enter an integer : \") % entering a stringinput(\"Enter a string : \", \"s\")", "e": 25834, "s": 25732, "text": null }, { "code": null, "e": 25843, "s": 25834, "text": "Output :" }, { "code": null, "e": 25927, "s": 25843, "text": "Enter an integer : 10\nans = 10\nEnter a string : GeeksforGeeks\nans = GeeksforGeeks\n" }, { "code": null, "e": 25949, "s": 25927, "text": "Syntax : display(OBJ)" }, { "code": null, "e": 25962, "s": 25949, "text": "Parameters :" }, { "code": null, "e": 25995, "s": 25962, "text": "OBJ : the object to be displayed" }, { "code": null, "e": 26013, "s": 25995, "text": "Returns : Nothing" }, { "code": null, "e": 26070, "s": 26013, "text": "The display() function is used to output data in MATLAB." }, { "code": null, "e": 26080, "s": 26070, "text": "Example :" }, { "code": "% output a stringdisplay(\"GeeksforGeeks\") % output a variablevar = 10;display(var)", "e": 26164, "s": 26080, "text": null }, { "code": null, "e": 26173, "s": 26164, "text": "Output :" }, { "code": null, "e": 26198, "s": 26173, "text": "GeeksforGeeks\nvar = 10\n" }, { "code": null, "e": 26205, "s": 26198, "text": "MATLAB" }, { "code": null, "e": 26231, "s": 26205, "text": "Advanced Computer Subject" }, { "code": null, "e": 26329, "s": 26231, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26373, "s": 26329, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 26397, "s": 26373, "text": "Markov Decision Process" }, { "code": null, "e": 26424, "s": 26397, "text": "Fuzzy Logic | Introduction" }, { "code": null, "e": 26445, "s": 26424, "text": "Q-Learning in Python" }, { "code": null, "e": 26486, "s": 26445, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 26522, "s": 26486, "text": "Basics of API Testing Using Postman" }, { "code": null, "e": 26554, "s": 26522, "text": "ML | What is Machine Learning ?" }, { "code": null, "e": 26572, "s": 26554, "text": "OpenCV - Overview" }, { "code": null, "e": 26627, "s": 26572, "text": "Deep Learning | Introduction to Long Short Term Memory" } ]
Sort an array according to count of set bits | Set 2 - GeeksforGeeks
26 Nov, 2021 Given an array arr[] of positive integers, the task is to sort the array in decreasing order of count of set bits in binary representations of array elements. For integers having same number of set bits in their binary representation, sort according to their position in the original array i.e., a stable sort. For example, if input array is {3, 5}, then output array should also be {3, 5}. Note that both 3 and 5 have same number set bits.Examples: Input: arr[] = {5, 2, 3, 9, 4, 6, 7, 15, 32} Output: 15 7 5 3 9 6 2 4 32 The integers in their binary representation are: 15 – 1111 7 – 0111 5 – 0101 3 – 0011 9 – 1001 6 – 0110 2 – 0010 4 – 0100 32 – 10000 Hence, the non-increasing sorted order is: {15, 7, 5, 3, 9, 6, 2, 4, 32}Input: arr[] = {1, 2, 3, 4, 5, 6}; Output: 3 5 6 1 2 4 Approach: We have already discussed the method of sorting based on set bit count in the previous section with various methods. This post contains implementation using maps. As we know that a map/multimap stores data in sorted manner. So if we store (32 – countsetbits(arr[i])) for an arr[i] in map, then the output will come out in decreasing order of set bit count which is the desired output.Below is the implementation of the above approach: C++ Python3 Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // function to sort the array according// to the number of set bits in elementsvoid sortArr(int arr[], int n){ multimap<int, int> map; for (int i = 0; i < n; i++) { int count = 0; int k = arr[i]; // Counting no of setBits in arr[i] while (k) { k = k & k - 1; count++; } // The count is subtracted from 32 // because the result needs // to be in descending order map.insert(make_pair(32 - count, arr[i])); } // Printing the numbers in descending // order of set bit count for (auto it = map.begin(); it != map.end(); it++) { cout << (*it).second << " "; }} // Driver codeint main(){ int arr[] = { 5, 2, 3, 9, 4, 6, 7, 15, 32 }; int n = sizeof(arr) / sizeof(arr[0]); sortArr(arr, n); return 0;} # Python3 implementation of the approach # function to sort the array according# to the number of set bits in elementsdef sortArr(arr, n): mp = [] for i in range( n): count = 0 k = arr[i] # Counting no of setBits in arr[i] while (k): k = k & k - 1 count += 1 # The count is subtracted from 32 # because the result needs # to be in descending order mp.append((32 - count, arr[i])) # Printing the numbers in descending # order of set bit count mp.sort(key = lambda x: x[0]) for it in mp: print(it[1], end= " ") # Driver codeif __name__ == "__main__": arr = [ 5, 2, 3, 9, 4, 6, 7, 15, 32 ] n = len(arr) sortArr(arr, n) # This code is contributed by chitranayal <script> // JavaScript implementation of the approach // function to sort the array according// to the number of set bits in elementsfunction sortArr(arr,n){ let map=[]; for (let i = 0; i < n; i++) { let count = 0; let k = arr[i]; // Counting no of setBits in arr[i] while (k) { k = k & k - 1; count++; } // The count is subtracted from 32 // because the result needs // to be in descending order map.push([32 - count, arr[i]]); } map.sort(function(a,b){return a[0]-b[0];}); // Printing the numbers in descending // order of set bit count for (let i=0;i<map.length;i++) { document.write(map[i][1]+" "); }} // Driver codelet arr=[5, 2, 3, 9, 4, 6, 7, 15, 32 ];let n=arr.length;sortArr(arr, n); // This code is contributed by avanitrachhadiya2155 </script> 15 7 5 3 9 6 2 4 32 Time Complexity: O(n * log n) Auxiliary Space: O(n) ukasp avanitrachhadiya2155 subhammahato348 setBitCount Arrays Bit Magic Sorting Arrays Bit Magic Sorting 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 Introduction to Arrays Multidimensional Arrays in Java Linear Search Linked List vs Array Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Count set bits in an integer How to swap two numbers without using a temporary variable?
[ { "code": null, "e": 26583, "s": 26555, "text": "\n26 Nov, 2021" }, { "code": null, "e": 27035, "s": 26583, "text": "Given an array arr[] of positive integers, the task is to sort the array in decreasing order of count of set bits in binary representations of array elements. For integers having same number of set bits in their binary representation, sort according to their position in the original array i.e., a stable sort. For example, if input array is {3, 5}, then output array should also be {3, 5}. Note that both 3 and 5 have same number set bits.Examples: " }, { "code": null, "e": 27370, "s": 27035, "text": "Input: arr[] = {5, 2, 3, 9, 4, 6, 7, 15, 32} Output: 15 7 5 3 9 6 2 4 32 The integers in their binary representation are: 15 – 1111 7 – 0111 5 – 0101 3 – 0011 9 – 1001 6 – 0110 2 – 0010 4 – 0100 32 – 10000 Hence, the non-increasing sorted order is: {15, 7, 5, 3, 9, 6, 2, 4, 32}Input: arr[] = {1, 2, 3, 4, 5, 6}; Output: 3 5 6 1 2 4 " }, { "code": null, "e": 27819, "s": 27372, "text": "Approach: We have already discussed the method of sorting based on set bit count in the previous section with various methods. This post contains implementation using maps. As we know that a map/multimap stores data in sorted manner. So if we store (32 – countsetbits(arr[i])) for an arr[i] in map, then the output will come out in decreasing order of set bit count which is the desired output.Below is the implementation of the above approach: " }, { "code": null, "e": 27823, "s": 27819, "text": "C++" }, { "code": null, "e": 27831, "s": 27823, "text": "Python3" }, { "code": null, "e": 27842, "s": 27831, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // function to sort the array according// to the number of set bits in elementsvoid sortArr(int arr[], int n){ multimap<int, int> map; for (int i = 0; i < n; i++) { int count = 0; int k = arr[i]; // Counting no of setBits in arr[i] while (k) { k = k & k - 1; count++; } // The count is subtracted from 32 // because the result needs // to be in descending order map.insert(make_pair(32 - count, arr[i])); } // Printing the numbers in descending // order of set bit count for (auto it = map.begin(); it != map.end(); it++) { cout << (*it).second << \" \"; }} // Driver codeint main(){ int arr[] = { 5, 2, 3, 9, 4, 6, 7, 15, 32 }; int n = sizeof(arr) / sizeof(arr[0]); sortArr(arr, n); return 0;}", "e": 28748, "s": 27842, "text": null }, { "code": "# Python3 implementation of the approach # function to sort the array according# to the number of set bits in elementsdef sortArr(arr, n): mp = [] for i in range( n): count = 0 k = arr[i] # Counting no of setBits in arr[i] while (k): k = k & k - 1 count += 1 # The count is subtracted from 32 # because the result needs # to be in descending order mp.append((32 - count, arr[i])) # Printing the numbers in descending # order of set bit count mp.sort(key = lambda x: x[0]) for it in mp: print(it[1], end= \" \") # Driver codeif __name__ == \"__main__\": arr = [ 5, 2, 3, 9, 4, 6, 7, 15, 32 ] n = len(arr) sortArr(arr, n) # This code is contributed by chitranayal", "e": 29537, "s": 28748, "text": null }, { "code": "<script> // JavaScript implementation of the approach // function to sort the array according// to the number of set bits in elementsfunction sortArr(arr,n){ let map=[]; for (let i = 0; i < n; i++) { let count = 0; let k = arr[i]; // Counting no of setBits in arr[i] while (k) { k = k & k - 1; count++; } // The count is subtracted from 32 // because the result needs // to be in descending order map.push([32 - count, arr[i]]); } map.sort(function(a,b){return a[0]-b[0];}); // Printing the numbers in descending // order of set bit count for (let i=0;i<map.length;i++) { document.write(map[i][1]+\" \"); }} // Driver codelet arr=[5, 2, 3, 9, 4, 6, 7, 15, 32 ];let n=arr.length;sortArr(arr, n); // This code is contributed by avanitrachhadiya2155 </script>", "e": 30422, "s": 29537, "text": null }, { "code": null, "e": 30442, "s": 30422, "text": "15 7 5 3 9 6 2 4 32" }, { "code": null, "e": 30474, "s": 30444, "text": "Time Complexity: O(n * log n)" }, { "code": null, "e": 30496, "s": 30474, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 30502, "s": 30496, "text": "ukasp" }, { "code": null, "e": 30523, "s": 30502, "text": "avanitrachhadiya2155" }, { "code": null, "e": 30539, "s": 30523, "text": "subhammahato348" }, { "code": null, "e": 30551, "s": 30539, "text": "setBitCount" }, { "code": null, "e": 30558, "s": 30551, "text": "Arrays" }, { "code": null, "e": 30568, "s": 30558, "text": "Bit Magic" }, { "code": null, "e": 30576, "s": 30568, "text": "Sorting" }, { "code": null, "e": 30583, "s": 30576, "text": "Arrays" }, { "code": null, "e": 30593, "s": 30583, "text": "Bit Magic" }, { "code": null, "e": 30601, "s": 30593, "text": "Sorting" }, { "code": null, "e": 30699, "s": 30601, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30767, "s": 30699, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 30790, "s": 30767, "text": "Introduction to Arrays" }, { "code": null, "e": 30822, "s": 30790, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 30836, "s": 30822, "text": "Linear Search" }, { "code": null, "e": 30857, "s": 30836, "text": "Linked List vs Array" }, { "code": null, "e": 30884, "s": 30857, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 30930, "s": 30884, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 30998, "s": 30930, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 31027, "s": 30998, "text": "Count set bits in an integer" } ]
Reverse a Doubly Linked List | Set-2 - GeeksforGeeks
08 Feb, 2022 Write a program to reverse the given Doubly Linked List. See below diagrams for example. (a) Original Doubly Linked List (b) Reversed Doubly Linked List Approach: In the previous post, doubly linked list is being reversed by swapping prev and next pointers for all nodes, changing prev of the head (or start) and then changing the head pointer in the end. In this post, we create a push function that adds the given node at the beginning of the given list. We traverse the original list and one by one pass the current node pointer to the push function. This process will reverse the list. Finally return the new head of this reversed list. C++ Java Python3 C# Javascript // C++ implementation to reverse// a doubly linked list#include <bits/stdc++.h> using namespace std; // a node of the doubly linked liststruct Node { int data; Node *next, *prev;}; // function to get a new nodeNode* getNode(int data){ // allocate space Node* new_node = (Node*)malloc(sizeof(Node)); // put in the data new_node->data = data; new_node->next = new_node->prev = NULL; return new_node;} // function to insert a node at the beginning// of the Doubly Linked Listvoid push(Node** head_ref, Node* new_node){ // since we are adding at the beginning, // prev is always NULL new_node->prev = NULL; // link the old list off the new node new_node->next = (*head_ref); // change prev of head node to new node if ((*head_ref) != NULL) (*head_ref)->prev = new_node; // move the head to point to the new node (*head_ref) = new_node;} // function to reverse a doubly linked listvoid reverseList(Node** head_ref){ // if list is empty or it contains // a single node only if (!(*head_ref) || !((*head_ref)->next)) return; Node* new_head = NULL; Node *curr = *head_ref, *next; while (curr != NULL) { // get pointer to next node next = curr->next; // push 'curr' node at the beginning of the // list with starting with 'new_head' push(&new_head, curr); // update 'curr' curr = next; } // update 'head_ref' *head_ref = new_head;} // Function to print nodes in a// given doubly linked listvoid printList(Node* head){ while (head != NULL) { cout << head->data << " "; head = head->next; }} // Driver program to test aboveint main(){ // Start with the empty list Node* head = NULL; // Create doubly linked: 10<->8<->4<->2 */ push(&head, getNode(2)); push(&head, getNode(4)); push(&head, getNode(8)); push(&head, getNode(10)); cout << "Original list: "; printList(head); // Reverse doubly linked list reverseList(&head); cout << "\nReversed list: "; printList(head); return 0;} // Java implementation to reverse// a doubly linked listclass GFG{ // a node of the doubly linked liststatic class Node{ int data; Node next, prev;}; // function to get a new nodestatic Node getNode(int data){ // allocate space Node new_node = new Node(); // put in the data new_node.data = data; new_node.next = new_node.prev = null; return new_node;} // function to insert a node at the beginning// of the Doubly Linked Liststatic Node push(Node head_ref, Node new_node){ // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = (head_ref); // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref;} // function to reverse a doubly linked liststatic Node reverseList(Node head_ref){ // if list is empty or it contains // a single node only if ((head_ref) == null || ((head_ref).next) == null) return null; Node new_head = null; Node curr = head_ref, next; while (curr != null) { // get pointer to next node next = curr.next; // push 'curr' node at the beginning of the // list with starting with 'new_head' new_head = push(new_head, curr); // update 'curr' curr = next; } // update 'head_ref' head_ref = new_head; return head_ref;} // Function to print nodes in a// given doubly linked liststatic void printList(Node head){ while (head != null) { System.out.print(head.data + " "); head = head.next; }} // Driver program to test abovepublic static void main(String args[]){ // Start with the empty list Node head = null; // Create doubly linked: 10< - >8< - >4< - >2 / head = push(head, getNode(2)); head = push(head, getNode(4)); head = push(head, getNode(8)); head = push(head, getNode(10)); System.out.print("Original list: "); printList(head); // Reverse doubly linked list head = reverseList(head); System.out.print("\nReversed list: "); printList(head);}} // This code is contributed by Arnab Kundu # Python3 implementation to reverse# a doubly linked listimport math # a node of the doubly linked listclass Node: def __init__(self, data): self.data = data self.next = None # function to get a new nodedef getNode(data): # allocate space new_node = Node(data) # put in the data new_node.data = data new_node.next = None new_node.prev = None return new_node # function to insert a node at the beginning# of the Doubly Linked Listdef push(head_ref, new_node): # since we are adding at the beginning, # prev is always None new_node.prev = None # link the old list off the new node new_node.next = head_ref # change prev of head node to new node if (head_ref != None): head_ref.prev = new_node # move the head to point to the new node head_ref = new_node return head_ref # function to reverse a doubly linked listdef reverseList(head_ref): # if list is empty or it contains # a single node only if (head_ref == None or (head_ref).next == None): return None new_head = None curr = head_ref while (curr != None): # get pointer to next node next = curr.next # push 'curr' node at the beginning of the # list with starting with 'new_head' new_head = push(new_head, curr) # update 'curr' curr = next # update 'head_ref' head_ref = new_head return head_ref # Function to print nodes in a# given doubly linked listdef printList(head): while (head != None) : print(head.data, end = " ") head = head.next # Driver Codeif __name__=='__main__': # Start with the empty list head = None # Create doubly linked: 10<.8<.4<.2 */ head = push(head, getNode(2)); head = push(head, getNode(4)); head = push(head, getNode(8)); head = push(head, getNode(10)); print("Original list: ", end = "") printList(head) # Reverse doubly linked list head = reverseList(head) print("\nReversed list: ", end = "") printList(head) # This code is contributed by Srathore // C# implementation to reverse// a doubly linked listusing System; class GFG{ // a node of the doubly linked listpublic class Node{ public int data; public Node next, prev;}; // function to get a new nodestatic Node getNode(int data){ // allocate space Node new_node = new Node(); // put in the data new_node.data = data; new_node.next = new_node.prev = null; return new_node;} // function to insert a node at the beginning// of the Doubly Linked Liststatic Node push(Node head_ref, Node new_node){ // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = (head_ref); // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref;} // function to reverse a doubly linked liststatic Node reverseList(Node head_ref){ // if list is empty or it contains // a single node only if ((head_ref) == null || ((head_ref).next) == null) return null; Node new_head = null; Node curr = head_ref, next; while (curr != null) { // get pointer to next node next = curr.next; // push 'curr' node at the beginning of the // list with starting with 'new_head' new_head = push(new_head, curr); // update 'curr' curr = next; } // update 'head_ref' head_ref = new_head; return head_ref;} // Function to print nodes in a// given doubly linked liststatic void printList(Node head){ while (head != null) { Console.Write(head.data + " "); head = head.next; }} // Driver codepublic static void Main(String []args){ // Start with the empty list Node head = null; // Create doubly linked: 10< - >8< - >4< - >2 / head = push(head, getNode(2)); head = push(head, getNode(4)); head = push(head, getNode(8)); head = push(head, getNode(10)); Console.Write("Original list: "); printList(head); // Reverse doubly linked list head = reverseList(head); Console.Write("\nReversed list: "); printList(head);}} // This code has been contributed by 29AjayKumar <script>// javascript implementation to reverse// a doubly linked list // a node of the doubly linked listclass Node { constructor() { this.data = 0; this.prev = null; this.next = null; }} // function to get a new node function getNode(data) { // allocate spacevar new_node = new Node(); // put in the data new_node.data = data; new_node.next = new_node.prev = null; return new_node; } // function to insert a node at the beginning // of the Doubly Linked List function push(head_ref, new_node) { // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = (head_ref); // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref; } // function to reverse a doubly linked list function reverseList(head_ref) { // if list is empty or it contains // a single node only if ((head_ref) == null || ((head_ref).next) == null) return null; var new_head = null;var curr = head_ref, next; while (curr != null) { // get pointer to next node next = curr.next; // push 'curr' node at the beginning of the // list with starting with 'new_head' new_head = push(new_head, curr); // update 'curr' curr = next; } // update 'head_ref' head_ref = new_head; return head_ref; } // Function to print nodes in a // given doubly linked list function printList(head) { while (head != null) { document.write(head.data + " "); head = head.next; } } // Driver program to test above // Start with the empty listvar head = null; // Create doubly linked: 10< - >8< - >4< - >2 / head = push(head, getNode(2)); head = push(head, getNode(4)); head = push(head, getNode(8)); head = push(head, getNode(10)); document.write("Original list: "); printList(head); // Reverse doubly linked list head = reverseList(head); document.write("<br/>Reversed list: "); printList(head); // This code contributed by Rajput-Ji</script> Output: Original list: 10 8 4 2 Reversed list: 2 4 8 10 Time Complexity: O(n). andrew1234 29AjayKumar nidhi_biet sapnasingh4991 Rajput-Ji simranarora5sos sweetyty surindertarika1234 simmytarika5 doubly linked list Reverse Linked List Linked List Reverse Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. LinkedList in Java Linked List vs Array Doubly Linked List | Set 1 (Introduction and Insertion) Merge two sorted linked lists Detect loop in a linked list Find the middle of a given linked list Implement a stack using singly linked list Queue - Linked List Implementation Implementing a Linked List in Java using Class Circular Linked List | Set 1 (Introduction and Applications)
[ { "code": null, "e": 25823, "s": 25795, "text": "\n08 Feb, 2022" }, { "code": null, "e": 25880, "s": 25823, "text": "Write a program to reverse the given Doubly Linked List." }, { "code": null, "e": 25912, "s": 25880, "text": "See below diagrams for example." }, { "code": null, "e": 25956, "s": 25912, "text": " (a) Original Doubly Linked List " }, { "code": null, "e": 26000, "s": 25956, "text": " (b) Reversed Doubly Linked List " }, { "code": null, "e": 26488, "s": 26000, "text": "Approach: In the previous post, doubly linked list is being reversed by swapping prev and next pointers for all nodes, changing prev of the head (or start) and then changing the head pointer in the end. In this post, we create a push function that adds the given node at the beginning of the given list. We traverse the original list and one by one pass the current node pointer to the push function. This process will reverse the list. Finally return the new head of this reversed list." }, { "code": null, "e": 26492, "s": 26488, "text": "C++" }, { "code": null, "e": 26497, "s": 26492, "text": "Java" }, { "code": null, "e": 26505, "s": 26497, "text": "Python3" }, { "code": null, "e": 26508, "s": 26505, "text": "C#" }, { "code": null, "e": 26519, "s": 26508, "text": "Javascript" }, { "code": "// C++ implementation to reverse// a doubly linked list#include <bits/stdc++.h> using namespace std; // a node of the doubly linked liststruct Node { int data; Node *next, *prev;}; // function to get a new nodeNode* getNode(int data){ // allocate space Node* new_node = (Node*)malloc(sizeof(Node)); // put in the data new_node->data = data; new_node->next = new_node->prev = NULL; return new_node;} // function to insert a node at the beginning// of the Doubly Linked Listvoid push(Node** head_ref, Node* new_node){ // since we are adding at the beginning, // prev is always NULL new_node->prev = NULL; // link the old list off the new node new_node->next = (*head_ref); // change prev of head node to new node if ((*head_ref) != NULL) (*head_ref)->prev = new_node; // move the head to point to the new node (*head_ref) = new_node;} // function to reverse a doubly linked listvoid reverseList(Node** head_ref){ // if list is empty or it contains // a single node only if (!(*head_ref) || !((*head_ref)->next)) return; Node* new_head = NULL; Node *curr = *head_ref, *next; while (curr != NULL) { // get pointer to next node next = curr->next; // push 'curr' node at the beginning of the // list with starting with 'new_head' push(&new_head, curr); // update 'curr' curr = next; } // update 'head_ref' *head_ref = new_head;} // Function to print nodes in a// given doubly linked listvoid printList(Node* head){ while (head != NULL) { cout << head->data << \" \"; head = head->next; }} // Driver program to test aboveint main(){ // Start with the empty list Node* head = NULL; // Create doubly linked: 10<->8<->4<->2 */ push(&head, getNode(2)); push(&head, getNode(4)); push(&head, getNode(8)); push(&head, getNode(10)); cout << \"Original list: \"; printList(head); // Reverse doubly linked list reverseList(&head); cout << \"\\nReversed list: \"; printList(head); return 0;}", "e": 28604, "s": 26519, "text": null }, { "code": "// Java implementation to reverse// a doubly linked listclass GFG{ // a node of the doubly linked liststatic class Node{ int data; Node next, prev;}; // function to get a new nodestatic Node getNode(int data){ // allocate space Node new_node = new Node(); // put in the data new_node.data = data; new_node.next = new_node.prev = null; return new_node;} // function to insert a node at the beginning// of the Doubly Linked Liststatic Node push(Node head_ref, Node new_node){ // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = (head_ref); // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref;} // function to reverse a doubly linked liststatic Node reverseList(Node head_ref){ // if list is empty or it contains // a single node only if ((head_ref) == null || ((head_ref).next) == null) return null; Node new_head = null; Node curr = head_ref, next; while (curr != null) { // get pointer to next node next = curr.next; // push 'curr' node at the beginning of the // list with starting with 'new_head' new_head = push(new_head, curr); // update 'curr' curr = next; } // update 'head_ref' head_ref = new_head; return head_ref;} // Function to print nodes in a// given doubly linked liststatic void printList(Node head){ while (head != null) { System.out.print(head.data + \" \"); head = head.next; }} // Driver program to test abovepublic static void main(String args[]){ // Start with the empty list Node head = null; // Create doubly linked: 10< - >8< - >4< - >2 / head = push(head, getNode(2)); head = push(head, getNode(4)); head = push(head, getNode(8)); head = push(head, getNode(10)); System.out.print(\"Original list: \"); printList(head); // Reverse doubly linked list head = reverseList(head); System.out.print(\"\\nReversed list: \"); printList(head);}} // This code is contributed by Arnab Kundu", "e": 30846, "s": 28604, "text": null }, { "code": "# Python3 implementation to reverse# a doubly linked listimport math # a node of the doubly linked listclass Node: def __init__(self, data): self.data = data self.next = None # function to get a new nodedef getNode(data): # allocate space new_node = Node(data) # put in the data new_node.data = data new_node.next = None new_node.prev = None return new_node # function to insert a node at the beginning# of the Doubly Linked Listdef push(head_ref, new_node): # since we are adding at the beginning, # prev is always None new_node.prev = None # link the old list off the new node new_node.next = head_ref # change prev of head node to new node if (head_ref != None): head_ref.prev = new_node # move the head to point to the new node head_ref = new_node return head_ref # function to reverse a doubly linked listdef reverseList(head_ref): # if list is empty or it contains # a single node only if (head_ref == None or (head_ref).next == None): return None new_head = None curr = head_ref while (curr != None): # get pointer to next node next = curr.next # push 'curr' node at the beginning of the # list with starting with 'new_head' new_head = push(new_head, curr) # update 'curr' curr = next # update 'head_ref' head_ref = new_head return head_ref # Function to print nodes in a# given doubly linked listdef printList(head): while (head != None) : print(head.data, end = \" \") head = head.next # Driver Codeif __name__=='__main__': # Start with the empty list head = None # Create doubly linked: 10<.8<.4<.2 */ head = push(head, getNode(2)); head = push(head, getNode(4)); head = push(head, getNode(8)); head = push(head, getNode(10)); print(\"Original list: \", end = \"\") printList(head) # Reverse doubly linked list head = reverseList(head) print(\"\\nReversed list: \", end = \"\") printList(head) # This code is contributed by Srathore", "e": 32938, "s": 30846, "text": null }, { "code": "// C# implementation to reverse// a doubly linked listusing System; class GFG{ // a node of the doubly linked listpublic class Node{ public int data; public Node next, prev;}; // function to get a new nodestatic Node getNode(int data){ // allocate space Node new_node = new Node(); // put in the data new_node.data = data; new_node.next = new_node.prev = null; return new_node;} // function to insert a node at the beginning// of the Doubly Linked Liststatic Node push(Node head_ref, Node new_node){ // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = (head_ref); // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref;} // function to reverse a doubly linked liststatic Node reverseList(Node head_ref){ // if list is empty or it contains // a single node only if ((head_ref) == null || ((head_ref).next) == null) return null; Node new_head = null; Node curr = head_ref, next; while (curr != null) { // get pointer to next node next = curr.next; // push 'curr' node at the beginning of the // list with starting with 'new_head' new_head = push(new_head, curr); // update 'curr' curr = next; } // update 'head_ref' head_ref = new_head; return head_ref;} // Function to print nodes in a// given doubly linked liststatic void printList(Node head){ while (head != null) { Console.Write(head.data + \" \"); head = head.next; }} // Driver codepublic static void Main(String []args){ // Start with the empty list Node head = null; // Create doubly linked: 10< - >8< - >4< - >2 / head = push(head, getNode(2)); head = push(head, getNode(4)); head = push(head, getNode(8)); head = push(head, getNode(10)); Console.Write(\"Original list: \"); printList(head); // Reverse doubly linked list head = reverseList(head); Console.Write(\"\\nReversed list: \"); printList(head);}} // This code has been contributed by 29AjayKumar", "e": 35186, "s": 32938, "text": null }, { "code": "<script>// javascript implementation to reverse// a doubly linked list // a node of the doubly linked listclass Node { constructor() { this.data = 0; this.prev = null; this.next = null; }} // function to get a new node function getNode(data) { // allocate spacevar new_node = new Node(); // put in the data new_node.data = data; new_node.next = new_node.prev = null; return new_node; } // function to insert a node at the beginning // of the Doubly Linked List function push(head_ref, new_node) { // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = (head_ref); // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref; } // function to reverse a doubly linked list function reverseList(head_ref) { // if list is empty or it contains // a single node only if ((head_ref) == null || ((head_ref).next) == null) return null; var new_head = null;var curr = head_ref, next; while (curr != null) { // get pointer to next node next = curr.next; // push 'curr' node at the beginning of the // list with starting with 'new_head' new_head = push(new_head, curr); // update 'curr' curr = next; } // update 'head_ref' head_ref = new_head; return head_ref; } // Function to print nodes in a // given doubly linked list function printList(head) { while (head != null) { document.write(head.data + \" \"); head = head.next; } } // Driver program to test above // Start with the empty listvar head = null; // Create doubly linked: 10< - >8< - >4< - >2 / head = push(head, getNode(2)); head = push(head, getNode(4)); head = push(head, getNode(8)); head = push(head, getNode(10)); document.write(\"Original list: \"); printList(head); // Reverse doubly linked list head = reverseList(head); document.write(\"<br/>Reversed list: \"); printList(head); // This code contributed by Rajput-Ji</script>", "e": 37643, "s": 35186, "text": null }, { "code": null, "e": 37652, "s": 37643, "text": "Output: " }, { "code": null, "e": 37700, "s": 37652, "text": "Original list: 10 8 4 2\nReversed list: 2 4 8 10" }, { "code": null, "e": 37724, "s": 37700, "text": "Time Complexity: O(n). " }, { "code": null, "e": 37735, "s": 37724, "text": "andrew1234" }, { "code": null, "e": 37747, "s": 37735, "text": "29AjayKumar" }, { "code": null, "e": 37758, "s": 37747, "text": "nidhi_biet" }, { "code": null, "e": 37773, "s": 37758, "text": "sapnasingh4991" }, { "code": null, "e": 37783, "s": 37773, "text": "Rajput-Ji" }, { "code": null, "e": 37799, "s": 37783, "text": "simranarora5sos" }, { "code": null, "e": 37808, "s": 37799, "text": "sweetyty" }, { "code": null, "e": 37827, "s": 37808, "text": "surindertarika1234" }, { "code": null, "e": 37840, "s": 37827, "text": "simmytarika5" }, { "code": null, "e": 37859, "s": 37840, "text": "doubly linked list" }, { "code": null, "e": 37867, "s": 37859, "text": "Reverse" }, { "code": null, "e": 37879, "s": 37867, "text": "Linked List" }, { "code": null, "e": 37891, "s": 37879, "text": "Linked List" }, { "code": null, "e": 37899, "s": 37891, "text": "Reverse" }, { "code": null, "e": 37997, "s": 37899, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38016, "s": 37997, "text": "LinkedList in Java" }, { "code": null, "e": 38037, "s": 38016, "text": "Linked List vs Array" }, { "code": null, "e": 38093, "s": 38037, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" }, { "code": null, "e": 38123, "s": 38093, "text": "Merge two sorted linked lists" }, { "code": null, "e": 38152, "s": 38123, "text": "Detect loop in a linked list" }, { "code": null, "e": 38191, "s": 38152, "text": "Find the middle of a given linked list" }, { "code": null, "e": 38234, "s": 38191, "text": "Implement a stack using singly linked list" }, { "code": null, "e": 38269, "s": 38234, "text": "Queue - Linked List Implementation" }, { "code": null, "e": 38316, "s": 38269, "text": "Implementing a Linked List in Java using Class" } ]
Python | Pandas dataframe.equals() - GeeksforGeeks
20 Nov, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.equals() function is used to determine if two dataframe object in consideration are equal or not. Unlike dataframe.eq() method, the result of the operation is a scalar boolean value indicating if the dataframe objects are equal or not. Syntax: DataFrame.equals(other) Parameters:other : DataFrame Returns: Scalar : boolean value Example #1: Use equals() function to find the result of comparison between two different dataframe objects. # importing pandas as pdimport pandas as pd # Creating the first dataframe df1 = pd.DataFrame({"A":[1,5,7,8], "B":[5,8,4,3], "C":[10,4,9,3]}) # Creating the second dataframedf2 = pd.DataFrame({"A":[5,3,6,4], "B":[11,2,4,3], "C":[4,3,8,5]}) # Print the first dataframedf1 # Print the second dataframedf2 Let’s find the result of comparison between both the data frames. # To find the comparison resultdf1.equals(df2) Output : The output is False because the two dataframes are not equal to each other. They have different elements. Example #2: Use equals() function to test for equality between two data frame object with NaN values.Note : NaNs in the same location are considered equal. # importing pandas as pdimport pandas as pd # Creating the first dataframedf1 = pd.DataFrame({"A":[1,2,3], "B":[4,5,None], "C":[7,8,9]}) # Creating the second dataframedf2 = pd.DataFrame({"A":[1,2,3], "B":[4,5,None], "C":[7,8,9]}) # Print the first dataframedf1 # Print the second dataframedf2 Let’s perform comparison operation on both the dataframes. # To find the comparison between two dataframesdf1.equals(df2) Output : The output scalar boolean value. True indicates that both the dataframes has equal values in the corresponding cells. Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe *args and **kwargs in Python Create a Pandas DataFrame from Lists Check if element exists in list in Python Convert integer to string in Python How To Convert Python Dictionary To JSON? sum() function in Python
[ { "code": null, "e": 26111, "s": 26083, "text": "\n20 Nov, 2018" }, { "code": null, "e": 26325, "s": 26111, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 26578, "s": 26325, "text": "Pandas dataframe.equals() function is used to determine if two dataframe object in consideration are equal or not. Unlike dataframe.eq() method, the result of the operation is a scalar boolean value indicating if the dataframe objects are equal or not." }, { "code": null, "e": 26610, "s": 26578, "text": "Syntax: DataFrame.equals(other)" }, { "code": null, "e": 26639, "s": 26610, "text": "Parameters:other : DataFrame" }, { "code": null, "e": 26671, "s": 26639, "text": "Returns: Scalar : boolean value" }, { "code": null, "e": 26779, "s": 26671, "text": "Example #1: Use equals() function to find the result of comparison between two different dataframe objects." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the first dataframe df1 = pd.DataFrame({\"A\":[1,5,7,8], \"B\":[5,8,4,3], \"C\":[10,4,9,3]}) # Creating the second dataframedf2 = pd.DataFrame({\"A\":[5,3,6,4], \"B\":[11,2,4,3], \"C\":[4,3,8,5]}) # Print the first dataframedf1 # Print the second dataframedf2", "e": 27154, "s": 26779, "text": null }, { "code": null, "e": 27220, "s": 27154, "text": "Let’s find the result of comparison between both the data frames." }, { "code": "# To find the comparison resultdf1.equals(df2)", "e": 27267, "s": 27220, "text": null }, { "code": null, "e": 27276, "s": 27267, "text": "Output :" }, { "code": null, "e": 27383, "s": 27276, "text": "The output is False because the two dataframes are not equal to each other. They have different elements. " }, { "code": null, "e": 27539, "s": 27383, "text": "Example #2: Use equals() function to test for equality between two data frame object with NaN values.Note : NaNs in the same location are considered equal." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the first dataframedf1 = pd.DataFrame({\"A\":[1,2,3], \"B\":[4,5,None], \"C\":[7,8,9]}) # Creating the second dataframedf2 = pd.DataFrame({\"A\":[1,2,3], \"B\":[4,5,None], \"C\":[7,8,9]}) # Print the first dataframedf1 # Print the second dataframedf2", "e": 27905, "s": 27539, "text": null }, { "code": null, "e": 27964, "s": 27905, "text": "Let’s perform comparison operation on both the dataframes." }, { "code": "# To find the comparison between two dataframesdf1.equals(df2)", "e": 28027, "s": 27964, "text": null }, { "code": null, "e": 28036, "s": 28027, "text": "Output :" }, { "code": null, "e": 28154, "s": 28036, "text": "The output scalar boolean value. True indicates that both the dataframes has equal values in the corresponding cells." }, { "code": null, "e": 28178, "s": 28154, "text": "Python pandas-dataFrame" }, { "code": null, "e": 28210, "s": 28178, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 28224, "s": 28210, "text": "Python-pandas" }, { "code": null, "e": 28231, "s": 28224, "text": "Python" }, { "code": null, "e": 28329, "s": 28231, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28347, "s": 28329, "text": "Python Dictionary" }, { "code": null, "e": 28379, "s": 28347, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28401, "s": 28379, "text": "Enumerate() in Python" }, { "code": null, "e": 28443, "s": 28401, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28472, "s": 28443, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28509, "s": 28472, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28551, "s": 28509, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28587, "s": 28551, "text": "Convert integer to string in Python" }, { "code": null, "e": 28629, "s": 28587, "text": "How To Convert Python Dictionary To JSON?" } ]
std::find_if , std::find_if_not in C++ - GeeksforGeeks
28 Apr, 2022 std :: find_if Returns an iterator to the first element in the range [first, last) for which pred(Unary Function) returns true. If no such element is found, the function returns last. Function Template : InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred); first, last :range which contains all the elements between first and last, including the element pointed by first but not the element pointed by last. pred : Unary function that accepts an element in the range as argument and returns a value in boolean. Return value : Returns an iterator to the first element in the range [first, last) for which pred(function) returns true. If no such element is found, the function returns last. std :: find_if_not Returns an iterator to the first element in the range [first, last) for which pred(Unary Function) returns false. If no such element is found, the function returns last. Function Template : InputIterator find_if_not (InputIterator first, InputIterator last, UnaryPredicate pred); Return value : Returns an iterator to the first element in the range [first, last) for which pred(function) returns false. CPP // CPP program to illustrate// std::find_if and std::find_if_not#include <bits/stdc++.h> // Returns true if argument is oddbool IsOdd(int i){ return i % 2;} // Driver codeint main(){ std::vector<int> vec{ 10, 25, 40, 55 }; // Iterator to store the position of element found std::vector<int>::iterator it; // std::find_if it = std::find_if(vec.begin(), vec.end(), IsOdd); std::cout << "The first odd value is " << *it << '\n'; // Iterator to store the position of element found std::vector<int>::iterator ite; // std::find_if_not ite = std::find_if_not(vec.begin(), vec.end(), IsOdd); std::cout << "The first non-odd(or even) value is " << *ite << '\n'; return 0;} Output: The first odd value is 25 The first non-odd(or even) value is 10 Related Articles: std::search std::find std::nth_element std::find_end This article is contributed by Sachin Bisht. 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. tomsaalex cpp-algorithm-library STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Sorting a vector in C++ Friend class and function in C++ std::string class in C++ Pair in C++ Standard Template Library (STL) Queue in C++ Standard Template Library (STL) Inline Functions in C++ Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++
[ { "code": null, "e": 25367, "s": 25339, "text": "\n28 Apr, 2022" }, { "code": null, "e": 25382, "s": 25367, "text": "std :: find_if" }, { "code": null, "e": 25571, "s": 25382, "text": "Returns an iterator to the first element in the range [first, last) for which pred(Unary Function) returns true. If no such element is found, the function returns last. Function Template :" }, { "code": null, "e": 26092, "s": 25571, "text": "InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred);\n\nfirst, last :range which contains all the elements between first\nand last, including the element pointed by first but\nnot the element pointed by last.\n\npred : Unary function that accepts an element in the range\nas argument and returns a value in boolean.\n\nReturn value :\nReturns an iterator to the first element in the range\n[first, last) for which pred(function) returns true. If\nno such element is found, the function returns last." }, { "code": null, "e": 26111, "s": 26092, "text": "std :: find_if_not" }, { "code": null, "e": 26301, "s": 26111, "text": "Returns an iterator to the first element in the range [first, last) for which pred(Unary Function) returns false. If no such element is found, the function returns last. Function Template :" }, { "code": null, "e": 26515, "s": 26301, "text": "InputIterator find_if_not (InputIterator first, InputIterator last, UnaryPredicate pred);\n\nReturn value :\nReturns an iterator to the first element in the range\n[first, last) for which pred(function) returns false." }, { "code": null, "e": 26519, "s": 26515, "text": "CPP" }, { "code": "// CPP program to illustrate// std::find_if and std::find_if_not#include <bits/stdc++.h> // Returns true if argument is oddbool IsOdd(int i){ return i % 2;} // Driver codeint main(){ std::vector<int> vec{ 10, 25, 40, 55 }; // Iterator to store the position of element found std::vector<int>::iterator it; // std::find_if it = std::find_if(vec.begin(), vec.end(), IsOdd); std::cout << \"The first odd value is \" << *it << '\\n'; // Iterator to store the position of element found std::vector<int>::iterator ite; // std::find_if_not ite = std::find_if_not(vec.begin(), vec.end(), IsOdd); std::cout << \"The first non-odd(or even) value is \" << *ite << '\\n'; return 0;}", "e": 27240, "s": 26519, "text": null }, { "code": null, "e": 27248, "s": 27240, "text": "Output:" }, { "code": null, "e": 27313, "s": 27248, "text": "The first odd value is 25\nThe first non-odd(or even) value is 10" }, { "code": null, "e": 27332, "s": 27313, "text": "Related Articles: " }, { "code": null, "e": 27344, "s": 27332, "text": "std::search" }, { "code": null, "e": 27354, "s": 27344, "text": "std::find" }, { "code": null, "e": 27371, "s": 27354, "text": "std::nth_element" }, { "code": null, "e": 27385, "s": 27371, "text": "std::find_end" }, { "code": null, "e": 27806, "s": 27385, "text": "This article is contributed by Sachin Bisht. 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": 27816, "s": 27806, "text": "tomsaalex" }, { "code": null, "e": 27838, "s": 27816, "text": "cpp-algorithm-library" }, { "code": null, "e": 27842, "s": 27838, "text": "STL" }, { "code": null, "e": 27846, "s": 27842, "text": "C++" }, { "code": null, "e": 27850, "s": 27846, "text": "STL" }, { "code": null, "e": 27854, "s": 27850, "text": "CPP" }, { "code": null, "e": 27952, "s": 27854, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27980, "s": 27952, "text": "Operator Overloading in C++" }, { "code": null, "e": 28000, "s": 27980, "text": "Polymorphism in C++" }, { "code": null, "e": 28024, "s": 28000, "text": "Sorting a vector in C++" }, { "code": null, "e": 28057, "s": 28024, "text": "Friend class and function in C++" }, { "code": null, "e": 28082, "s": 28057, "text": "std::string class in C++" }, { "code": null, "e": 28126, "s": 28082, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 28171, "s": 28126, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 28195, "s": 28171, "text": "Inline Functions in C++" }, { "code": null, "e": 28248, "s": 28195, "text": "Array of Strings in C++ (5 Different Ways to Create)" } ]
HTML Course | Building Footer - GeeksforGeeks
10 Aug, 2021 Course Navigation So, we have completed building all parts of our website except the footer. So, let’s take a look at what our final footer will look like: Our footer mainly consists of two sections: Company Details: This contains of three columns with address details, phone details and Email details. Copyright Information: This contains information about the Copyright and links to social media handles. Before we start building the Footer. It is recommended to go to this link once: Font Awesome Icons. We will be using font awesome icons at different places in the footer. To use fontawesome icons, follow below steps: Include Font Awesome CSS. Paste the below code in between your head tags present at the top of index.html file. HTML <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> Now, to use the icons just add the below class to a span tag. <span class="fa fa-icon_name"></span> Where, icon_name is the name of the icon. Let us now just start writing the HTML structure of the website’s footer. We have divided the footer in two sections namely Company Details and Copyright Information. Follow the below steps: Create two div’s with class names as “company-details” and “copyright” respectively.Steps For div with class “company-details”:Add a div with class named as “row”.Add three div’s inside the previous div with id’s col1, col2 and col3 respectively.For each of the column divs declare two span tags. One for the font awesome icon and second for the information.Steps For div with class “copyright”: Add a paragraph element to show the text: “© All rights reserved | GeeksforGeeks.”Add an unordered list of three elements to show the three social media icons. Create two div’s with class names as “company-details” and “copyright” respectively. Steps For div with class “company-details”:Add a div with class named as “row”.Add three div’s inside the previous div with id’s col1, col2 and col3 respectively.For each of the column divs declare two span tags. One for the font awesome icon and second for the information. Add a div with class named as “row”. Add three div’s inside the previous div with id’s col1, col2 and col3 respectively. For each of the column divs declare two span tags. One for the font awesome icon and second for the information. Steps For div with class “copyright”: Add a paragraph element to show the text: “© All rights reserved | GeeksforGeeks.”Add an unordered list of three elements to show the three social media icons. Add a paragraph element to show the text: “© All rights reserved | GeeksforGeeks.” Add an unordered list of three elements to show the three social media icons. Below is the complete HTML code of the footer: HTML <!-- Footer Menu --> <footer id="footer"> <!-- Company Details --> <!-- 1. Address 2. Contact Number 3. Enquiry Mail --> <div class="company-details"> <div class="row"> <div id="col1"> <span id="icon" class="fa fa-map-marker"></span> <span> 710-B, Advant Navis Business Park, <br />Sector-142, Noida </span> </div> <div id="col2"> <span id="icon" class="fa fa-phone"></span> <span> Telephone: +91-890 * * * * * * * </span> </div> <div id="col3"> <span id="icon" class="fa fa-envelope"></span> <span>[email protected]</span> </div> </div> </div> <!-- Copyright Section --> <div class="copyright"> <p>© All rights reserved | GeeksforGeeks.</p> <ul class="contact"> <li> <a href="#" class="fa fa-twitter"> </a> </li> <li> <a href="#" class="fa fa-facebook"> </a> </li> <li> <a href="#" class="fa fa-pinterest-p"> </a> </li> </ul> </div> </footer> Look at the red marked portion in the below image. This is what the website’s footer look like now: Let’s now add styles to the footer. Adding Styles to div “website-details” First style the basic layout: Set the basic margins, paddings, background color and align the texts to center. Add the below CSS code to your style.css: CSS .company-details{ overflow: hidden; padding: 3em 0em; background: #E3F0F7; text-align: center; margin-top: 5em;} Aligning the three columns in one line: Float all of the three columns to the left and assign a width of 320px to each one of them. Add the below CSS code to your style.css file: CSS #footer #col1,#footer #col2,#footer #col3{ float: left; width: 320px; padding: 0px 40px 0px 40px;} Adding Styles to the FontAwesome Icons: Set the font-size of the icons to 3em and a bottom-margin of 1em and display them as block. Add the below CSS code to your style.css file: CSS #footer #icon{ display: block; margin-bottom: 1em; font-size: 3em;} Adding Styles to div “copyright” Adding Styles to basic layout: Set the basic margins, paddings, background-colors etc. for the copyright class.Add the below CSS code to your style.css file: CSS .copyright{ overflow: hidden; padding: 3em 0em; border-top: 20px solid rgba(255, 255, 255, 0.08); text-align: center; background: #4CAF50;} Adding style to the paragraph element: Add styles to the copyright information stored in <p> tags. Add letter-spacing, color etc.Add the below CSS code to your style.css file: CSS .copyright p{ letter-spacing: 1px; font-size: 0.90em; color: rgba(255, 255, 255, 0.6);} Adding Styles to the anchor tag: Set the color of the anchor tag and text-decoration to none: CSS .copyright a{ text-decoration: none; color: rgba(255, 255, 255, 0.8);} If you open the index.html file in the browser now, you will see the footer as shown below: The above footer looks good, the only difference is in the display of the social icons of facebook, twitter etc. Let’s fix this. The last thing left is to add styles to the social media icons. Adding styles to the Social Icons: Remove the margin from the ul or class named “contact”, add padding and set the list-style to none: CSS ul.contact{ margin: 0; padding: 2em 0em 0em 0em; list-style: none;} Set the list items to display as inline-block so that the icons can be displayed horizontally instead of vertically. Also add padding and font-size to the list items. CSS ul.contact li{ display: inline-block; padding: 0em 0.10em; font-size: 1em;} After adding the above two styles, the icons will now be arranged horizontally and at the center of the copyright div. Refresh and see the result in your browser after making the above changes. The last thing is to add background for the social icons. To do so, add the below style for the anchor tags of each list item: CSS ul.contact li a{ color: #FFF; display: inline-block; background: #4C93B9; width: 40px; height: 40px; line-height: 40px; text-align: center;} The complete CSS code for the footer of the Website is as below: CSS /**********************************//* Styling Footer *//**********************************/ /*** Adding Styles to Company Details ***/.company-details{ overflow: hidden; padding: 3em 0em; background: #E3F0F7; text-align: center; margin-top: 5em;} #footer #col1,#footer #col2,#footer #col3{ float: left; width: 320px; padding: 0px 40px 0px 40px;} #footer #icon{ display: block; margin-bottom: 1em; font-size: 3em;} /*** Adding Styles to Copyright Div ***/.copyright{ overflow: hidden; padding: 3em 0em; border-top: 20px solid rgba(255, 255, 255, 0.08); text-align: center; background: #4CAF50;} .copyright p{ letter-spacing: 1px; font-size: 0.90em; color: rgba(255, 255, 255, 0.6);} .copyright a{ text-decoration: none; color: rgba(255, 255, 255, 0.8);} /* Styling Social Icons */ul.contact{ margin: 0; padding: 2em 0em 0em 0em; list-style: none;} ul.contact li{ display: inline-block; padding: 0em 0.10em; font-size: 1em;} ul.contact li a{ color: #FFF; display: inline-block; background: #4C93B9; width: 40px; height: 40px; line-height: 40px; text-align: center;} Supported Browser: Google Chrome Microsoft Edge Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. ghoshsuman0129 ysachin2314 HTML-course-basic HTML5 CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property
[ { "code": null, "e": 31623, "s": 31595, "text": "\n10 Aug, 2021" }, { "code": null, "e": 31643, "s": 31623, "text": "Course Navigation " }, { "code": null, "e": 31783, "s": 31643, "text": "So, we have completed building all parts of our website except the footer. So, let’s take a look at what our final footer will look like: " }, { "code": null, "e": 31829, "s": 31783, "text": "Our footer mainly consists of two sections: " }, { "code": null, "e": 31932, "s": 31829, "text": "Company Details: This contains of three columns with address details, phone details and Email details." }, { "code": null, "e": 32036, "s": 31932, "text": "Copyright Information: This contains information about the Copyright and links to social media handles." }, { "code": null, "e": 32255, "s": 32036, "text": "Before we start building the Footer. It is recommended to go to this link once: Font Awesome Icons. We will be using font awesome icons at different places in the footer. To use fontawesome icons, follow below steps: " }, { "code": null, "e": 32369, "s": 32255, "text": "Include Font Awesome CSS. Paste the below code in between your head tags present at the top of index.html file. " }, { "code": null, "e": 32374, "s": 32369, "text": "HTML" }, { "code": "<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\">", "e": 32488, "s": 32374, "text": null }, { "code": null, "e": 32552, "s": 32488, "text": "Now, to use the icons just add the below class to a span tag. " }, { "code": null, "e": 32633, "s": 32552, "text": "<span class=\"fa fa-icon_name\"></span>\n\nWhere, icon_name is the name of the icon." }, { "code": null, "e": 32826, "s": 32633, "text": "Let us now just start writing the HTML structure of the website’s footer. We have divided the footer in two sections namely Company Details and Copyright Information. Follow the below steps: " }, { "code": null, "e": 33382, "s": 32826, "text": "Create two div’s with class names as “company-details” and “copyright” respectively.Steps For div with class “company-details”:Add a div with class named as “row”.Add three div’s inside the previous div with id’s col1, col2 and col3 respectively.For each of the column divs declare two span tags. One for the font awesome icon and second for the information.Steps For div with class “copyright”: Add a paragraph element to show the text: “© All rights reserved | GeeksforGeeks.”Add an unordered list of three elements to show the three social media icons." }, { "code": null, "e": 33467, "s": 33382, "text": "Create two div’s with class names as “company-details” and “copyright” respectively." }, { "code": null, "e": 33742, "s": 33467, "text": "Steps For div with class “company-details”:Add a div with class named as “row”.Add three div’s inside the previous div with id’s col1, col2 and col3 respectively.For each of the column divs declare two span tags. One for the font awesome icon and second for the information." }, { "code": null, "e": 33779, "s": 33742, "text": "Add a div with class named as “row”." }, { "code": null, "e": 33863, "s": 33779, "text": "Add three div’s inside the previous div with id’s col1, col2 and col3 respectively." }, { "code": null, "e": 33976, "s": 33863, "text": "For each of the column divs declare two span tags. One for the font awesome icon and second for the information." }, { "code": null, "e": 34174, "s": 33976, "text": "Steps For div with class “copyright”: Add a paragraph element to show the text: “© All rights reserved | GeeksforGeeks.”Add an unordered list of three elements to show the three social media icons." }, { "code": null, "e": 34257, "s": 34174, "text": "Add a paragraph element to show the text: “© All rights reserved | GeeksforGeeks.”" }, { "code": null, "e": 34335, "s": 34257, "text": "Add an unordered list of three elements to show the three social media icons." }, { "code": null, "e": 34384, "s": 34335, "text": "Below is the complete HTML code of the footer: " }, { "code": null, "e": 34389, "s": 34384, "text": "HTML" }, { "code": "<!-- Footer Menu --> <footer id=\"footer\"> <!-- Company Details --> <!-- 1. Address 2. Contact Number 3. Enquiry Mail --> <div class=\"company-details\"> <div class=\"row\"> <div id=\"col1\"> <span id=\"icon\" class=\"fa fa-map-marker\"></span> <span> 710-B, Advant Navis Business Park, <br />Sector-142, Noida </span> </div> <div id=\"col2\"> <span id=\"icon\" class=\"fa fa-phone\"></span> <span> Telephone: +91-890 * * * * * * * </span> </div> <div id=\"col3\"> <span id=\"icon\" class=\"fa fa-envelope\"></span> <span>[email protected]</span> </div> </div> </div> <!-- Copyright Section --> <div class=\"copyright\"> <p>© All rights reserved | GeeksforGeeks.</p> <ul class=\"contact\"> <li> <a href=\"#\" class=\"fa fa-twitter\"> </a> </li> <li> <a href=\"#\" class=\"fa fa-facebook\"> </a> </li> <li> <a href=\"#\" class=\"fa fa-pinterest-p\"> </a> </li> </ul> </div> </footer>", "e": 35875, "s": 34389, "text": null }, { "code": null, "e": 35977, "s": 35875, "text": "Look at the red marked portion in the below image. This is what the website’s footer look like now: " }, { "code": null, "e": 36014, "s": 35977, "text": "Let’s now add styles to the footer. " }, { "code": null, "e": 36055, "s": 36014, "text": "Adding Styles to div “website-details” " }, { "code": null, "e": 36210, "s": 36055, "text": "First style the basic layout: Set the basic margins, paddings, background color and align the texts to center. Add the below CSS code to your style.css: " }, { "code": null, "e": 36214, "s": 36210, "text": "CSS" }, { "code": ".company-details{ overflow: hidden; padding: 3em 0em; background: #E3F0F7; text-align: center; margin-top: 5em;}", "e": 36342, "s": 36214, "text": null }, { "code": null, "e": 36523, "s": 36342, "text": "Aligning the three columns in one line: Float all of the three columns to the left and assign a width of 320px to each one of them. Add the below CSS code to your style.css file: " }, { "code": null, "e": 36527, "s": 36523, "text": "CSS" }, { "code": "#footer #col1,#footer #col2,#footer #col3{ float: left; width: 320px; padding: 0px 40px 0px 40px;}", "e": 36635, "s": 36527, "text": null }, { "code": null, "e": 36816, "s": 36635, "text": "Adding Styles to the FontAwesome Icons: Set the font-size of the icons to 3em and a bottom-margin of 1em and display them as block. Add the below CSS code to your style.css file: " }, { "code": null, "e": 36820, "s": 36816, "text": "CSS" }, { "code": "#footer #icon{ display: block; margin-bottom: 1em; font-size: 3em;}", "e": 36897, "s": 36820, "text": null }, { "code": null, "e": 36932, "s": 36897, "text": "Adding Styles to div “copyright” " }, { "code": null, "e": 37092, "s": 36932, "text": "Adding Styles to basic layout: Set the basic margins, paddings, background-colors etc. for the copyright class.Add the below CSS code to your style.css file: " }, { "code": null, "e": 37096, "s": 37092, "text": "CSS" }, { "code": ".copyright{ overflow: hidden; padding: 3em 0em; border-top: 20px solid rgba(255, 255, 255, 0.08); text-align: center; background: #4CAF50;}", "e": 37251, "s": 37096, "text": null }, { "code": null, "e": 37429, "s": 37251, "text": "Adding style to the paragraph element: Add styles to the copyright information stored in <p> tags. Add letter-spacing, color etc.Add the below CSS code to your style.css file: " }, { "code": null, "e": 37433, "s": 37429, "text": "CSS" }, { "code": ".copyright p{ letter-spacing: 1px; font-size: 0.90em; color: rgba(255, 255, 255, 0.6);}", "e": 37530, "s": 37433, "text": null }, { "code": null, "e": 37626, "s": 37530, "text": "Adding Styles to the anchor tag: Set the color of the anchor tag and text-decoration to none: " }, { "code": null, "e": 37630, "s": 37626, "text": "CSS" }, { "code": ".copyright a{ text-decoration: none; color: rgba(255, 255, 255, 0.8);}", "e": 37707, "s": 37630, "text": null }, { "code": null, "e": 37800, "s": 37707, "text": "If you open the index.html file in the browser now, you will see the footer as shown below: " }, { "code": null, "e": 37995, "s": 37800, "text": " The above footer looks good, the only difference is in the display of the social icons of facebook, twitter etc. Let’s fix this. The last thing left is to add styles to the social media icons. " }, { "code": null, "e": 38031, "s": 37995, "text": "Adding styles to the Social Icons: " }, { "code": null, "e": 38133, "s": 38031, "text": "Remove the margin from the ul or class named “contact”, add padding and set the list-style to none: " }, { "code": null, "e": 38137, "s": 38133, "text": "CSS" }, { "code": "ul.contact{ margin: 0; padding: 2em 0em 0em 0em; list-style: none;}", "e": 38214, "s": 38137, "text": null }, { "code": null, "e": 38383, "s": 38214, "text": "Set the list items to display as inline-block so that the icons can be displayed horizontally instead of vertically. Also add padding and font-size to the list items. " }, { "code": null, "e": 38387, "s": 38383, "text": "CSS" }, { "code": "ul.contact li{ display: inline-block; padding: 0em 0.10em; font-size: 1em;}", "e": 38472, "s": 38387, "text": null }, { "code": null, "e": 38666, "s": 38472, "text": "After adding the above two styles, the icons will now be arranged horizontally and at the center of the copyright div. Refresh and see the result in your browser after making the above changes." }, { "code": null, "e": 38795, "s": 38666, "text": "The last thing is to add background for the social icons. To do so, add the below style for the anchor tags of each list item: " }, { "code": null, "e": 38799, "s": 38795, "text": "CSS" }, { "code": "ul.contact li a{ color: #FFF; display: inline-block; background: #4C93B9; width: 40px; height: 40px; line-height: 40px; text-align: center;}", "e": 38961, "s": 38799, "text": null }, { "code": null, "e": 39028, "s": 38961, "text": "The complete CSS code for the footer of the Website is as below: " }, { "code": null, "e": 39032, "s": 39028, "text": "CSS" }, { "code": "/**********************************//* Styling Footer *//**********************************/ /*** Adding Styles to Company Details ***/.company-details{ overflow: hidden; padding: 3em 0em; background: #E3F0F7; text-align: center; margin-top: 5em;} #footer #col1,#footer #col2,#footer #col3{ float: left; width: 320px; padding: 0px 40px 0px 40px;} #footer #icon{ display: block; margin-bottom: 1em; font-size: 3em;} /*** Adding Styles to Copyright Div ***/.copyright{ overflow: hidden; padding: 3em 0em; border-top: 20px solid rgba(255, 255, 255, 0.08); text-align: center; background: #4CAF50;} .copyright p{ letter-spacing: 1px; font-size: 0.90em; color: rgba(255, 255, 255, 0.6);} .copyright a{ text-decoration: none; color: rgba(255, 255, 255, 0.8);} /* Styling Social Icons */ul.contact{ margin: 0; padding: 2em 0em 0em 0em; list-style: none;} ul.contact li{ display: inline-block; padding: 0em 0.10em; font-size: 1em;} ul.contact li a{ color: #FFF; display: inline-block; background: #4C93B9; width: 40px; height: 40px; line-height: 40px; text-align: center;}", "e": 40231, "s": 39032, "text": null }, { "code": null, "e": 40250, "s": 40231, "text": "Supported Browser:" }, { "code": null, "e": 40264, "s": 40250, "text": "Google Chrome" }, { "code": null, "e": 40279, "s": 40264, "text": "Microsoft Edge" }, { "code": null, "e": 40287, "s": 40279, "text": "Firefox" }, { "code": null, "e": 40293, "s": 40287, "text": "Opera" }, { "code": null, "e": 40300, "s": 40293, "text": "Safari" }, { "code": null, "e": 40437, "s": 40300, "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": 40452, "s": 40437, "text": "ghoshsuman0129" }, { "code": null, "e": 40464, "s": 40452, "text": "ysachin2314" }, { "code": null, "e": 40482, "s": 40464, "text": "HTML-course-basic" }, { "code": null, "e": 40488, "s": 40482, "text": "HTML5" }, { "code": null, "e": 40492, "s": 40488, "text": "CSS" }, { "code": null, "e": 40497, "s": 40492, "text": "HTML" }, { "code": null, "e": 40514, "s": 40497, "text": "Web Technologies" }, { "code": null, "e": 40519, "s": 40514, "text": "HTML" }, { "code": null, "e": 40617, "s": 40519, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40667, "s": 40617, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 40729, "s": 40667, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 40777, "s": 40729, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 40835, "s": 40777, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 40890, "s": 40835, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 40940, "s": 40890, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 41002, "s": 40940, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 41050, "s": 41002, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 41110, "s": 41050, "text": "How to set the default value for an HTML <select> element ?" } ]
Tail Call Elimination - GeeksforGeeks
17 May, 2021 We have discussed (in tail recursion) that a recursive function is tail recursive if the recursive call is the last thing executed by the function. C++ Java Python3 C# Javascript // An example of tail recursive functionvoid print(int n){ if (n < 0) return; cout << " " << n; // The last executed statement is recursive call print(n-1);} // An example of tail recursive functionstatic void print(int n){ if (n < 0) return; System.out.print(" " + n); // The last executed statement // is recursive call print(n - 1);} // This code is contributed by rutvik_56 # An example of tail recursive functiondef print(n): if (n < 0): return print(" ", n) # The last executed statement is recursive call print(n - 1) # This code is contributed by sanjoy_62 // An example of tail recursive functionstatic void print(int n){ if (n < 0) return; Console.Write(" " + n); // The last executed statement // is recursive call print(n - 1);} // This code is contributed by pratham76 <script> // An example of tail recursive functionfunction print(n){ if (n < 0) return; document.write( " " + n); // The last executed statement is recursive call print(n-1);} </script> We also discussed that a tail-recursive is better than a non-tail recursive as tail-recursion can be optimized by modern compilers. Modern compiler basically does tail call elimination to optimize the tail-recursive code. If we take a closer look at the above function, we can remove the last call with goto. Below are examples of tail call elimination. C++ // Above code after tail call eliminationvoid print(int n){start: if (n < 0) return; cout << " " << n; // Update parameters of recursive call // and replace recursive call with goto n = n-1 goto start;} QuickSort : One more example QuickSort is also tail recursive (Note that MergeSort is not tail recursive, this is also one of the reasons why QuickSort performs better) C++ /* Tail recursive function for QuickSort arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */void quickSort(int arr[], int low, int high){ if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); }}// See below link for complete running code// http://geeksquiz.com/quick-sort/ The above function can be replaced by following after tail call elimination. C++ /* QuickSort after tail call elimination arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */void quickSort(int arr[], int low, int high){start: if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi - 1); // Update parameters of recursive call // and replace recursive call with goto low = pi+1; high = high; goto start; }}// See below link for complete running code// https://ide.geeksforgeeks.org/dbq4yl Therefore job for compilers is to identify tail recursion, add a label at the beginning and update parameter(s) at the end followed by adding the last goto statement. Function stack frame management in Tail Call Elimination : Recursion uses a stack to keep track of function calls. With every function call, a new frame is pushed onto the stack which contains local variables and data of that call. Let’s say one stack frame requires O(1) i.e, constant memory space, then for N recursive call memory required would be O(N). Tail call elimination reduces the space complexity of recursion from O(N) to O(1). As function call is eliminated, no new stack frames are created and the function is executed in constant memory space. It is possible for the function to execute in constant memory space because, in tail recursive function, there are no statements after call statement so preserving state and frame of parent function is not required. Child function is called and finishes immediately, it doesn’t have to return control back to the parent function. As no computation is performed on the returned value and no statements are left for execution, the current frame can be modified as per the requirements of the current function call. So there is no need to preserve stack frames of previous function calls and function executes in constant memory space. This makes tail recursion faster and memory-friendly. Next Article: QuickSort Tail Call Optimization (Reducing worst case space to Log n )This article is contributed by Dheeraj Jain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above ishayadav181 rutvik_56 pratham76 sanjoy_62 famously Quick Sort tail-recursion Algorithms Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar How to write a Pseudo Code? Understanding Time Complexity with Simple Examples Introduction to Algorithms How to Start Learning DSA? Playfair Cipher with Examples Difference between NP hard and NP complete problem Converting Roman Numerals to Decimal lying between 1 to 3999 Quick Sort vs Merge Sort
[ { "code": null, "e": 25931, "s": 25903, "text": "\n17 May, 2021" }, { "code": null, "e": 26080, "s": 25931, "text": "We have discussed (in tail recursion) that a recursive function is tail recursive if the recursive call is the last thing executed by the function. " }, { "code": null, "e": 26084, "s": 26080, "text": "C++" }, { "code": null, "e": 26089, "s": 26084, "text": "Java" }, { "code": null, "e": 26097, "s": 26089, "text": "Python3" }, { "code": null, "e": 26100, "s": 26097, "text": "C#" }, { "code": null, "e": 26111, "s": 26100, "text": "Javascript" }, { "code": "// An example of tail recursive functionvoid print(int n){ if (n < 0) return; cout << \" \" << n; // The last executed statement is recursive call print(n-1);}", "e": 26289, "s": 26111, "text": null }, { "code": "// An example of tail recursive functionstatic void print(int n){ if (n < 0) return; System.out.print(\" \" + n); // The last executed statement // is recursive call print(n - 1);} // This code is contributed by rutvik_56", "e": 26541, "s": 26289, "text": null }, { "code": "# An example of tail recursive functiondef print(n): if (n < 0): return print(\" \", n) # The last executed statement is recursive call print(n - 1) # This code is contributed by sanjoy_62", "e": 26757, "s": 26541, "text": null }, { "code": "// An example of tail recursive functionstatic void print(int n){ if (n < 0) return; Console.Write(\" \" + n); // The last executed statement // is recursive call print(n - 1);} // This code is contributed by pratham76", "e": 27006, "s": 26757, "text": null }, { "code": "<script> // An example of tail recursive functionfunction print(n){ if (n < 0) return; document.write( \" \" + n); // The last executed statement is recursive call print(n-1);} </script>", "e": 27213, "s": 27006, "text": null }, { "code": null, "e": 27436, "s": 27213, "text": "We also discussed that a tail-recursive is better than a non-tail recursive as tail-recursion can be optimized by modern compilers. Modern compiler basically does tail call elimination to optimize the tail-recursive code. " }, { "code": null, "e": 27568, "s": 27436, "text": "If we take a closer look at the above function, we can remove the last call with goto. Below are examples of tail call elimination." }, { "code": null, "e": 27572, "s": 27568, "text": "C++" }, { "code": "// Above code after tail call eliminationvoid print(int n){start: if (n < 0) return; cout << \" \" << n; // Update parameters of recursive call // and replace recursive call with goto n = n-1 goto start;}", "e": 27800, "s": 27572, "text": null }, { "code": null, "e": 27970, "s": 27800, "text": "QuickSort : One more example QuickSort is also tail recursive (Note that MergeSort is not tail recursive, this is also one of the reasons why QuickSort performs better) " }, { "code": null, "e": 27974, "s": 27970, "text": "C++" }, { "code": "/* Tail recursive function for QuickSort arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */void quickSort(int arr[], int low, int high){ if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); }}// See below link for complete running code// http://geeksquiz.com/quick-sort/", "e": 28528, "s": 27974, "text": null }, { "code": null, "e": 28606, "s": 28528, "text": "The above function can be replaced by following after tail call elimination. " }, { "code": null, "e": 28610, "s": 28606, "text": "C++" }, { "code": "/* QuickSort after tail call elimination arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */void quickSort(int arr[], int low, int high){start: if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi - 1); // Update parameters of recursive call // and replace recursive call with goto low = pi+1; high = high; goto start; }}// See below link for complete running code// https://ide.geeksforgeeks.org/dbq4yl", "e": 29290, "s": 28610, "text": null }, { "code": null, "e": 29457, "s": 29290, "text": "Therefore job for compilers is to identify tail recursion, add a label at the beginning and update parameter(s) at the end followed by adding the last goto statement." }, { "code": null, "e": 29815, "s": 29457, "text": "Function stack frame management in Tail Call Elimination : Recursion uses a stack to keep track of function calls. With every function call, a new frame is pushed onto the stack which contains local variables and data of that call. Let’s say one stack frame requires O(1) i.e, constant memory space, then for N recursive call memory required would be O(N). " }, { "code": null, "e": 30018, "s": 29815, "text": "Tail call elimination reduces the space complexity of recursion from O(N) to O(1). As function call is eliminated, no new stack frames are created and the function is executed in constant memory space. " }, { "code": null, "e": 30349, "s": 30018, "text": "It is possible for the function to execute in constant memory space because, in tail recursive function, there are no statements after call statement so preserving state and frame of parent function is not required. Child function is called and finishes immediately, it doesn’t have to return control back to the parent function. " }, { "code": null, "e": 30706, "s": 30349, "text": "As no computation is performed on the returned value and no statements are left for execution, the current frame can be modified as per the requirements of the current function call. So there is no need to preserve stack frames of previous function calls and function executes in constant memory space. This makes tail recursion faster and memory-friendly." }, { "code": null, "e": 30960, "s": 30706, "text": "Next Article: QuickSort Tail Call Optimization (Reducing worst case space to Log n )This article is contributed by Dheeraj Jain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 30973, "s": 30960, "text": "ishayadav181" }, { "code": null, "e": 30983, "s": 30973, "text": "rutvik_56" }, { "code": null, "e": 30993, "s": 30983, "text": "pratham76" }, { "code": null, "e": 31003, "s": 30993, "text": "sanjoy_62" }, { "code": null, "e": 31012, "s": 31003, "text": "famously" }, { "code": null, "e": 31023, "s": 31012, "text": "Quick Sort" }, { "code": null, "e": 31038, "s": 31023, "text": "tail-recursion" }, { "code": null, "e": 31049, "s": 31038, "text": "Algorithms" }, { "code": null, "e": 31060, "s": 31049, "text": "Algorithms" }, { "code": null, "e": 31158, "s": 31060, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31207, "s": 31158, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 31232, "s": 31207, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 31260, "s": 31232, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 31311, "s": 31260, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 31338, "s": 31311, "text": "Introduction to Algorithms" }, { "code": null, "e": 31365, "s": 31338, "text": "How to Start Learning DSA?" }, { "code": null, "e": 31395, "s": 31365, "text": "Playfair Cipher with Examples" }, { "code": null, "e": 31446, "s": 31395, "text": "Difference between NP hard and NP complete problem" }, { "code": null, "e": 31507, "s": 31446, "text": "Converting Roman Numerals to Decimal lying between 1 to 3999" } ]
list unique() in C++ STL - GeeksforGeeks
04 Feb, 2021 list::unique() is an inbuilt function in C++ STL which removes all duplicate consecutive elements from the list. It works only on sorted list. Syntax: list_name.unique(BinaryPredicate name) Parameters: The function accepts a single and optional parameter which is a binary predicate that returns true if the elements should be treated as equal. It has following syntax: bool name(data_type a, data_type b); Return value: This function does not return anything. Below is the implementation of above function: CPP // C++ program to illustrate the// unique() function#include <bits/stdc++.h>using namespace std; // Function for binary_predicatebool compare(double a, double b){ return ((int)a == (int)b);} // Driver codeint main(){ list<double> list = { 2.55, 3.15, 4.16, 4.16, 4.77, 12.65, 12.65, 13.59 }; cout << "List is: "; //sort the list list.sort(); // unique operation on list with no parameters list.unique(); // starts from the first element // of the list to the last for (auto it = list.begin(); it != list.end(); ++it) cout << *it << " "; // unique operation on list with parameter list.unique(compare); cout << "\nList is: "; // starts from the first element // of the list to the last for (auto it = list.begin(); it != list.end(); ++it) cout << *it << " "; return 0;} List is: 2.55 3.15 4.16 4.77 12.65 13.59 List is: 2.55 3.15 4.16 12.65 13.59 syvs pk1853894 CPP-Functions cpp-list STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ C++ Classes and Objects Bitwise Operators in C/C++ Virtual Function in C++ Templates in C++ with Examples Constructors in C++ Operator Overloading in C++ Socket Programming in C/C++ Object Oriented Programming in C++ Copy Constructor in C++
[ { "code": null, "e": 25923, "s": 25895, "text": "\n04 Feb, 2021" }, { "code": null, "e": 26066, "s": 25923, "text": "list::unique() is an inbuilt function in C++ STL which removes all duplicate consecutive elements from the list. It works only on sorted list." }, { "code": null, "e": 26075, "s": 26066, "text": "Syntax: " }, { "code": null, "e": 26114, "s": 26075, "text": "list_name.unique(BinaryPredicate name)" }, { "code": null, "e": 26296, "s": 26114, "text": "Parameters: The function accepts a single and optional parameter which is a binary predicate that returns true if the elements should be treated as equal. It has following syntax: " }, { "code": null, "e": 26333, "s": 26296, "text": "bool name(data_type a, data_type b);" }, { "code": null, "e": 26387, "s": 26333, "text": "Return value: This function does not return anything." }, { "code": null, "e": 26435, "s": 26387, "text": "Below is the implementation of above function: " }, { "code": null, "e": 26439, "s": 26435, "text": "CPP" }, { "code": "// C++ program to illustrate the// unique() function#include <bits/stdc++.h>using namespace std; // Function for binary_predicatebool compare(double a, double b){ return ((int)a == (int)b);} // Driver codeint main(){ list<double> list = { 2.55, 3.15, 4.16, 4.16, 4.77, 12.65, 12.65, 13.59 }; cout << \"List is: \"; //sort the list list.sort(); // unique operation on list with no parameters list.unique(); // starts from the first element // of the list to the last for (auto it = list.begin(); it != list.end(); ++it) cout << *it << \" \"; // unique operation on list with parameter list.unique(compare); cout << \"\\nList is: \"; // starts from the first element // of the list to the last for (auto it = list.begin(); it != list.end(); ++it) cout << *it << \" \"; return 0;}", "e": 27312, "s": 26439, "text": null }, { "code": null, "e": 27391, "s": 27312, "text": "List is: 2.55 3.15 4.16 4.77 12.65 13.59 \nList is: 2.55 3.15 4.16 12.65 13.59 " }, { "code": null, "e": 27396, "s": 27391, "text": "syvs" }, { "code": null, "e": 27406, "s": 27396, "text": "pk1853894" }, { "code": null, "e": 27420, "s": 27406, "text": "CPP-Functions" }, { "code": null, "e": 27429, "s": 27420, "text": "cpp-list" }, { "code": null, "e": 27433, "s": 27429, "text": "STL" }, { "code": null, "e": 27437, "s": 27433, "text": "C++" }, { "code": null, "e": 27441, "s": 27437, "text": "STL" }, { "code": null, "e": 27445, "s": 27441, "text": "CPP" }, { "code": null, "e": 27543, "s": 27445, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27562, "s": 27543, "text": "Inheritance in C++" }, { "code": null, "e": 27586, "s": 27562, "text": "C++ Classes and Objects" }, { "code": null, "e": 27613, "s": 27586, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 27637, "s": 27613, "text": "Virtual Function in C++" }, { "code": null, "e": 27668, "s": 27637, "text": "Templates in C++ with Examples" }, { "code": null, "e": 27688, "s": 27668, "text": "Constructors in C++" }, { "code": null, "e": 27716, "s": 27688, "text": "Operator Overloading in C++" }, { "code": null, "e": 27744, "s": 27716, "text": "Socket Programming in C/C++" }, { "code": null, "e": 27779, "s": 27744, "text": "Object Oriented Programming in C++" } ]
Python VLC Instance - Enumerate the defined audio output devices - GeeksforGeeks
29 Aug, 2020 In this article we will see how we can get the enumerate audio output devices from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we can create media player, list player or any other player available in VLC. Instance class the base classed used in VLC to create various objects. These audio devices can be speaker or headphone as well. In order to do this we will use audio_output_enumerate_devices method with the Instance object Syntax : instance.audio_output_enumerate_devices() Argument : It takes no argument Return : It returns list of dict Below is the implementation # importing vlc moduleimport vlc # importing time moduleimport time # creating Instance class objectplayer = vlc.Instance() # creating a new media listmedia_list = player.media_list_new() # creating a media player objectmedia_player = player.media_list_player_new() # creating a new mediamedia = player.media_new("death_note.mkv") # adding media to media listmedia_list.add_media(media) # setting media list to the mediaplayermedia_player.set_media_list(media_list) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) # getting audio enumerate devicesvalue = player.audio_output_enumerate_devices() # printing valueprint(value) Output : [{'name': b'adummy', 'description': b'Dummy audio output'}, {'name': b'afile', 'description': b'File audio output'}, {'name': b'amem', 'description': b'Audio memory output'}, {'name': b'directsound', 'description': b'DirectX audio output'}, {'name': b'mmdevice', 'description': b'Windows Multimedia Device output'}, {'name': b'waveout', 'description': b'WaveOut audio output'}] Another exampleBelow is the implementation # importing vlc moduleimport vlc # importing time moduleimport time # creating Instance class objectplayer = vlc.Instance() # creating a new media listmedia_list = player.media_list_new() # creating a media player objectmedia_player = player.media_list_player_new() # creating a new mediamedia = player.media_new("1.mp4") # adding media to media listmedia_list.add_media(media) # setting media list to the mediaplayermedia_player.set_media_list(media_list) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) # getting audio enumerate devicesvalue = player.audio_output_enumerate_devices() # printing valueprint(value) Output : [{'name': b'adummy', 'description': b'Dummy audio output'}, {'name': b'afile', 'description': b'File audio output'}, {'name': b'amem', 'description': b'Audio memory output'}, {'name': b'directsound', 'description': b'DirectX audio output'}, {'name': b'mmdevice', 'description': b'Windows Multimedia Device output'}, {'name': b'waveout', 'description': b'WaveOut audio output'}] Python vlc-library Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python
[ { "code": null, "e": 25493, "s": 25465, "text": "\n29 Aug, 2020" }, { "code": null, "e": 26052, "s": 25493, "text": "In this article we will see how we can get the enumerate audio output devices from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we can create media player, list player or any other player available in VLC. Instance class the base classed used in VLC to create various objects. These audio devices can be speaker or headphone as well." }, { "code": null, "e": 26147, "s": 26052, "text": "In order to do this we will use audio_output_enumerate_devices method with the Instance object" }, { "code": null, "e": 26198, "s": 26147, "text": "Syntax : instance.audio_output_enumerate_devices()" }, { "code": null, "e": 26230, "s": 26198, "text": "Argument : It takes no argument" }, { "code": null, "e": 26263, "s": 26230, "text": "Return : It returns list of dict" }, { "code": null, "e": 26291, "s": 26263, "text": "Below is the implementation" }, { "code": "# importing vlc moduleimport vlc # importing time moduleimport time # creating Instance class objectplayer = vlc.Instance() # creating a new media listmedia_list = player.media_list_new() # creating a media player objectmedia_player = player.media_list_player_new() # creating a new mediamedia = player.media_new(\"death_note.mkv\") # adding media to media listmedia_list.add_media(media) # setting media list to the mediaplayermedia_player.set_media_list(media_list) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) # getting audio enumerate devicesvalue = player.audio_output_enumerate_devices() # printing valueprint(value)", "e": 27018, "s": 26291, "text": null }, { "code": null, "e": 27027, "s": 27018, "text": "Output :" }, { "code": null, "e": 27406, "s": 27027, "text": "[{'name': b'adummy', 'description': b'Dummy audio output'}, {'name': b'afile', 'description': b'File audio output'}, {'name': b'amem', 'description': b'Audio memory output'}, {'name': b'directsound', 'description': b'DirectX audio output'}, {'name': b'mmdevice', 'description': b'Windows Multimedia Device output'}, {'name': b'waveout', 'description': b'WaveOut audio output'}]\n" }, { "code": null, "e": 27449, "s": 27406, "text": "Another exampleBelow is the implementation" }, { "code": "# importing vlc moduleimport vlc # importing time moduleimport time # creating Instance class objectplayer = vlc.Instance() # creating a new media listmedia_list = player.media_list_new() # creating a media player objectmedia_player = player.media_list_player_new() # creating a new mediamedia = player.media_new(\"1.mp4\") # adding media to media listmedia_list.add_media(media) # setting media list to the mediaplayermedia_player.set_media_list(media_list) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) # getting audio enumerate devicesvalue = player.audio_output_enumerate_devices() # printing valueprint(value)", "e": 28167, "s": 27449, "text": null }, { "code": null, "e": 28176, "s": 28167, "text": "Output :" }, { "code": null, "e": 28555, "s": 28176, "text": "[{'name': b'adummy', 'description': b'Dummy audio output'}, {'name': b'afile', 'description': b'File audio output'}, {'name': b'amem', 'description': b'Audio memory output'}, {'name': b'directsound', 'description': b'DirectX audio output'}, {'name': b'mmdevice', 'description': b'Windows Multimedia Device output'}, {'name': b'waveout', 'description': b'WaveOut audio output'}]\n" }, { "code": null, "e": 28574, "s": 28555, "text": "Python vlc-library" }, { "code": null, "e": 28581, "s": 28574, "text": "Python" }, { "code": null, "e": 28679, "s": 28581, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28711, "s": 28679, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28733, "s": 28711, "text": "Enumerate() in Python" }, { "code": null, "e": 28775, "s": 28733, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28805, "s": 28775, "text": "Iterate over a list in Python" }, { "code": null, "e": 28831, "s": 28805, "text": "Python String | replace()" }, { "code": null, "e": 28860, "s": 28831, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28904, "s": 28860, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28941, "s": 28904, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28977, "s": 28941, "text": "Convert integer to string in Python" } ]
SQL | Date functions - GeeksforGeeks
03 Sep, 2021 In SQL, dates are complicated for newbies, since while working with database, the format of the date in table must be matched with the input date in order to insert. In various scenarios instead of date, datetime (time is also involved with date) is used.In MySql the default date functions are: NOW(): Returns the current date and time. Example:SELECT NOW(); Output:2017-01-13 08:03:52 SELECT NOW(); Output: 2017-01-13 08:03:52 CURDATE(): Returns the current date. Example:SELECT CURDATE(); Output:2017-01-13 SELECT CURDATE(); Output: 2017-01-13 CURTIME(): Returns the current time. Example:SELECT CURTIME(); Output:08:05:15 SELECT CURTIME(); Output: 08:05:15 DATE(): Extracts the date part of a date or date/time expression. Example:For the below table named ‘Test’IdNameBirthTime4120Pratik1996-09-26 16:44:15.581SELECT Name, DATE(BirthTime) AS BirthDate FROM Test; Output:NameBirthDatePratik1996-09-26 SELECT Name, DATE(BirthTime) AS BirthDate FROM Test; Output: EXTRACT(): Returns a single part of a date/time. Syntax:EXTRACT(unit FROM date); There are several units that can be considered but only some are used such as:MICROSECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR, etc.And ‘date’ is a valid date expression.Example:For the below table named ‘Test’IdNameBirthTime4120Pratik1996-09-26 16:44:15.581QueriesSELECT Name, Extract(DAY FROM BirthTime) AS BirthDay FROM Test; Output:NameBirthDayPratik26SELECT Name, Extract(YEAR FROM BirthTime) AS BirthYear FROM Test; Output:NameBirthYearPratik1996SELECT Name, Extract(SECOND FROM BirthTime) AS BirthSecond FROM Test; Output:NameBirthSecondPratik581 EXTRACT(unit FROM date); There are several units that can be considered but only some are used such as:MICROSECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR, etc.And ‘date’ is a valid date expression. Example:For the below table named ‘Test’ Queries SELECT Name, Extract(DAY FROM BirthTime) AS BirthDay FROM Test; Output:NameBirthDayPratik26 SELECT Name, Extract(DAY FROM BirthTime) AS BirthDay FROM Test; Output: SELECT Name, Extract(YEAR FROM BirthTime) AS BirthYear FROM Test; Output:NameBirthYearPratik1996 SELECT Name, Extract(YEAR FROM BirthTime) AS BirthYear FROM Test; Output: SELECT Name, Extract(SECOND FROM BirthTime) AS BirthSecond FROM Test; Output:NameBirthSecondPratik581 SELECT Name, Extract(SECOND FROM BirthTime) AS BirthSecond FROM Test; Output: DATE_ADD() : Adds a specified time interval to a dateSyntax:DATE_ADD(date, INTERVAL expr type); Where, date – valid date expression and expr is the number of interval we want to add.and type can be one of the following:MICROSECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR, etc.Example:For the below table named ‘Test’IdNameBirthTime4120Pratik1996-09-26 16:44:15.581QueriesSELECT Name, DATE_ADD(BirthTime, INTERVAL 1 YEAR) AS BirthTimeModified FROM Test; Output:NameBirthTimeModifiedPratik1997-09-26 16:44:15.581SELECT Name, DATE_ADD(BirthTime, INTERVAL 30 DAY) AS BirthDayModified FROM Test; Output:NameBirthDayModifiedPratik1996-10-26 16:44:15.581SELECT Name, DATE_ADD(BirthTime, INTERVAL 4 HOUR) AS BirthHourModified FROM Test; Output:NameBirthSecondPratik1996-10-26 20:44:15.581 DATE_ADD(date, INTERVAL expr type); Where, date – valid date expression and expr is the number of interval we want to add.and type can be one of the following:MICROSECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR, etc. Example:For the below table named ‘Test’ Queries SELECT Name, DATE_ADD(BirthTime, INTERVAL 1 YEAR) AS BirthTimeModified FROM Test; Output:NameBirthTimeModifiedPratik1997-09-26 16:44:15.581 SELECT Name, DATE_ADD(BirthTime, INTERVAL 1 YEAR) AS BirthTimeModified FROM Test; Output: SELECT Name, DATE_ADD(BirthTime, INTERVAL 30 DAY) AS BirthDayModified FROM Test; Output:NameBirthDayModifiedPratik1996-10-26 16:44:15.581 SELECT Name, DATE_ADD(BirthTime, INTERVAL 30 DAY) AS BirthDayModified FROM Test; Output: SELECT Name, DATE_ADD(BirthTime, INTERVAL 4 HOUR) AS BirthHourModified FROM Test; Output:NameBirthSecondPratik1996-10-26 20:44:15.581 SELECT Name, DATE_ADD(BirthTime, INTERVAL 4 HOUR) AS BirthHourModified FROM Test; Output: DATE_SUB(): Subtracts a specified time interval from a date. Syntax for DATE_SUB is same as DATE_ADD just the difference is that DATE_SUB is used to subtract a given interval of date. DATEDIFF(): Returns the number of days between two dates.Syntax:DATEDIFF(date1, date2); date1 & date2- date/time expression Example:SELECT DATEDIFF('2017-01-13','2017-01-03') AS DateDiff; Output:DateDiff10 DATEDIFF(date1, date2); date1 & date2- date/time expression Example: SELECT DATEDIFF('2017-01-13','2017-01-03') AS DateDiff; Output: DATE_FORMAT(): Displays date/time data in different formats.Syntax:DATE_FORMAT(date,format); date is a valid date and format specifies the output format for the date/time. The formats that can be used are:%a-Abbreviated weekday name (Sun-Sat)%b-Abbreviated month name (Jan-Dec)%c-Month, numeric (0-12)%D-Day of month with English suffix (0th, 1st, 2nd, 3rd)%d-Day of month, numeric (00-31)%e-Day of month, numeric (0-31)%f-Microseconds (000000-999999)%H-Hour (00-23)%h-Hour (01-12)%I-Hour (01-12)%i-Minutes, numeric (00-59)%j-Day of year (001-366)%k-Hour (0-23)%l-Hour (1-12)%M-Month name (January-December)%m-Month, numeric (00-12)%p-AM or PM%r-Time, 12-hour (hh:mm:ss followed by AM or PM)%S-Seconds (00-59)%s-Seconds (00-59)%T-Time, 24-hour (hh:mm:ss)%U-Week (00-53) where Sunday is the first day of week%u-Week (00-53) where Monday is the first day of week%V-Week (01-53) where Sunday is the first day of week, used with %X%v-Week (01-53) where Monday is the first day of week, used with %x%W-Weekday name (Sunday-Saturday)%w-Day of the week (0=Sunday, 6=Saturday)%X-Year for the week where Sunday is the first day of week, four digits, used with %V%x-Year for the week where Monday is the first day of week, four digits, used with %v%Y-Year, numeric, four digits%y-Year, numeric, two digitsExample:DATE_FORMAT(NOW(),'%d %b %y') Result:13 Jan 17 DATE_FORMAT(date,format); date is a valid date and format specifies the output format for the date/time. The formats that can be used are: %a-Abbreviated weekday name (Sun-Sat) %b-Abbreviated month name (Jan-Dec) %c-Month, numeric (0-12) %D-Day of month with English suffix (0th, 1st, 2nd, 3rd) %d-Day of month, numeric (00-31) %e-Day of month, numeric (0-31) %f-Microseconds (000000-999999) %H-Hour (00-23) %h-Hour (01-12) %I-Hour (01-12) %i-Minutes, numeric (00-59) %j-Day of year (001-366) %k-Hour (0-23) %l-Hour (1-12) %M-Month name (January-December) %m-Month, numeric (00-12) %p-AM or PM %r-Time, 12-hour (hh:mm:ss followed by AM or PM) %S-Seconds (00-59) %s-Seconds (00-59) %T-Time, 24-hour (hh:mm:ss) %U-Week (00-53) where Sunday is the first day of week %u-Week (00-53) where Monday is the first day of week %V-Week (01-53) where Sunday is the first day of week, used with %X %v-Week (01-53) where Monday is the first day of week, used with %x %W-Weekday name (Sunday-Saturday) %w-Day of the week (0=Sunday, 6=Saturday) %X-Year for the week where Sunday is the first day of week, four digits, used with %V %x-Year for the week where Monday is the first day of week, four digits, used with %v %Y-Year, numeric, four digits %y-Year, numeric, two digits Example: DATE_FORMAT(NOW(),'%d %b %y') Result: 13 Jan 17 This article is contributed by Pratik Agarwal. 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. rumble_fool allenben SQL-Functions Articles DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to write a Pseudo Code? Analysis of Algorithms | Set 1 (Asymptotic Analysis) SQL Interview Questions Understanding "extern" keyword in C Analysis of Algorithms | Set 3 (Asymptotic Notations) ACID Properties in DBMS SQL query to find second highest salary? Normal Forms in DBMS SQL Interview Questions Introduction of B-Tree
[ { "code": null, "e": 25378, "s": 25350, "text": "\n03 Sep, 2021" }, { "code": null, "e": 25674, "s": 25378, "text": "In SQL, dates are complicated for newbies, since while working with database, the format of the date in table must be matched with the input date in order to insert. In various scenarios instead of date, datetime (time is also involved with date) is used.In MySql the default date functions are:" }, { "code": null, "e": 25766, "s": 25674, "text": "NOW(): Returns the current date and time. Example:SELECT NOW();\nOutput:2017-01-13 08:03:52\n" }, { "code": null, "e": 25781, "s": 25766, "text": "SELECT NOW();\n" }, { "code": null, "e": 25789, "s": 25781, "text": "Output:" }, { "code": null, "e": 25810, "s": 25789, "text": "2017-01-13 08:03:52\n" }, { "code": null, "e": 25892, "s": 25810, "text": "CURDATE(): Returns the current date. Example:SELECT CURDATE();\nOutput:2017-01-13\n" }, { "code": null, "e": 25911, "s": 25892, "text": "SELECT CURDATE();\n" }, { "code": null, "e": 25919, "s": 25911, "text": "Output:" }, { "code": null, "e": 25931, "s": 25919, "text": "2017-01-13\n" }, { "code": null, "e": 26011, "s": 25931, "text": "CURTIME(): Returns the current time. Example:SELECT CURTIME();\nOutput:08:05:15\n" }, { "code": null, "e": 26030, "s": 26011, "text": "SELECT CURTIME();\n" }, { "code": null, "e": 26038, "s": 26030, "text": "Output:" }, { "code": null, "e": 26048, "s": 26038, "text": "08:05:15\n" }, { "code": null, "e": 26292, "s": 26048, "text": "DATE(): Extracts the date part of a date or date/time expression. Example:For the below table named ‘Test’IdNameBirthTime4120Pratik1996-09-26 16:44:15.581SELECT Name, DATE(BirthTime) AS BirthDate FROM Test;\nOutput:NameBirthDatePratik1996-09-26" }, { "code": null, "e": 26346, "s": 26292, "text": "SELECT Name, DATE(BirthTime) AS BirthDate FROM Test;\n" }, { "code": null, "e": 26354, "s": 26346, "text": "Output:" }, { "code": null, "e": 27007, "s": 26354, "text": "EXTRACT(): Returns a single part of a date/time. Syntax:EXTRACT(unit FROM date);\nThere are several units that can be considered but only some are used such as:MICROSECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR, etc.And ‘date’ is a valid date expression.Example:For the below table named ‘Test’IdNameBirthTime4120Pratik1996-09-26 16:44:15.581QueriesSELECT Name, Extract(DAY FROM BirthTime) AS BirthDay FROM Test;\nOutput:NameBirthDayPratik26SELECT Name, Extract(YEAR FROM BirthTime) AS BirthYear FROM Test;\nOutput:NameBirthYearPratik1996SELECT Name, Extract(SECOND FROM BirthTime) AS BirthSecond FROM Test;\nOutput:NameBirthSecondPratik581" }, { "code": null, "e": 27033, "s": 27007, "text": "EXTRACT(unit FROM date);\n" }, { "code": null, "e": 27222, "s": 27033, "text": "There are several units that can be considered but only some are used such as:MICROSECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR, etc.And ‘date’ is a valid date expression." }, { "code": null, "e": 27263, "s": 27222, "text": "Example:For the below table named ‘Test’" }, { "code": null, "e": 27271, "s": 27263, "text": "Queries" }, { "code": null, "e": 27363, "s": 27271, "text": "SELECT Name, Extract(DAY FROM BirthTime) AS BirthDay FROM Test;\nOutput:NameBirthDayPratik26" }, { "code": null, "e": 27428, "s": 27363, "text": "SELECT Name, Extract(DAY FROM BirthTime) AS BirthDay FROM Test;\n" }, { "code": null, "e": 27436, "s": 27428, "text": "Output:" }, { "code": null, "e": 27533, "s": 27436, "text": "SELECT Name, Extract(YEAR FROM BirthTime) AS BirthYear FROM Test;\nOutput:NameBirthYearPratik1996" }, { "code": null, "e": 27600, "s": 27533, "text": "SELECT Name, Extract(YEAR FROM BirthTime) AS BirthYear FROM Test;\n" }, { "code": null, "e": 27608, "s": 27600, "text": "Output:" }, { "code": null, "e": 27710, "s": 27608, "text": "SELECT Name, Extract(SECOND FROM BirthTime) AS BirthSecond FROM Test;\nOutput:NameBirthSecondPratik581" }, { "code": null, "e": 27781, "s": 27710, "text": "SELECT Name, Extract(SECOND FROM BirthTime) AS BirthSecond FROM Test;\n" }, { "code": null, "e": 27789, "s": 27781, "text": "Output:" }, { "code": null, "e": 28586, "s": 27789, "text": "DATE_ADD() : Adds a specified time interval to a dateSyntax:DATE_ADD(date, INTERVAL expr type);\nWhere, date – valid date expression and expr is the number of interval we want to add.and type can be one of the following:MICROSECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR, etc.Example:For the below table named ‘Test’IdNameBirthTime4120Pratik1996-09-26 16:44:15.581QueriesSELECT Name, DATE_ADD(BirthTime, INTERVAL 1 YEAR) AS BirthTimeModified FROM Test;\nOutput:NameBirthTimeModifiedPratik1997-09-26 16:44:15.581SELECT Name, DATE_ADD(BirthTime, INTERVAL 30 DAY) AS BirthDayModified FROM Test;\nOutput:NameBirthDayModifiedPratik1996-10-26 16:44:15.581SELECT Name, DATE_ADD(BirthTime, INTERVAL 4 HOUR) AS BirthHourModified FROM Test;\nOutput:NameBirthSecondPratik1996-10-26 20:44:15.581" }, { "code": null, "e": 28623, "s": 28586, "text": "DATE_ADD(date, INTERVAL expr type);\n" }, { "code": null, "e": 28820, "s": 28623, "text": "Where, date – valid date expression and expr is the number of interval we want to add.and type can be one of the following:MICROSECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR, etc." }, { "code": null, "e": 28861, "s": 28820, "text": "Example:For the below table named ‘Test’" }, { "code": null, "e": 28869, "s": 28861, "text": "Queries" }, { "code": null, "e": 29009, "s": 28869, "text": "SELECT Name, DATE_ADD(BirthTime, INTERVAL 1 YEAR) AS BirthTimeModified FROM Test;\nOutput:NameBirthTimeModifiedPratik1997-09-26 16:44:15.581" }, { "code": null, "e": 29092, "s": 29009, "text": "SELECT Name, DATE_ADD(BirthTime, INTERVAL 1 YEAR) AS BirthTimeModified FROM Test;\n" }, { "code": null, "e": 29100, "s": 29092, "text": "Output:" }, { "code": null, "e": 29238, "s": 29100, "text": "SELECT Name, DATE_ADD(BirthTime, INTERVAL 30 DAY) AS BirthDayModified FROM Test;\nOutput:NameBirthDayModifiedPratik1996-10-26 16:44:15.581" }, { "code": null, "e": 29320, "s": 29238, "text": "SELECT Name, DATE_ADD(BirthTime, INTERVAL 30 DAY) AS BirthDayModified FROM Test;\n" }, { "code": null, "e": 29328, "s": 29320, "text": "Output:" }, { "code": null, "e": 29462, "s": 29328, "text": "SELECT Name, DATE_ADD(BirthTime, INTERVAL 4 HOUR) AS BirthHourModified FROM Test;\nOutput:NameBirthSecondPratik1996-10-26 20:44:15.581" }, { "code": null, "e": 29545, "s": 29462, "text": "SELECT Name, DATE_ADD(BirthTime, INTERVAL 4 HOUR) AS BirthHourModified FROM Test;\n" }, { "code": null, "e": 29553, "s": 29545, "text": "Output:" }, { "code": null, "e": 29737, "s": 29553, "text": "DATE_SUB(): Subtracts a specified time interval from a date. Syntax for DATE_SUB is same as DATE_ADD just the difference is that DATE_SUB is used to subtract a given interval of date." }, { "code": null, "e": 29943, "s": 29737, "text": "DATEDIFF(): Returns the number of days between two dates.Syntax:DATEDIFF(date1, date2);\ndate1 & date2- date/time expression\nExample:SELECT DATEDIFF('2017-01-13','2017-01-03') AS DateDiff;\nOutput:DateDiff10" }, { "code": null, "e": 30004, "s": 29943, "text": "DATEDIFF(date1, date2);\ndate1 & date2- date/time expression\n" }, { "code": null, "e": 30013, "s": 30004, "text": "Example:" }, { "code": null, "e": 30070, "s": 30013, "text": "SELECT DATEDIFF('2017-01-13','2017-01-03') AS DateDiff;\n" }, { "code": null, "e": 30078, "s": 30070, "text": "Output:" }, { "code": null, "e": 31429, "s": 30078, "text": "DATE_FORMAT(): Displays date/time data in different formats.Syntax:DATE_FORMAT(date,format);\ndate is a valid date and format specifies the output format for the date/time. The formats that can be used are:%a-Abbreviated weekday name (Sun-Sat)%b-Abbreviated month name (Jan-Dec)%c-Month, numeric (0-12)%D-Day of month with English suffix (0th, 1st, 2nd, 3rd)%d-Day of month, numeric (00-31)%e-Day of month, numeric (0-31)%f-Microseconds (000000-999999)%H-Hour (00-23)%h-Hour (01-12)%I-Hour (01-12)%i-Minutes, numeric (00-59)%j-Day of year (001-366)%k-Hour (0-23)%l-Hour (1-12)%M-Month name (January-December)%m-Month, numeric (00-12)%p-AM or PM%r-Time, 12-hour (hh:mm:ss followed by AM or PM)%S-Seconds (00-59)%s-Seconds (00-59)%T-Time, 24-hour (hh:mm:ss)%U-Week (00-53) where Sunday is the first day of week%u-Week (00-53) where Monday is the first day of week%V-Week (01-53) where Sunday is the first day of week, used with %X%v-Week (01-53) where Monday is the first day of week, used with %x%W-Weekday name (Sunday-Saturday)%w-Day of the week (0=Sunday, 6=Saturday)%X-Year for the week where Sunday is the first day of week, four digits, used with %V%x-Year for the week where Monday is the first day of week, four digits, used with %v%Y-Year, numeric, four digits%y-Year, numeric, two digitsExample:DATE_FORMAT(NOW(),'%d %b %y')\nResult:13 Jan 17\n" }, { "code": null, "e": 31456, "s": 31429, "text": "DATE_FORMAT(date,format);\n" }, { "code": null, "e": 31569, "s": 31456, "text": "date is a valid date and format specifies the output format for the date/time. The formats that can be used are:" }, { "code": null, "e": 31607, "s": 31569, "text": "%a-Abbreviated weekday name (Sun-Sat)" }, { "code": null, "e": 31643, "s": 31607, "text": "%b-Abbreviated month name (Jan-Dec)" }, { "code": null, "e": 31668, "s": 31643, "text": "%c-Month, numeric (0-12)" }, { "code": null, "e": 31725, "s": 31668, "text": "%D-Day of month with English suffix (0th, 1st, 2nd, 3rd)" }, { "code": null, "e": 31758, "s": 31725, "text": "%d-Day of month, numeric (00-31)" }, { "code": null, "e": 31790, "s": 31758, "text": "%e-Day of month, numeric (0-31)" }, { "code": null, "e": 31822, "s": 31790, "text": "%f-Microseconds (000000-999999)" }, { "code": null, "e": 31838, "s": 31822, "text": "%H-Hour (00-23)" }, { "code": null, "e": 31854, "s": 31838, "text": "%h-Hour (01-12)" }, { "code": null, "e": 31870, "s": 31854, "text": "%I-Hour (01-12)" }, { "code": null, "e": 31898, "s": 31870, "text": "%i-Minutes, numeric (00-59)" }, { "code": null, "e": 31923, "s": 31898, "text": "%j-Day of year (001-366)" }, { "code": null, "e": 31938, "s": 31923, "text": "%k-Hour (0-23)" }, { "code": null, "e": 31953, "s": 31938, "text": "%l-Hour (1-12)" }, { "code": null, "e": 31986, "s": 31953, "text": "%M-Month name (January-December)" }, { "code": null, "e": 32012, "s": 31986, "text": "%m-Month, numeric (00-12)" }, { "code": null, "e": 32024, "s": 32012, "text": "%p-AM or PM" }, { "code": null, "e": 32073, "s": 32024, "text": "%r-Time, 12-hour (hh:mm:ss followed by AM or PM)" }, { "code": null, "e": 32092, "s": 32073, "text": "%S-Seconds (00-59)" }, { "code": null, "e": 32111, "s": 32092, "text": "%s-Seconds (00-59)" }, { "code": null, "e": 32139, "s": 32111, "text": "%T-Time, 24-hour (hh:mm:ss)" }, { "code": null, "e": 32193, "s": 32139, "text": "%U-Week (00-53) where Sunday is the first day of week" }, { "code": null, "e": 32247, "s": 32193, "text": "%u-Week (00-53) where Monday is the first day of week" }, { "code": null, "e": 32315, "s": 32247, "text": "%V-Week (01-53) where Sunday is the first day of week, used with %X" }, { "code": null, "e": 32383, "s": 32315, "text": "%v-Week (01-53) where Monday is the first day of week, used with %x" }, { "code": null, "e": 32417, "s": 32383, "text": "%W-Weekday name (Sunday-Saturday)" }, { "code": null, "e": 32459, "s": 32417, "text": "%w-Day of the week (0=Sunday, 6=Saturday)" }, { "code": null, "e": 32545, "s": 32459, "text": "%X-Year for the week where Sunday is the first day of week, four digits, used with %V" }, { "code": null, "e": 32631, "s": 32545, "text": "%x-Year for the week where Monday is the first day of week, four digits, used with %v" }, { "code": null, "e": 32661, "s": 32631, "text": "%Y-Year, numeric, four digits" }, { "code": null, "e": 32690, "s": 32661, "text": "%y-Year, numeric, two digits" }, { "code": null, "e": 32699, "s": 32690, "text": "Example:" }, { "code": null, "e": 32730, "s": 32699, "text": "DATE_FORMAT(NOW(),'%d %b %y')\n" }, { "code": null, "e": 32738, "s": 32730, "text": "Result:" }, { "code": null, "e": 32749, "s": 32738, "text": "13 Jan 17\n" }, { "code": null, "e": 33047, "s": 32749, "text": "This article is contributed by Pratik Agarwal. 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." }, { "code": null, "e": 33172, "s": 33047, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 33184, "s": 33172, "text": "rumble_fool" }, { "code": null, "e": 33193, "s": 33184, "text": "allenben" }, { "code": null, "e": 33207, "s": 33193, "text": "SQL-Functions" }, { "code": null, "e": 33216, "s": 33207, "text": "Articles" }, { "code": null, "e": 33221, "s": 33216, "text": "DBMS" }, { "code": null, "e": 33225, "s": 33221, "text": "SQL" }, { "code": null, "e": 33230, "s": 33225, "text": "DBMS" }, { "code": null, "e": 33234, "s": 33230, "text": "SQL" }, { "code": null, "e": 33332, "s": 33234, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33360, "s": 33332, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 33413, "s": 33360, "text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)" }, { "code": null, "e": 33437, "s": 33413, "text": "SQL Interview Questions" }, { "code": null, "e": 33473, "s": 33437, "text": "Understanding \"extern\" keyword in C" }, { "code": null, "e": 33527, "s": 33473, "text": "Analysis of Algorithms | Set 3 (Asymptotic Notations)" }, { "code": null, "e": 33551, "s": 33527, "text": "ACID Properties in DBMS" }, { "code": null, "e": 33592, "s": 33551, "text": "SQL query to find second highest salary?" }, { "code": null, "e": 33613, "s": 33592, "text": "Normal Forms in DBMS" }, { "code": null, "e": 33637, "s": 33613, "text": "SQL Interview Questions" } ]
Calculate speed, distance and time - GeeksforGeeks
11 Mar, 2022 When an object moves in a straight line at a steady speed, we can calculate its speed if we know how far it travels and how long it takes. This equation shows the relationship between speed, distance traveled and time taken: Speed is distance divided by the time taken. For example, a car travels 30 kilometers in 2 hours. Its speed is 30 ÷ 2 = 15km/hr. Formula used : Distance = Speed * Time Time = Distance / Speed Speed = Distance / Time Examples: Input : distance(km) : 48.5 time(hr) : 2.6 Output : Speed(km / hr) : 18.653846153 Input : speed(km / hr) : 46.0 time(hr) : 3.2 Output : Distance(km) : 147.2 Input : distance(km) : 48.5 speed(km / hr) : 46.0 Output : Time(hr) : 1.0543 C++ Java Python3 C# PHP Javascript // C++ Program to calculate speed// distance and time#include<iostream>using namespace std; // Function to calculate speeddouble cal_speed(double dist, double time){ cout << "\n Distance(km) : " << dist ; cout << "\n Time(hr) : " << time ; return dist / time;} // Function to calculate distance traveleddouble cal_dis(double speed, double time){ cout << "\n Time(hr) : " << time ; cout << "\n Speed(km / hr) : " << speed ; return speed * time;} // Function to calculate time takendouble cal_time(double dist, double speed){ cout << "\n Distance(km) : "<< dist ; cout << "\n Speed(km / hr) : " << speed ; return dist / speed;} // Driver functionint main(){ // Calling function cal_speed() cout << "\n The calculated Speed(km / hr) is : " << cal_speed(45.9, 2.0 ) << endl ; // Calling function cal_dis() cout << "\n The calculated Distance(km) : " << cal_dis(62.9, 2.5) << endl ; // Calling function cal_time() cout << "\n The calculated Time(hr) : " << cal_time(48.0, 4.5) << endl ; return 0;} // Java Program to calculate speed// distance and time class GFG{ // Function to calculate speed static double cal_speed(double dist, double time) { System.out.print("\n Distance(km) : " + dist) ; System.out.print("\n Time(hr) : " + time) ; return dist / time; } // Function to calculate distance traveled static double cal_dis(double speed, double time) { System.out.print("\n Time(hr) : " + time) ; System.out.print("\n Speed(km / hr) : " + speed) ; return speed * time; } // Function to calculate time taken static double cal_time(double dist, double speed) { System.out.print("\n Distance(km) : "+ dist) ; System.out.print("\n Speed(km / hr) : " + speed) ; return dist / speed; } // Driver code public static void main (String[] args) { // Calling function cal_speed() System.out.println("\n The calculated Speed(km / hr) is : "+ cal_speed(45.9, 2.0 )); // Calling function cal_dis() System.out.println("\n The calculated Distance(km) : "+ cal_dis(62.9, 2.5)); // Calling function cal_time() System.out.println("\n The calculated Time(hr) : "+ cal_time(48.0, 4.5)); }} // This code is contributed by Anant Agarwal. # Python3 Program to calculate speed,# distance and time # Function to calculate speeddef cal_speed(dist, time): print(" Distance(km) :", dist); print(" Time(hr) :", time); return dist / time; # Function to calculate distance traveleddef cal_dis(speed, time): print(" Time(hr) :", time) ; print(" Speed(km / hr) :", speed); return speed * time; # Function to calculate time takendef cal_time(dist, speed): print(" Distance(km) :", dist); print(" Speed(km / hr) :", speed); return dist / speed; # Driver Code # Calling function cal_speed()print(" The calculated Speed(km / hr) is :", cal_speed(45.9, 2.0 ));print(""); # Calling function cal_dis()print(" The calculated Distance(km) :", cal_dis(62.9, 2.5));print(""); # Calling function cal_time()print(" The calculated Time(hr) :", cal_time(48.0, 4.5)); # This code is contributed# by mits // C# Program to calculate speed// distance and timeusing System; class GFG{ // Function to calculate speed static double cal_speed(double dist, double time) { Console.WriteLine(" Distance(km) : " + dist) ; Console.WriteLine(" Time(hr) : " + time) ; return dist / time; } // Function to calculate distance traveled static double cal_dis(double speed, double time) { Console.WriteLine(" Time(hr) : " + time) ; Console.WriteLine(" Speed(km / hr) : " + speed) ; return speed * time; } // Function to calculate time taken static double cal_time(double dist, double speed) { Console.WriteLine(" Distance(km) : "+ dist) ; Console.WriteLine(" Speed(km / hr) : " + speed) ; return dist / speed; } // Driver code public static void Main () { // Calling function cal_speed() Console.WriteLine(" The calculated Speed(km / hr) is : "+ cal_speed(45.9, 2.0 )); // Calling function cal_dis() Console.WriteLine(" The calculated Distance(km) : "+ cal_dis(62.9, 2.5)); // Calling function cal_time() Console.WriteLine(" The calculated Time(hr) : "+ cal_time(48.0, 4.5)); }} // This code is contributed by vt_m. <?php// PHP Program to calculate// speed distance and time // Function to calculate speedfunction cal_speed($dist, $time){echo "\n Distance(km) : " . $dist ;echo "\n Time(hr) : " . $time ; return $dist / $time;} // Function to calculate// distance traveledfunction cal_dis($speed, $time){echo "\n Time(hr) : " . $time ;echo "\n Speed(km / hr) : " . $speed ; return $speed * $time;} // Function to calculate// time takenfunction cal_time($dist, $speed){echo "\n Distance(km) : " . $dist ;echo "\n Speed(km / hr) : " . $speed ; return $dist / $speed ;} // Driver Code // Calling function cal_speed()echo " The calculated Speed(km / hr) is : ". cal_speed(45.9, 2.0 )."\n"; // Calling function cal_dis()echo "\n The calculated Distance(km) : ". cal_dis(62.9, 2.5)."\n"; // Calling function cal_time()echo "\n The calculated Time(hr) : ". cal_time(48.0, 4.5)."\n"; // This code is contributed// by mits?> <script> // Javascript Program to calculate speed// distance and time // Function to calculate speed function cal_speed( dist, time) { document.write(" Distance(km) : " + dist + "<br>" ) ; document.write(" Time(hr) : " + time + "<br>") ; return dist / time; } // Function to calculate distance traveled function cal_dis( speed, time) { document.write(" Time(hr) : " + time + "<br>" ) ; document.write(" Speed(km / hr) : " + speed + "<br>") ; return speed * time; } // Function to calculate time taken function cal_time( dist, speed) { document.write(" Distance(km) : " + dist + "<br>") ; document.write(" Speed(km / hr) : " + speed + "<br>" ) ; return dist / speed; } // Driver code // Calling function cal_speed() document.write(" The calculated Speed(km / hr) is : "+ cal_speed(45.9, 2.0 ) + "<br>"); document.write("<br>"); // Calling function cal_dis() document.write(" The calculated Distance(km) : "+ cal_dis(62.9, 2.5) + "<br>"); document.write("<br>"); // Calling function cal_time() document.write(" The calculated Time(hr) : "+ cal_time(48.0, 4.5) + "<br>"); </script> Output: Distance(km) : 45.9 Time(hr) : 2 The calculated Speed(km / hr) is : 22.95 Time(hr) : 2.5 Speed(km / hr) : 62.9 The calculated Distance(km) : 157.25 Distance(km) : 48 Speed(km / hr) : 4.5 The calculated Time(hr) : 10.6667 Mithun Kumar bunnyram19 atulkeshri Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Print all possible combinations of r elements in a given array of size n Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26085, "s": 26057, "text": "\n11 Mar, 2022" }, { "code": null, "e": 26456, "s": 26085, "text": "When an object moves in a straight line at a steady speed, we can calculate its speed if we know how far it travels and how long it takes. This equation shows the relationship between speed, distance traveled and time taken: Speed is distance divided by the time taken. For example, a car travels 30 kilometers in 2 hours. Its speed is 30 ÷ 2 = 15km/hr. Formula used : " }, { "code": null, "e": 26529, "s": 26456, "text": "Distance = Speed * Time\nTime = Distance / Speed\nSpeed = Distance / Time" }, { "code": null, "e": 26541, "s": 26529, "text": "Examples: " }, { "code": null, "e": 26780, "s": 26541, "text": "Input : distance(km) : 48.5 time(hr) : 2.6\nOutput : Speed(km / hr) : 18.653846153\n\nInput : speed(km / hr) : 46.0 time(hr) : 3.2\nOutput : Distance(km) : 147.2\n\nInput : distance(km) : 48.5 speed(km / hr) : 46.0\nOutput : Time(hr) : 1.0543" }, { "code": null, "e": 26788, "s": 26784, "text": "C++" }, { "code": null, "e": 26793, "s": 26788, "text": "Java" }, { "code": null, "e": 26801, "s": 26793, "text": "Python3" }, { "code": null, "e": 26804, "s": 26801, "text": "C#" }, { "code": null, "e": 26808, "s": 26804, "text": "PHP" }, { "code": null, "e": 26819, "s": 26808, "text": "Javascript" }, { "code": "// C++ Program to calculate speed// distance and time#include<iostream>using namespace std; // Function to calculate speeddouble cal_speed(double dist, double time){ cout << \"\\n Distance(km) : \" << dist ; cout << \"\\n Time(hr) : \" << time ; return dist / time;} // Function to calculate distance traveleddouble cal_dis(double speed, double time){ cout << \"\\n Time(hr) : \" << time ; cout << \"\\n Speed(km / hr) : \" << speed ; return speed * time;} // Function to calculate time takendouble cal_time(double dist, double speed){ cout << \"\\n Distance(km) : \"<< dist ; cout << \"\\n Speed(km / hr) : \" << speed ; return dist / speed;} // Driver functionint main(){ // Calling function cal_speed() cout << \"\\n The calculated Speed(km / hr) is : \" << cal_speed(45.9, 2.0 ) << endl ; // Calling function cal_dis() cout << \"\\n The calculated Distance(km) : \" << cal_dis(62.9, 2.5) << endl ; // Calling function cal_time() cout << \"\\n The calculated Time(hr) : \" << cal_time(48.0, 4.5) << endl ; return 0;}", "e": 27911, "s": 26819, "text": null }, { "code": "// Java Program to calculate speed// distance and time class GFG{ // Function to calculate speed static double cal_speed(double dist, double time) { System.out.print(\"\\n Distance(km) : \" + dist) ; System.out.print(\"\\n Time(hr) : \" + time) ; return dist / time; } // Function to calculate distance traveled static double cal_dis(double speed, double time) { System.out.print(\"\\n Time(hr) : \" + time) ; System.out.print(\"\\n Speed(km / hr) : \" + speed) ; return speed * time; } // Function to calculate time taken static double cal_time(double dist, double speed) { System.out.print(\"\\n Distance(km) : \"+ dist) ; System.out.print(\"\\n Speed(km / hr) : \" + speed) ; return dist / speed; } // Driver code public static void main (String[] args) { // Calling function cal_speed() System.out.println(\"\\n The calculated Speed(km / hr) is : \"+ cal_speed(45.9, 2.0 )); // Calling function cal_dis() System.out.println(\"\\n The calculated Distance(km) : \"+ cal_dis(62.9, 2.5)); // Calling function cal_time() System.out.println(\"\\n The calculated Time(hr) : \"+ cal_time(48.0, 4.5)); }} // This code is contributed by Anant Agarwal.", "e": 29316, "s": 27911, "text": null }, { "code": "# Python3 Program to calculate speed,# distance and time # Function to calculate speeddef cal_speed(dist, time): print(\" Distance(km) :\", dist); print(\" Time(hr) :\", time); return dist / time; # Function to calculate distance traveleddef cal_dis(speed, time): print(\" Time(hr) :\", time) ; print(\" Speed(km / hr) :\", speed); return speed * time; # Function to calculate time takendef cal_time(dist, speed): print(\" Distance(km) :\", dist); print(\" Speed(km / hr) :\", speed); return dist / speed; # Driver Code # Calling function cal_speed()print(\" The calculated Speed(km / hr) is :\", cal_speed(45.9, 2.0 ));print(\"\"); # Calling function cal_dis()print(\" The calculated Distance(km) :\", cal_dis(62.9, 2.5));print(\"\"); # Calling function cal_time()print(\" The calculated Time(hr) :\", cal_time(48.0, 4.5)); # This code is contributed# by mits", "e": 30233, "s": 29316, "text": null }, { "code": "// C# Program to calculate speed// distance and timeusing System; class GFG{ // Function to calculate speed static double cal_speed(double dist, double time) { Console.WriteLine(\" Distance(km) : \" + dist) ; Console.WriteLine(\" Time(hr) : \" + time) ; return dist / time; } // Function to calculate distance traveled static double cal_dis(double speed, double time) { Console.WriteLine(\" Time(hr) : \" + time) ; Console.WriteLine(\" Speed(km / hr) : \" + speed) ; return speed * time; } // Function to calculate time taken static double cal_time(double dist, double speed) { Console.WriteLine(\" Distance(km) : \"+ dist) ; Console.WriteLine(\" Speed(km / hr) : \" + speed) ; return dist / speed; } // Driver code public static void Main () { // Calling function cal_speed() Console.WriteLine(\" The calculated Speed(km / hr) is : \"+ cal_speed(45.9, 2.0 )); // Calling function cal_dis() Console.WriteLine(\" The calculated Distance(km) : \"+ cal_dis(62.9, 2.5)); // Calling function cal_time() Console.WriteLine(\" The calculated Time(hr) : \"+ cal_time(48.0, 4.5)); }} // This code is contributed by vt_m.", "e": 31608, "s": 30233, "text": null }, { "code": "<?php// PHP Program to calculate// speed distance and time // Function to calculate speedfunction cal_speed($dist, $time){echo \"\\n Distance(km) : \" . $dist ;echo \"\\n Time(hr) : \" . $time ; return $dist / $time;} // Function to calculate// distance traveledfunction cal_dis($speed, $time){echo \"\\n Time(hr) : \" . $time ;echo \"\\n Speed(km / hr) : \" . $speed ; return $speed * $time;} // Function to calculate// time takenfunction cal_time($dist, $speed){echo \"\\n Distance(km) : \" . $dist ;echo \"\\n Speed(km / hr) : \" . $speed ; return $dist / $speed ;} // Driver Code // Calling function cal_speed()echo \" The calculated Speed(km / hr) is : \". cal_speed(45.9, 2.0 ).\"\\n\"; // Calling function cal_dis()echo \"\\n The calculated Distance(km) : \". cal_dis(62.9, 2.5).\"\\n\"; // Calling function cal_time()echo \"\\n The calculated Time(hr) : \". cal_time(48.0, 4.5).\"\\n\"; // This code is contributed// by mits?>", "e": 32577, "s": 31608, "text": null }, { "code": "<script> // Javascript Program to calculate speed// distance and time // Function to calculate speed function cal_speed( dist, time) { document.write(\" Distance(km) : \" + dist + \"<br>\" ) ; document.write(\" Time(hr) : \" + time + \"<br>\") ; return dist / time; } // Function to calculate distance traveled function cal_dis( speed, time) { document.write(\" Time(hr) : \" + time + \"<br>\" ) ; document.write(\" Speed(km / hr) : \" + speed + \"<br>\") ; return speed * time; } // Function to calculate time taken function cal_time( dist, speed) { document.write(\" Distance(km) : \" + dist + \"<br>\") ; document.write(\" Speed(km / hr) : \" + speed + \"<br>\" ) ; return dist / speed; } // Driver code // Calling function cal_speed() document.write(\" The calculated Speed(km / hr) is : \"+ cal_speed(45.9, 2.0 ) + \"<br>\"); document.write(\"<br>\"); // Calling function cal_dis() document.write(\" The calculated Distance(km) : \"+ cal_dis(62.9, 2.5) + \"<br>\"); document.write(\"<br>\"); // Calling function cal_time() document.write(\" The calculated Time(hr) : \"+ cal_time(48.0, 4.5) + \"<br>\"); </script> ", "e": 33973, "s": 32577, "text": null }, { "code": null, "e": 33982, "s": 33973, "text": "Output: " }, { "code": null, "e": 34214, "s": 33982, "text": " Distance(km) : 45.9\n Time(hr) : 2\n The calculated Speed(km / hr) is : 22.95\n\n Time(hr) : 2.5\n Speed(km / hr) : 62.9\n The calculated Distance(km) : 157.25\n\n Distance(km) : 48\n Speed(km / hr) : 4.5\n The calculated Time(hr) : 10.6667" }, { "code": null, "e": 34229, "s": 34216, "text": "Mithun Kumar" }, { "code": null, "e": 34240, "s": 34229, "text": "bunnyram19" }, { "code": null, "e": 34251, "s": 34240, "text": "atulkeshri" }, { "code": null, "e": 34264, "s": 34251, "text": "Mathematical" }, { "code": null, "e": 34283, "s": 34264, "text": "School Programming" }, { "code": null, "e": 34296, "s": 34283, "text": "Mathematical" }, { "code": null, "e": 34394, "s": 34296, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34418, "s": 34394, "text": "Merge two sorted arrays" }, { "code": null, "e": 34461, "s": 34418, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 34475, "s": 34461, "text": "Prime Numbers" }, { "code": null, "e": 34517, "s": 34475, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 34590, "s": 34517, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 34608, "s": 34590, "text": "Python Dictionary" }, { "code": null, "e": 34624, "s": 34608, "text": "Arrays in C/C++" }, { "code": null, "e": 34643, "s": 34624, "text": "Inheritance in C++" }, { "code": null, "e": 34668, "s": 34643, "text": "Reverse a string in Java" } ]
PyQt5 - Snake Game - GeeksforGeeks
03 Jun, 2020 In this article, we will see how we can design the simple snake game using PyQt5. Snake is the common name for a video game concept where the player maneuvers a line which grows in length, with the line itself being a primary obstacle. The concept originated in the 1976 arcade game Blockade, and the ease of implementing Snake has led to hundreds of versions (some of which have the word snake or worm in the title) for many platforms. Implementation steps :1. Create a main window add status bar to it, to show the score and create an object of board class and add it as central widget2. Create a class named board which inherits the QFrame3. Inside the board class create a timer object which calls the timer method after certain amount of time4. Inside the timer method call other action of the snake game like movement, food eaten and if snake committed suicide5. Create a key press event method that check if arrow keys are pressed and change the direction of the snake according to it.6. Create a paint event method that draws snake and the food7. Create move method to move the snake according to the direction8. Create food eaten method that checks the snake current position and position if food is eaten remove the current food increment the snake length and drop a new food at random location.9. Create check suicide method that checks if snakehead position is similar to the body position or not, if matches stop the timer and show the message Below is the implementation # importing librariesfrom PyQt5.QtCore import * from PyQt5.QtWidgets import * from PyQt5.QtGui import * import randomimport sys # creating game windowclass Window(QMainWindow): def __init__(self): super(Window, self).__init__() # creating a board object self.board = Board(self) # creating a status bar to show result self.statusbar = self.statusBar() # adding border to the status bar self.statusbar.setStyleSheet("border : 2px solid black;") # calling showMessage method when signal received by board self.board.msg2statusbar[str].connect(self.statusbar.showMessage) # adding board as a central widget self.setCentralWidget(self.board) # setting title to the window self.setWindowTitle('Snake game') # setting geometry to the window self.setGeometry(100, 100, 600, 400) # starting the board object self.board.start() # showing the main window self.show() # creating a board class# that inherits QFrameclass Board(QFrame): # creating signal object msg2statusbar = pyqtSignal(str) # speed of the snake # timer countdown time SPEED = 80 # block width and height WIDTHINBLOCKS = 60 HEIGHTINBLOCKS = 40 # constructor def __init__(self, parent): super(Board, self).__init__(parent) # creating a timer self.timer = QBasicTimer() # snake self.snake = [[5, 10], [5, 11]] # current head x head self.current_x_head = self.snake[0][0] # current y head self.current_y_head = self.snake[0][1] # food list self.food = [] # growing is false self.grow_snake = False # board list self.board = [] # direction self.direction = 1 # called drop food method self.drop_food() # setting focus self.setFocusPolicy(Qt.StrongFocus) # square width method def square_width(self): return self.contentsRect().width() / Board.WIDTHINBLOCKS # square height def square_height(self): return self.contentsRect().height() / Board.HEIGHTINBLOCKS # start method def start(self): # msg for status bar # score = current len - 2 self.msg2statusbar.emit(str(len(self.snake) - 2)) # starting timer self.timer.start(Board.SPEED, self) # paint event def paintEvent(self, event): # creating painter object painter = QPainter(self) # getting rectangle rect = self.contentsRect() # board top boardtop = rect.bottom() - Board.HEIGHTINBLOCKS * self.square_height() # drawing snake for pos in self.snake: self.draw_square(painter, rect.left() + pos[0] * self.square_width(), boardtop + pos[1] * self.square_height()) # drawing food for pos in self.food: self.draw_square(painter, rect.left() + pos[0] * self.square_width(), boardtop + pos[1] * self.square_height()) # drawing square def draw_square(self, painter, x, y): # color color = QColor(0x228B22) # painting rectangle painter.fillRect(x + 1, y + 1, self.square_width() - 2, self.square_height() - 2, color) # key press event def keyPressEvent(self, event): # getting key pressed key = event.key() # if left key pressed if key == Qt.Key_Left: # if direction is not right if self.direction != 2: # set direction to left self.direction = 1 # if right key is pressed elif key == Qt.Key_Right: # if direction is not left if self.direction != 1: # set direction to right self.direction = 2 # if down key is pressed elif key == Qt.Key_Down: # if direction is not up if self.direction != 4: # set direction to down self.direction = 3 # if up key is pressed elif key == Qt.Key_Up: # if direction is not down if self.direction != 3: # set direction to up self.direction = 4 # method to move the snake def move_snake(self): # if direction is left change its position if self.direction == 1: self.current_x_head, self.current_y_head = self.current_x_head - 1, self.current_y_head # if it goes beyond left wall if self.current_x_head < 0: self.current_x_head = Board.WIDTHINBLOCKS - 1 # if direction is right change its position if self.direction == 2: self.current_x_head, self.current_y_head = self.current_x_head + 1, self.current_y_head # if it goes beyond right wall if self.current_x_head == Board.WIDTHINBLOCKS: self.current_x_head = 0 # if direction is down change its position if self.direction == 3: self.current_x_head, self.current_y_head = self.current_x_head, self.current_y_head + 1 # if it goes beyond down wall if self.current_y_head == Board.HEIGHTINBLOCKS: self.current_y_head = 0 # if direction is up change its position if self.direction == 4: self.current_x_head, self.current_y_head = self.current_x_head, self.current_y_head - 1 # if it goes beyond up wall if self.current_y_head < 0: self.current_y_head = Board.HEIGHTINBLOCKS # changing head position head = [self.current_x_head, self.current_y_head] # inset head in snake list self.snake.insert(0, head) # if snake grow is False if not self.grow_snake: # pop the last element self.snake.pop() else: # show msg in status bar self.msg2statusbar.emit(str(len(self.snake)-2)) # make grow_snake to false self.grow_snake = False # time event method def timerEvent(self, event): # checking timer id if event.timerId() == self.timer.timerId(): # call move snake method self.move_snake() # call food collision method self.is_food_collision() # call is suicide method self.is_suicide() # update the window self.update() # method to check if snake collides itself def is_suicide(self): # traversing the snake for i in range(1, len(self.snake)): # if collision found if self.snake[i] == self.snake[0]: # show game ended msg in status bar self.msg2statusbar.emit(str("Game Ended")) # making background color black self.setStyleSheet("background-color : black;") # stopping the timer self.timer.stop() # updating the window self.update() # method to check if the food cis collied def is_food_collision(self): # traversing the position of the food for pos in self.food: # if food position is similar of snake position if pos == self.snake[0]: # remove the food self.food.remove(pos) # call drop food method self.drop_food() # grow the snake self.grow_snake = True # method to drop food on screen def drop_food(self): # creating random co-ordinates x = random.randint(3, 58) y = random.randint(3, 38) # traversing if snake position is not equal to the # food position so that food do not drop on snake for pos in self.snake: # if position matches if pos == [x, y]: # call drop food method again self.drop_food() # append food location self.food.append([x, y]) # main methodif __name__ == '__main__': app = QApplication([]) window = Window() sys.exit(app.exec_()) Output : PyQt-exercise Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n03 Jun, 2020" }, { "code": null, "e": 25619, "s": 25537, "text": "In this article, we will see how we can design the simple snake game using PyQt5." }, { "code": null, "e": 25974, "s": 25619, "text": "Snake is the common name for a video game concept where the player maneuvers a line which grows in length, with the line itself being a primary obstacle. The concept originated in the 1976 arcade game Blockade, and the ease of implementing Snake has led to hundreds of versions (some of which have the word snake or worm in the title) for many platforms." }, { "code": null, "e": 26994, "s": 25974, "text": "Implementation steps :1. Create a main window add status bar to it, to show the score and create an object of board class and add it as central widget2. Create a class named board which inherits the QFrame3. Inside the board class create a timer object which calls the timer method after certain amount of time4. Inside the timer method call other action of the snake game like movement, food eaten and if snake committed suicide5. Create a key press event method that check if arrow keys are pressed and change the direction of the snake according to it.6. Create a paint event method that draws snake and the food7. Create move method to move the snake according to the direction8. Create food eaten method that checks the snake current position and position if food is eaten remove the current food increment the snake length and drop a new food at random location.9. Create check suicide method that checks if snakehead position is similar to the body position or not, if matches stop the timer and show the message" }, { "code": null, "e": 27022, "s": 26994, "text": "Below is the implementation" }, { "code": "# importing librariesfrom PyQt5.QtCore import * from PyQt5.QtWidgets import * from PyQt5.QtGui import * import randomimport sys # creating game windowclass Window(QMainWindow): def __init__(self): super(Window, self).__init__() # creating a board object self.board = Board(self) # creating a status bar to show result self.statusbar = self.statusBar() # adding border to the status bar self.statusbar.setStyleSheet(\"border : 2px solid black;\") # calling showMessage method when signal received by board self.board.msg2statusbar[str].connect(self.statusbar.showMessage) # adding board as a central widget self.setCentralWidget(self.board) # setting title to the window self.setWindowTitle('Snake game') # setting geometry to the window self.setGeometry(100, 100, 600, 400) # starting the board object self.board.start() # showing the main window self.show() # creating a board class# that inherits QFrameclass Board(QFrame): # creating signal object msg2statusbar = pyqtSignal(str) # speed of the snake # timer countdown time SPEED = 80 # block width and height WIDTHINBLOCKS = 60 HEIGHTINBLOCKS = 40 # constructor def __init__(self, parent): super(Board, self).__init__(parent) # creating a timer self.timer = QBasicTimer() # snake self.snake = [[5, 10], [5, 11]] # current head x head self.current_x_head = self.snake[0][0] # current y head self.current_y_head = self.snake[0][1] # food list self.food = [] # growing is false self.grow_snake = False # board list self.board = [] # direction self.direction = 1 # called drop food method self.drop_food() # setting focus self.setFocusPolicy(Qt.StrongFocus) # square width method def square_width(self): return self.contentsRect().width() / Board.WIDTHINBLOCKS # square height def square_height(self): return self.contentsRect().height() / Board.HEIGHTINBLOCKS # start method def start(self): # msg for status bar # score = current len - 2 self.msg2statusbar.emit(str(len(self.snake) - 2)) # starting timer self.timer.start(Board.SPEED, self) # paint event def paintEvent(self, event): # creating painter object painter = QPainter(self) # getting rectangle rect = self.contentsRect() # board top boardtop = rect.bottom() - Board.HEIGHTINBLOCKS * self.square_height() # drawing snake for pos in self.snake: self.draw_square(painter, rect.left() + pos[0] * self.square_width(), boardtop + pos[1] * self.square_height()) # drawing food for pos in self.food: self.draw_square(painter, rect.left() + pos[0] * self.square_width(), boardtop + pos[1] * self.square_height()) # drawing square def draw_square(self, painter, x, y): # color color = QColor(0x228B22) # painting rectangle painter.fillRect(x + 1, y + 1, self.square_width() - 2, self.square_height() - 2, color) # key press event def keyPressEvent(self, event): # getting key pressed key = event.key() # if left key pressed if key == Qt.Key_Left: # if direction is not right if self.direction != 2: # set direction to left self.direction = 1 # if right key is pressed elif key == Qt.Key_Right: # if direction is not left if self.direction != 1: # set direction to right self.direction = 2 # if down key is pressed elif key == Qt.Key_Down: # if direction is not up if self.direction != 4: # set direction to down self.direction = 3 # if up key is pressed elif key == Qt.Key_Up: # if direction is not down if self.direction != 3: # set direction to up self.direction = 4 # method to move the snake def move_snake(self): # if direction is left change its position if self.direction == 1: self.current_x_head, self.current_y_head = self.current_x_head - 1, self.current_y_head # if it goes beyond left wall if self.current_x_head < 0: self.current_x_head = Board.WIDTHINBLOCKS - 1 # if direction is right change its position if self.direction == 2: self.current_x_head, self.current_y_head = self.current_x_head + 1, self.current_y_head # if it goes beyond right wall if self.current_x_head == Board.WIDTHINBLOCKS: self.current_x_head = 0 # if direction is down change its position if self.direction == 3: self.current_x_head, self.current_y_head = self.current_x_head, self.current_y_head + 1 # if it goes beyond down wall if self.current_y_head == Board.HEIGHTINBLOCKS: self.current_y_head = 0 # if direction is up change its position if self.direction == 4: self.current_x_head, self.current_y_head = self.current_x_head, self.current_y_head - 1 # if it goes beyond up wall if self.current_y_head < 0: self.current_y_head = Board.HEIGHTINBLOCKS # changing head position head = [self.current_x_head, self.current_y_head] # inset head in snake list self.snake.insert(0, head) # if snake grow is False if not self.grow_snake: # pop the last element self.snake.pop() else: # show msg in status bar self.msg2statusbar.emit(str(len(self.snake)-2)) # make grow_snake to false self.grow_snake = False # time event method def timerEvent(self, event): # checking timer id if event.timerId() == self.timer.timerId(): # call move snake method self.move_snake() # call food collision method self.is_food_collision() # call is suicide method self.is_suicide() # update the window self.update() # method to check if snake collides itself def is_suicide(self): # traversing the snake for i in range(1, len(self.snake)): # if collision found if self.snake[i] == self.snake[0]: # show game ended msg in status bar self.msg2statusbar.emit(str(\"Game Ended\")) # making background color black self.setStyleSheet(\"background-color : black;\") # stopping the timer self.timer.stop() # updating the window self.update() # method to check if the food cis collied def is_food_collision(self): # traversing the position of the food for pos in self.food: # if food position is similar of snake position if pos == self.snake[0]: # remove the food self.food.remove(pos) # call drop food method self.drop_food() # grow the snake self.grow_snake = True # method to drop food on screen def drop_food(self): # creating random co-ordinates x = random.randint(3, 58) y = random.randint(3, 38) # traversing if snake position is not equal to the # food position so that food do not drop on snake for pos in self.snake: # if position matches if pos == [x, y]: # call drop food method again self.drop_food() # append food location self.food.append([x, y]) # main methodif __name__ == '__main__': app = QApplication([]) window = Window() sys.exit(app.exec_())", "e": 35228, "s": 27022, "text": null }, { "code": null, "e": 35237, "s": 35228, "text": "Output :" }, { "code": null, "e": 35251, "s": 35237, "text": "PyQt-exercise" }, { "code": null, "e": 35262, "s": 35251, "text": "Python-gui" }, { "code": null, "e": 35274, "s": 35262, "text": "Python-PyQt" }, { "code": null, "e": 35281, "s": 35274, "text": "Python" }, { "code": null, "e": 35379, "s": 35281, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35411, "s": 35379, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 35453, "s": 35411, "text": "Check if element exists in list in Python" }, { "code": null, "e": 35495, "s": 35453, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 35522, "s": 35495, "text": "Python Classes and Objects" }, { "code": null, "e": 35578, "s": 35522, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 35617, "s": 35578, "text": "Python | Get unique values from a list" }, { "code": null, "e": 35639, "s": 35617, "text": "Defaultdict in Python" }, { "code": null, "e": 35670, "s": 35639, "text": "Python | os.path.join() method" }, { "code": null, "e": 35699, "s": 35670, "text": "Create a directory in Python" } ]
jQuery UI Draggable revert Option - GeeksforGeeks
10 Mar, 2021 The jQuery UI consists of GUI widgets, visual effects, and themes implemented using jQuery, CSS, and HTML. jQuery UI is great for building UI interfaces for the webpages. The jQuery UI Draggable revert Option is used to set the revert property of an element. If this option is set to true the helper element to be used for dragging display. Syntax: $( ".selector" ).draggable({ revert: true }); CDN Link: First, add jQuery UI scripts needed for your project. <link rel=”stylesheet” href=”//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css”><script src=”//code.jquery.com/jquery-1.12.4.js”></script><script src=”//code.jquery.com/ui/1.12.1/jquery-ui.js”></script> Example: HTML <!doctype html><html lang="en"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.12.4.js"> </script> <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"> </script> <style> h1 { color: green; } #div_element { width: 150px; height: 150px; background: green; display: flex; justify-content: center; align-items: center; text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h3>jQuery UI Draggable revert Option</h3> <div id="div_element">Div content</div> <script> $(function () { $("#div_element").draggable({ revert: true }); }); </script></body> </html> Output: Reference:https://api.jqueryui.com/draggable/#option-revert jQuery-UI JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to change the background color after clicking the button in JavaScript ? How to fetch data from JSON file and display in HTML table using jQuery ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 52596, "s": 52568, "text": "\n10 Mar, 2021" }, { "code": null, "e": 52937, "s": 52596, "text": "The jQuery UI consists of GUI widgets, visual effects, and themes implemented using jQuery, CSS, and HTML. jQuery UI is great for building UI interfaces for the webpages. The jQuery UI Draggable revert Option is used to set the revert property of an element. If this option is set to true the helper element to be used for dragging display." }, { "code": null, "e": 52945, "s": 52937, "text": "Syntax:" }, { "code": null, "e": 52995, "s": 52945, "text": "$( \".selector\" ).draggable({\n revert: true\n});" }, { "code": null, "e": 53059, "s": 52995, "text": "CDN Link: First, add jQuery UI scripts needed for your project." }, { "code": null, "e": 53272, "s": 53059, "text": "<link rel=”stylesheet” href=”//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css”><script src=”//code.jquery.com/jquery-1.12.4.js”></script><script src=”//code.jquery.com/ui/1.12.1/jquery-ui.js”></script>" }, { "code": null, "e": 53281, "s": 53272, "text": "Example:" }, { "code": null, "e": 53286, "s": 53281, "text": "HTML" }, { "code": "<!doctype html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css\"> <script src=\"//code.jquery.com/jquery-1.12.4.js\"> </script> <script src=\"//code.jquery.com/ui/1.12.1/jquery-ui.js\"> </script> <style> h1 { color: green; } #div_element { width: 150px; height: 150px; background: green; display: flex; justify-content: center; align-items: center; text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h3>jQuery UI Draggable revert Option</h3> <div id=\"div_element\">Div content</div> <script> $(function () { $(\"#div_element\").draggable({ revert: true }); }); </script></body> </html>", "e": 54187, "s": 53286, "text": null }, { "code": null, "e": 54195, "s": 54187, "text": "Output:" }, { "code": null, "e": 54255, "s": 54195, "text": "Reference:https://api.jqueryui.com/draggable/#option-revert" }, { "code": null, "e": 54265, "s": 54255, "text": "jQuery-UI" }, { "code": null, "e": 54272, "s": 54265, "text": "JQuery" }, { "code": null, "e": 54289, "s": 54272, "text": "Web Technologies" }, { "code": null, "e": 54387, "s": 54289, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 54433, "s": 54387, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 54462, "s": 54433, "text": "Form validation using jQuery" }, { "code": null, "e": 54525, "s": 54462, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 54602, "s": 54525, "text": "How to change the background color after clicking the button in JavaScript ?" }, { "code": null, "e": 54676, "s": 54602, "text": "How to fetch data from JSON file and display in HTML table using jQuery ?" }, { "code": null, "e": 54716, "s": 54676, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 54749, "s": 54716, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 54794, "s": 54749, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 54837, "s": 54794, "text": "How to fetch data from an API in ReactJS ?" } ]
Output of Java programs | Set 29 - GeeksforGeeks
31 Aug, 2017 Question 1. What is the output of the following question? class Test1 {public static void main(String[] args) { int String = 65; int Runnable = 97; System.out.print(String + " : " + Runnable); }} OptionA) ErrorB) A : aC) 65 : 97D) None Output: C Explanation : We can use all predefined Java class name and interface name as identifiers. Question 2. What is the output of the following question? class Test2 {public static void main(String[] args) { int if = 65; int else = 97; System.out.println(if + " : " + else); }} OptionA) ErrorB) A : BC) 65 : 97D) None Output: A Explanation : We can’t use reserved words as identifiers. Question 3. What is the output of the following question? class Test3 {public static void main(String[] args) { int x = 1; if (x) { System.out.print("GeeksForGeeks"); } else { System.out.print("GFG"); } }} OptionA) GeeksForGeeksB) GFGC) ErrorD) None Output: C Explanation :In Java, Compiler gives error – Incompatible types : int can not be converted to boolean type.But in C or C++ its a valid statement. Question 4. What is the output of the following question? class Test4 {public static void main(String[] args) { double d1 = 123.456; double d2 = 12_3.4_5_6; double d3 = 12_3.4_56; System.out.println(d1); System.out.println(d2); System.out.println(d3); }} OptionA) ErrorB) 123.45612_3.4_5_612_3.4_56C) 123.456123.456123.456D) None Output: C Explanation : From (1.7v onwards)we can use ‘_'(under Score) Symbol between digits of numeric literals. See more at Java naming conventions. Question 5. What is the output of the following question? class Test5 {public static void main(String[] args) { double d1 = _123 .456; double d2 = 12_3_.4_5_6; double d3 = 12_3.4_56_; System.out.println(d1); System.out.println(d2); System.out.println(d3); }} OptionA) ErrorB) 123.45612_3.4_5_612_3.4_56C) 123.456123.456123.456D) None Output: A Explanation : We can use the ‘_’ (under score) symbol only between the digits. if we are using anywhere else we will get compile time error – Illegal under score. This article is contributed by Shivakant Jaiswal. 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. Java-Output Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Output of Java program | Set 18 (Overriding) Output of C++ programs | Set 34 (File Handling) Different ways to copy a string in C/C++ Output of Python Program | Set 1 Output of C++ programs | Set 50 Runtime Errors Output of C Programs | Set 2 C++ Programming Multiple Choice Questions Output of C++ Program | Set 1 Output of Java Program | Set 20 (Inheritance)
[ { "code": null, "e": 25685, "s": 25657, "text": "\n31 Aug, 2017" }, { "code": null, "e": 25743, "s": 25685, "text": "Question 1. What is the output of the following question?" }, { "code": "class Test1 {public static void main(String[] args) { int String = 65; int Runnable = 97; System.out.print(String + \" : \" + Runnable); }}", "e": 25913, "s": 25743, "text": null }, { "code": null, "e": 25953, "s": 25913, "text": "OptionA) ErrorB) A : aC) 65 : 97D) None" }, { "code": null, "e": 25963, "s": 25953, "text": "Output: C" }, { "code": null, "e": 26054, "s": 25963, "text": "Explanation : We can use all predefined Java class name and interface name as identifiers." }, { "code": null, "e": 26112, "s": 26054, "text": "Question 2. What is the output of the following question?" }, { "code": "class Test2 {public static void main(String[] args) { int if = 65; int else = 97; System.out.println(if + \" : \" + else); }}", "e": 26268, "s": 26112, "text": null }, { "code": null, "e": 26308, "s": 26268, "text": "OptionA) ErrorB) A : BC) 65 : 97D) None" }, { "code": null, "e": 26318, "s": 26308, "text": "Output: A" }, { "code": null, "e": 26376, "s": 26318, "text": "Explanation : We can’t use reserved words as identifiers." }, { "code": null, "e": 26434, "s": 26376, "text": "Question 3. What is the output of the following question?" }, { "code": "class Test3 {public static void main(String[] args) { int x = 1; if (x) { System.out.print(\"GeeksForGeeks\"); } else { System.out.print(\"GFG\"); } }}", "e": 26643, "s": 26434, "text": null }, { "code": null, "e": 26687, "s": 26643, "text": "OptionA) GeeksForGeeksB) GFGC) ErrorD) None" }, { "code": null, "e": 26697, "s": 26687, "text": "Output: C" }, { "code": null, "e": 26843, "s": 26697, "text": "Explanation :In Java, Compiler gives error – Incompatible types : int can not be converted to boolean type.But in C or C++ its a valid statement." }, { "code": null, "e": 26901, "s": 26843, "text": "Question 4. What is the output of the following question?" }, { "code": "class Test4 {public static void main(String[] args) { double d1 = 123.456; double d2 = 12_3.4_5_6; double d3 = 12_3.4_56; System.out.println(d1); System.out.println(d2); System.out.println(d3); }}", "e": 27151, "s": 26901, "text": null }, { "code": null, "e": 27226, "s": 27151, "text": "OptionA) ErrorB) 123.45612_3.4_5_612_3.4_56C) 123.456123.456123.456D) None" }, { "code": null, "e": 27236, "s": 27226, "text": "Output: C" }, { "code": null, "e": 27377, "s": 27236, "text": "Explanation : From (1.7v onwards)we can use ‘_'(under Score) Symbol between digits of numeric literals. See more at Java naming conventions." }, { "code": null, "e": 27435, "s": 27377, "text": "Question 5. What is the output of the following question?" }, { "code": "class Test5 {public static void main(String[] args) { double d1 = _123 .456; double d2 = 12_3_.4_5_6; double d3 = 12_3.4_56_; System.out.println(d1); System.out.println(d2); System.out.println(d3); }}", "e": 27689, "s": 27435, "text": null }, { "code": null, "e": 27764, "s": 27689, "text": "OptionA) ErrorB) 123.45612_3.4_5_612_3.4_56C) 123.456123.456123.456D) None" }, { "code": null, "e": 27774, "s": 27764, "text": "Output: A" }, { "code": null, "e": 27937, "s": 27774, "text": "Explanation : We can use the ‘_’ (under score) symbol only between the digits. if we are using anywhere else we will get compile time error – Illegal under score." }, { "code": null, "e": 28242, "s": 27937, "text": "This article is contributed by Shivakant Jaiswal. 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": 28367, "s": 28242, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 28379, "s": 28367, "text": "Java-Output" }, { "code": null, "e": 28394, "s": 28379, "text": "Program Output" }, { "code": null, "e": 28492, "s": 28394, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28537, "s": 28492, "text": "Output of Java program | Set 18 (Overriding)" }, { "code": null, "e": 28585, "s": 28537, "text": "Output of C++ programs | Set 34 (File Handling)" }, { "code": null, "e": 28626, "s": 28585, "text": "Different ways to copy a string in C/C++" }, { "code": null, "e": 28659, "s": 28626, "text": "Output of Python Program | Set 1" }, { "code": null, "e": 28691, "s": 28659, "text": "Output of C++ programs | Set 50" }, { "code": null, "e": 28706, "s": 28691, "text": "Runtime Errors" }, { "code": null, "e": 28735, "s": 28706, "text": "Output of C Programs | Set 2" }, { "code": null, "e": 28777, "s": 28735, "text": "C++ Programming Multiple Choice Questions" }, { "code": null, "e": 28807, "s": 28777, "text": "Output of C++ Program | Set 1" } ]
Adding Pages to a PDF Document using Java - GeeksforGeeks
28 Jan, 2021 PDDocument class of ‘org.apache.pdfbox.pdmodel’ package which extends ‘java.lang.Object‘. is used. Declaration: public class PDDocument extends Object implements Pageable, Closeable Pre-requisite: Constructors PDDocument(): This constructor used to construct a new PDF document with zero pages.PDDocument(COSDocument doc): This constructor uses already existing PDF documents, and then we can add or remove pages.PDDocument(COSDocument doc, BaseParser usedParser): This constructor is similar to the above one but it has a parser in it. PDDocument(): This constructor used to construct a new PDF document with zero pages. PDDocument(COSDocument doc): This constructor uses already existing PDF documents, and then we can add or remove pages. PDDocument(COSDocument doc, BaseParser usedParser): This constructor is similar to the above one but it has a parser in it. Method Using: addPage() Method There are many methods in PDDocument class but standard and most frequently used to add anything to PDF be it image or pages, the requirement is only for addPage() method. The addPage() method is used for adding pages in the PDF document. The following code adds a page in a PDF document. Syntax: To declare addPage() method public void addPage(PDPage page) ; This will add a page to the document. This is the easiest method, which will add the page to the root of the hierarchy and set the parent of the page to the root. Hence, so far by now, the page to be added to the document is defined clearly. Procedure: Create a document.Create a blank page.Add this page to the document.Save the document.Close the document. Create a document. Create a blank page. Add this page to the document. Save the document. Close the document. Step 1: Creating a Document An object is needed to be created of PDDocument class which will enable the creation of an empty PDF document. Currently, it does not contain any page. Syntax: PDDocument doc = new PDDocument(); Step 2: Creating a Blank Page PDPage is also a type of class that belongs to the same package as PDDocument which is ‘org.apache.pdfbox.pdmodel‘. Syntax: PDPage page = new PDPage(); Step 3: Adding Page to Document Here, addPage() method of PDDocument class is used to add the blank to the document which is nothing but an object of PDDocument. Syntax: PDPage page = new PDPage(); Step 4: Saving the Document After adding pages to the document you have to save that file at the desired location for that we use the save() method which takes a string as a parameter containing the path address. Syntax: doc.save("path"); Step 5: Closing Document Finally, we have to close the document by using the close() method. If we don’t close it then if another program wants to access that PDF then it will get an error. Syntax: doc.close(); Implementation: Example 1(A) Java // Java Program to add page to a PDF document // Here a page will be created in PDF and saved only// carried forward to next example // Importing required packagesimport java.io.IOException;// Importing Apache POI modulesimport org.apache.pdfbox.pdmodel.*; // Classpublic class GFG { // Main driver method public static void main(String[] args) throws IOException { // Creating PDF document object PDDocument doc = new PDDocument(); // Creating a blankpage PDPage page = new PDPage(); // Adding the blankpage to the document doc.addPage(page); // Saving the document from the // local directory on the system // Custom directory window path here doc.save("F:/sample.pdf"); // Closing the document doc.close(); }} Output: Note: By now there is only 1 page in the PDF document as shown in the markup[1/1] in the above output image. Example 1(B) Java // Java Program to add pages to PDF// using addPage() method // Carried forward from above example // Importing input output classesimport java.io.IOException;// Importing Apache POI modulesimport org.apache.pdfbox.pdmodel.PDDocument; // Classpublic class GFG { // Main driver method public static void main(String[] args) throws IOException { // Step 1: Creating PDF document object PDDocument doc = new PDDocument(); // Traversing via for loop responsible // for addition of blank pages // Customly adding pages say // number be it 7 for (int i = 0; i < 7; i++) { // Step 2: Creating a blankpage // using PDPage() method PDPage page = new PDPage(); // Step 3: Adding the blankpage to the // document using addPage() method doc.addPage(page); } // Step 4: Saving the document doc.save("F:/sample1.pdf"); // Step 5: Closing the document doc.close(); }} Output: Note: By now, a page has been added to the above image page which is evidently seen in the markup [1/2] in the above output image. Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Iterate through List in Java
[ { "code": null, "e": 25263, "s": 25235, "text": "\n28 Jan, 2021" }, { "code": null, "e": 25362, "s": 25263, "text": "PDDocument class of ‘org.apache.pdfbox.pdmodel’ package which extends ‘java.lang.Object‘. is used." }, { "code": null, "e": 25375, "s": 25362, "text": "Declaration:" }, { "code": null, "e": 25445, "s": 25375, "text": "public class PDDocument\nextends Object\nimplements Pageable, Closeable" }, { "code": null, "e": 25473, "s": 25445, "text": "Pre-requisite: Constructors" }, { "code": null, "e": 25800, "s": 25473, "text": "PDDocument(): This constructor used to construct a new PDF document with zero pages.PDDocument(COSDocument doc): This constructor uses already existing PDF documents, and then we can add or remove pages.PDDocument(COSDocument doc, BaseParser usedParser): This constructor is similar to the above one but it has a parser in it." }, { "code": null, "e": 25885, "s": 25800, "text": "PDDocument(): This constructor used to construct a new PDF document with zero pages." }, { "code": null, "e": 26005, "s": 25885, "text": "PDDocument(COSDocument doc): This constructor uses already existing PDF documents, and then we can add or remove pages." }, { "code": null, "e": 26129, "s": 26005, "text": "PDDocument(COSDocument doc, BaseParser usedParser): This constructor is similar to the above one but it has a parser in it." }, { "code": null, "e": 26161, "s": 26129, "text": "Method Using: addPage() Method " }, { "code": null, "e": 26450, "s": 26161, "text": "There are many methods in PDDocument class but standard and most frequently used to add anything to PDF be it image or pages, the requirement is only for addPage() method. The addPage() method is used for adding pages in the PDF document. The following code adds a page in a PDF document." }, { "code": null, "e": 26486, "s": 26450, "text": "Syntax: To declare addPage() method" }, { "code": null, "e": 26521, "s": 26486, "text": "public void addPage(PDPage page) ;" }, { "code": null, "e": 26764, "s": 26521, "text": "This will add a page to the document. This is the easiest method, which will add the page to the root of the hierarchy and set the parent of the page to the root. Hence, so far by now, the page to be added to the document is defined clearly. " }, { "code": null, "e": 26775, "s": 26764, "text": "Procedure:" }, { "code": null, "e": 26881, "s": 26775, "text": "Create a document.Create a blank page.Add this page to the document.Save the document.Close the document." }, { "code": null, "e": 26900, "s": 26881, "text": "Create a document." }, { "code": null, "e": 26921, "s": 26900, "text": "Create a blank page." }, { "code": null, "e": 26952, "s": 26921, "text": "Add this page to the document." }, { "code": null, "e": 26971, "s": 26952, "text": "Save the document." }, { "code": null, "e": 26991, "s": 26971, "text": "Close the document." }, { "code": null, "e": 27019, "s": 26991, "text": "Step 1: Creating a Document" }, { "code": null, "e": 27171, "s": 27019, "text": "An object is needed to be created of PDDocument class which will enable the creation of an empty PDF document. Currently, it does not contain any page." }, { "code": null, "e": 27180, "s": 27171, "text": "Syntax: " }, { "code": null, "e": 27216, "s": 27180, "text": "PDDocument doc = new PDDocument(); " }, { "code": null, "e": 27246, "s": 27216, "text": "Step 2: Creating a Blank Page" }, { "code": null, "e": 27362, "s": 27246, "text": "PDPage is also a type of class that belongs to the same package as PDDocument which is ‘org.apache.pdfbox.pdmodel‘." }, { "code": null, "e": 27371, "s": 27362, "text": "Syntax: " }, { "code": null, "e": 27399, "s": 27371, "text": "PDPage page = new PDPage();" }, { "code": null, "e": 27431, "s": 27399, "text": "Step 3: Adding Page to Document" }, { "code": null, "e": 27561, "s": 27431, "text": "Here, addPage() method of PDDocument class is used to add the blank to the document which is nothing but an object of PDDocument." }, { "code": null, "e": 27570, "s": 27561, "text": "Syntax: " }, { "code": null, "e": 27598, "s": 27570, "text": "PDPage page = new PDPage();" }, { "code": null, "e": 27626, "s": 27598, "text": "Step 4: Saving the Document" }, { "code": null, "e": 27811, "s": 27626, "text": "After adding pages to the document you have to save that file at the desired location for that we use the save() method which takes a string as a parameter containing the path address." }, { "code": null, "e": 27820, "s": 27811, "text": "Syntax: " }, { "code": null, "e": 27838, "s": 27820, "text": "doc.save(\"path\");" }, { "code": null, "e": 27863, "s": 27838, "text": "Step 5: Closing Document" }, { "code": null, "e": 28028, "s": 27863, "text": "Finally, we have to close the document by using the close() method. If we don’t close it then if another program wants to access that PDF then it will get an error." }, { "code": null, "e": 28037, "s": 28028, "text": "Syntax: " }, { "code": null, "e": 28050, "s": 28037, "text": "doc.close();" }, { "code": null, "e": 28066, "s": 28050, "text": "Implementation:" }, { "code": null, "e": 28079, "s": 28066, "text": "Example 1(A)" }, { "code": null, "e": 28084, "s": 28079, "text": "Java" }, { "code": "// Java Program to add page to a PDF document // Here a page will be created in PDF and saved only// carried forward to next example // Importing required packagesimport java.io.IOException;// Importing Apache POI modulesimport org.apache.pdfbox.pdmodel.*; // Classpublic class GFG { // Main driver method public static void main(String[] args) throws IOException { // Creating PDF document object PDDocument doc = new PDDocument(); // Creating a blankpage PDPage page = new PDPage(); // Adding the blankpage to the document doc.addPage(page); // Saving the document from the // local directory on the system // Custom directory window path here doc.save(\"F:/sample.pdf\"); // Closing the document doc.close(); }}", "e": 28915, "s": 28084, "text": null }, { "code": null, "e": 28923, "s": 28915, "text": "Output:" }, { "code": null, "e": 29033, "s": 28923, "text": "Note: By now there is only 1 page in the PDF document as shown in the markup[1/1] in the above output image. " }, { "code": null, "e": 29046, "s": 29033, "text": "Example 1(B)" }, { "code": null, "e": 29051, "s": 29046, "text": "Java" }, { "code": "// Java Program to add pages to PDF// using addPage() method // Carried forward from above example // Importing input output classesimport java.io.IOException;// Importing Apache POI modulesimport org.apache.pdfbox.pdmodel.PDDocument; // Classpublic class GFG { // Main driver method public static void main(String[] args) throws IOException { // Step 1: Creating PDF document object PDDocument doc = new PDDocument(); // Traversing via for loop responsible // for addition of blank pages // Customly adding pages say // number be it 7 for (int i = 0; i < 7; i++) { // Step 2: Creating a blankpage // using PDPage() method PDPage page = new PDPage(); // Step 3: Adding the blankpage to the // document using addPage() method doc.addPage(page); } // Step 4: Saving the document doc.save(\"F:/sample1.pdf\"); // Step 5: Closing the document doc.close(); }}", "e": 30091, "s": 29051, "text": null }, { "code": null, "e": 30099, "s": 30091, "text": "Output:" }, { "code": null, "e": 30231, "s": 30099, "text": "Note: By now, a page has been added to the above image page which is evidently seen in the markup [1/2] in the above output image. " }, { "code": null, "e": 30238, "s": 30231, "text": "Picked" }, { "code": null, "e": 30262, "s": 30238, "text": "Technical Scripter 2020" }, { "code": null, "e": 30267, "s": 30262, "text": "Java" }, { "code": null, "e": 30281, "s": 30267, "text": "Java Programs" }, { "code": null, "e": 30300, "s": 30281, "text": "Technical Scripter" }, { "code": null, "e": 30305, "s": 30300, "text": "Java" }, { "code": null, "e": 30403, "s": 30305, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30418, "s": 30403, "text": "Stream In Java" }, { "code": null, "e": 30439, "s": 30418, "text": "Constructors in Java" }, { "code": null, "e": 30458, "s": 30439, "text": "Exceptions in Java" }, { "code": null, "e": 30488, "s": 30458, "text": "Functional Interfaces in Java" }, { "code": null, "e": 30534, "s": 30488, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 30560, "s": 30534, "text": "Java Programming Examples" }, { "code": null, "e": 30594, "s": 30560, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 30641, "s": 30594, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 30673, "s": 30641, "text": "How to Iterate HashMap in Java?" } ]
How to validate a domain name using Regular Expression - GeeksforGeeks
04 Feb, 2021 Given string str, the task is to check whether the given string is a valid domain name or not by using Regular Expression.The valid domain name must satisfy the following conditions: The domain name should be a-z or A-Z or 0-9 and hyphen (-).The domain name should be between 1 and 63 characters long.The domain name should not start or end with a hyphen(-) (e.g. -geeksforgeeks.org or geeksforgeeks.org-).The last TLD (Top level domain) must be at least two characters and a maximum of 6 characters.The domain name can be a subdomain (e.g. contribute.geeksforgeeks.org). The domain name should be a-z or A-Z or 0-9 and hyphen (-). The domain name should be between 1 and 63 characters long. The domain name should not start or end with a hyphen(-) (e.g. -geeksforgeeks.org or geeksforgeeks.org-). The last TLD (Top level domain) must be at least two characters and a maximum of 6 characters. The domain name can be a subdomain (e.g. contribute.geeksforgeeks.org). Examples: Input: str = “contribute.geeksforgeeks.org” Output: true Explanation: The given string satisfies all the above mentioned conditions. Therefore, it is a valid domain name.Input: str = “-geeksforgeeks.org” Output: false Explanation: The given string starts with a hyphen (-). Therefore, it is not a valid domain name.Input: str = “geeksforgeeks.o” Output: false Explanation: The given string have last TLD of 1 character, the last TLD must be between 2 and 6 characters long. Therefore, it is not a valid domain name.Input: str = “.org” Output: false Explanation: The given string doesn’t start with a-z or A-Z or 0-9. Therefore, it is not a valid domain name. Approach: The idea is to use Regular Expression to solve this problem. The following steps can be followed to compute the answer: Get the String. Create a regular expression to check the valid domain name as mentioned below: regex = “^((?!-)[A-Za-z0-9-]{1, 63}(?<!-)\\.)+[A-Za-z]{2, 6}$” Where: ^ represents the starting of the string.( represents the starting of the group.(?!-) represents the string should not start with a hyphen (-).[A-Za-z0-9-]{1, 63} represents the domain name should be a-z or A-Z or 0-9 and hyphen (-) between 1 and 63 characters long.(?<!-) represents the string should not end with a hyphen (-).\\. represents the string followed by a dot.)+ represents the ending of the group, this group must appear at least 1 time, but allowed multiple times for subdomain.[A-Za-z]{2, 6} represents the TLD must be A-Z or a-z between 2 and 6 characters long.$ represents the ending of the string. ^ represents the starting of the string. ( represents the starting of the group. (?!-) represents the string should not start with a hyphen (-). [A-Za-z0-9-]{1, 63} represents the domain name should be a-z or A-Z or 0-9 and hyphen (-) between 1 and 63 characters long. (?<!-) represents the string should not end with a hyphen (-). \\. represents the string followed by a dot. )+ represents the ending of the group, this group must appear at least 1 time, but allowed multiple times for subdomain. [A-Za-z]{2, 6} represents the TLD must be A-Z or a-z between 2 and 6 characters long. $ represents the ending of the string. Match the given string with the regular expression. In Java, this can be done by using Pattern.matcher(). Return true if the string matches with the given regular expression, else return false. Below is the implementation of the above approach: C++ Java Python3 // C++ program to validate the// domain name using Regular Expression#include <iostream>#include <regex>using namespace std; // Function to validate the domain name.bool isValidDomain(string str){ // Regex to check valid domain name. const regex pattern("^(?!-)[A-Za-z0-9-]+([\\-\\.]{1}[a-z0-9]+)*\\.[A-Za-z]{2,6}$"); // If the domain name // is empty return false if (str.empty()) { return false; } // Return true if the domain name // matched the ReGex if(regex_match(str, pattern)) { return true; } else { return false; }} // Driver Codeint main(){ // Test Case 1: string str1 = "geeksforgeeks.org"; cout << isValidDomain(str1) << endl; // Test Case 2: string str2 = "contribute.geeksforgeeks.org"; cout << isValidDomain(str2) << endl; // Test Case 3: string str3 = "-geeksforgeeks.org"; cout << isValidDomain(str3) << endl; // Test Case 4: string str4 = "geeksforgeeks.o"; cout << isValidDomain(str4) << endl; // Test Case 5: string str5 = ".org"; cout << isValidDomain(str5) << endl; return 0;} // This code is contributed by yuvraj_chandra // Java program to validate domain name.// using regular expression. import java.util.regex.*;class GFG { // Function to validate domain name. public static boolean isValidDomain(String str) { // Regex to check valid domain name. String regex = "^((?!-)[A-Za-z0-9-]" + "{1,63}(?<!-)\\.)" + "+[A-Za-z]{2,6}"; // Compile the ReGex Pattern p = Pattern.compile(regex); // If the string is empty // return false if (str == null) { return false; } // Pattern class contains matcher() // method to find the matching // between the given string and // regular expression. Matcher m = p.matcher(str); // Return if the string // matched the ReGex return m.matches(); } // Driver Code public static void main(String args[]) { // Test Case 1: String str1 = "geeksforgeeks.org"; System.out.println(isValidDomain(str1)); // Test Case 2: String str2 = "contribute.geeksforgeeks.org"; System.out.println(isValidDomain(str2)); // Test Case 3: String str3 = "-geeksforgeeks.org"; System.out.println(isValidDomain(str3)); // Test Case 4: String str4 = "geeksforgeeks.o"; System.out.println(isValidDomain(str4)); // Test Case 5: String str5 = ".org"; System.out.println(isValidDomain(str5)); }} # Python3 program to validate# domain name# using regular expressionimport re # Function to validate# domain name.def isValidDomain(str): # Regex to check valid # domain name. regex = "^((?!-)[A-Za-z0-9-]" + "{1,63}(?<!-)\\.)" + "+[A-Za-z]{2,6}" # Compile the ReGex p = re.compile(regex) # If the string is empty # return false if (str == None): return False # Return if the string # matched the ReGex if(re.search(p, str)): return True else: return False # Driver code # Test Case 1:str1 = "geeksforgeeks.org"print(isValidDomain(str1)) # Test Case 2:str2 = "contribute.geeksforgeeks.org"print(isValidDomain(str2)) # Test Case 3:str3 = "-geeksforgeeks.org"print(isValidDomain(str3)) # Test Case 4:str4 = "geeksforgeeks.o"print(isValidDomain(str4)) # Test Case 5:str5 = ".org"print(isValidDomain(str5)) # This code is contributed by avanitrachhadiya2155 true true false false false avanitrachhadiya2155 yuvraj_chandra CPP-regex java-regular-expression regular-expression Pattern Searching Strings Strings Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Boyer Moore Algorithm for Pattern Searching Search a Word in a 2D Grid of characters How to check if string contains only digits in Java Check if a string contains uppercase, lowercase, special characters and numeric values Applications of String Matching Algorithms 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": 26627, "s": 26599, "text": "\n04 Feb, 2021" }, { "code": null, "e": 26811, "s": 26627, "text": "Given string str, the task is to check whether the given string is a valid domain name or not by using Regular Expression.The valid domain name must satisfy the following conditions: " }, { "code": null, "e": 27200, "s": 26811, "text": "The domain name should be a-z or A-Z or 0-9 and hyphen (-).The domain name should be between 1 and 63 characters long.The domain name should not start or end with a hyphen(-) (e.g. -geeksforgeeks.org or geeksforgeeks.org-).The last TLD (Top level domain) must be at least two characters and a maximum of 6 characters.The domain name can be a subdomain (e.g. contribute.geeksforgeeks.org)." }, { "code": null, "e": 27260, "s": 27200, "text": "The domain name should be a-z or A-Z or 0-9 and hyphen (-)." }, { "code": null, "e": 27320, "s": 27260, "text": "The domain name should be between 1 and 63 characters long." }, { "code": null, "e": 27426, "s": 27320, "text": "The domain name should not start or end with a hyphen(-) (e.g. -geeksforgeeks.org or geeksforgeeks.org-)." }, { "code": null, "e": 27521, "s": 27426, "text": "The last TLD (Top level domain) must be at least two characters and a maximum of 6 characters." }, { "code": null, "e": 27593, "s": 27521, "text": "The domain name can be a subdomain (e.g. contribute.geeksforgeeks.org)." }, { "code": null, "e": 27604, "s": 27593, "text": "Examples: " }, { "code": null, "e": 28264, "s": 27604, "text": "Input: str = “contribute.geeksforgeeks.org” Output: true Explanation: The given string satisfies all the above mentioned conditions. Therefore, it is a valid domain name.Input: str = “-geeksforgeeks.org” Output: false Explanation: The given string starts with a hyphen (-). Therefore, it is not a valid domain name.Input: str = “geeksforgeeks.o” Output: false Explanation: The given string have last TLD of 1 character, the last TLD must be between 2 and 6 characters long. Therefore, it is not a valid domain name.Input: str = “.org” Output: false Explanation: The given string doesn’t start with a-z or A-Z or 0-9. Therefore, it is not a valid domain name. " }, { "code": null, "e": 28394, "s": 28264, "text": "Approach: The idea is to use Regular Expression to solve this problem. The following steps can be followed to compute the answer:" }, { "code": null, "e": 28410, "s": 28394, "text": "Get the String." }, { "code": null, "e": 28489, "s": 28410, "text": "Create a regular expression to check the valid domain name as mentioned below:" }, { "code": null, "e": 28554, "s": 28489, "text": "regex = “^((?!-)[A-Za-z0-9-]{1, 63}(?<!-)\\\\.)+[A-Za-z]{2, 6}$” " }, { "code": null, "e": 29176, "s": 28554, "text": "Where: ^ represents the starting of the string.( represents the starting of the group.(?!-) represents the string should not start with a hyphen (-).[A-Za-z0-9-]{1, 63} represents the domain name should be a-z or A-Z or 0-9 and hyphen (-) between 1 and 63 characters long.(?<!-) represents the string should not end with a hyphen (-).\\\\. represents the string followed by a dot.)+ represents the ending of the group, this group must appear at least 1 time, but allowed multiple times for subdomain.[A-Za-z]{2, 6} represents the TLD must be A-Z or a-z between 2 and 6 characters long.$ represents the ending of the string." }, { "code": null, "e": 29217, "s": 29176, "text": "^ represents the starting of the string." }, { "code": null, "e": 29257, "s": 29217, "text": "( represents the starting of the group." }, { "code": null, "e": 29321, "s": 29257, "text": "(?!-) represents the string should not start with a hyphen (-)." }, { "code": null, "e": 29445, "s": 29321, "text": "[A-Za-z0-9-]{1, 63} represents the domain name should be a-z or A-Z or 0-9 and hyphen (-) between 1 and 63 characters long." }, { "code": null, "e": 29508, "s": 29445, "text": "(?<!-) represents the string should not end with a hyphen (-)." }, { "code": null, "e": 29553, "s": 29508, "text": "\\\\. represents the string followed by a dot." }, { "code": null, "e": 29674, "s": 29553, "text": ")+ represents the ending of the group, this group must appear at least 1 time, but allowed multiple times for subdomain." }, { "code": null, "e": 29760, "s": 29674, "text": "[A-Za-z]{2, 6} represents the TLD must be A-Z or a-z between 2 and 6 characters long." }, { "code": null, "e": 29799, "s": 29760, "text": "$ represents the ending of the string." }, { "code": null, "e": 29905, "s": 29799, "text": "Match the given string with the regular expression. In Java, this can be done by using Pattern.matcher()." }, { "code": null, "e": 29993, "s": 29905, "text": "Return true if the string matches with the given regular expression, else return false." }, { "code": null, "e": 30045, "s": 29993, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 30049, "s": 30045, "text": "C++" }, { "code": null, "e": 30054, "s": 30049, "text": "Java" }, { "code": null, "e": 30062, "s": 30054, "text": "Python3" }, { "code": "// C++ program to validate the// domain name using Regular Expression#include <iostream>#include <regex>using namespace std; // Function to validate the domain name.bool isValidDomain(string str){ // Regex to check valid domain name. const regex pattern(\"^(?!-)[A-Za-z0-9-]+([\\\\-\\\\.]{1}[a-z0-9]+)*\\\\.[A-Za-z]{2,6}$\"); // If the domain name // is empty return false if (str.empty()) { return false; } // Return true if the domain name // matched the ReGex if(regex_match(str, pattern)) { return true; } else { return false; }} // Driver Codeint main(){ // Test Case 1: string str1 = \"geeksforgeeks.org\"; cout << isValidDomain(str1) << endl; // Test Case 2: string str2 = \"contribute.geeksforgeeks.org\"; cout << isValidDomain(str2) << endl; // Test Case 3: string str3 = \"-geeksforgeeks.org\"; cout << isValidDomain(str3) << endl; // Test Case 4: string str4 = \"geeksforgeeks.o\"; cout << isValidDomain(str4) << endl; // Test Case 5: string str5 = \".org\"; cout << isValidDomain(str5) << endl; return 0;} // This code is contributed by yuvraj_chandra", "e": 31160, "s": 30062, "text": null }, { "code": "// Java program to validate domain name.// using regular expression. import java.util.regex.*;class GFG { // Function to validate domain name. public static boolean isValidDomain(String str) { // Regex to check valid domain name. String regex = \"^((?!-)[A-Za-z0-9-]\" + \"{1,63}(?<!-)\\\\.)\" + \"+[A-Za-z]{2,6}\"; // Compile the ReGex Pattern p = Pattern.compile(regex); // If the string is empty // return false if (str == null) { return false; } // Pattern class contains matcher() // method to find the matching // between the given string and // regular expression. Matcher m = p.matcher(str); // Return if the string // matched the ReGex return m.matches(); } // Driver Code public static void main(String args[]) { // Test Case 1: String str1 = \"geeksforgeeks.org\"; System.out.println(isValidDomain(str1)); // Test Case 2: String str2 = \"contribute.geeksforgeeks.org\"; System.out.println(isValidDomain(str2)); // Test Case 3: String str3 = \"-geeksforgeeks.org\"; System.out.println(isValidDomain(str3)); // Test Case 4: String str4 = \"geeksforgeeks.o\"; System.out.println(isValidDomain(str4)); // Test Case 5: String str5 = \".org\"; System.out.println(isValidDomain(str5)); }}", "e": 32653, "s": 31160, "text": null }, { "code": "# Python3 program to validate# domain name# using regular expressionimport re # Function to validate# domain name.def isValidDomain(str): # Regex to check valid # domain name. regex = \"^((?!-)[A-Za-z0-9-]\" + \"{1,63}(?<!-)\\\\.)\" + \"+[A-Za-z]{2,6}\" # Compile the ReGex p = re.compile(regex) # If the string is empty # return false if (str == None): return False # Return if the string # matched the ReGex if(re.search(p, str)): return True else: return False # Driver code # Test Case 1:str1 = \"geeksforgeeks.org\"print(isValidDomain(str1)) # Test Case 2:str2 = \"contribute.geeksforgeeks.org\"print(isValidDomain(str2)) # Test Case 3:str3 = \"-geeksforgeeks.org\"print(isValidDomain(str3)) # Test Case 4:str4 = \"geeksforgeeks.o\"print(isValidDomain(str4)) # Test Case 5:str5 = \".org\"print(isValidDomain(str5)) # This code is contributed by avanitrachhadiya2155", "e": 33594, "s": 32653, "text": null }, { "code": null, "e": 33622, "s": 33594, "text": "true\ntrue\nfalse\nfalse\nfalse" }, { "code": null, "e": 33645, "s": 33624, "text": "avanitrachhadiya2155" }, { "code": null, "e": 33660, "s": 33645, "text": "yuvraj_chandra" }, { "code": null, "e": 33670, "s": 33660, "text": "CPP-regex" }, { "code": null, "e": 33694, "s": 33670, "text": "java-regular-expression" }, { "code": null, "e": 33713, "s": 33694, "text": "regular-expression" }, { "code": null, "e": 33731, "s": 33713, "text": "Pattern Searching" }, { "code": null, "e": 33739, "s": 33731, "text": "Strings" }, { "code": null, "e": 33747, "s": 33739, "text": "Strings" }, { "code": null, "e": 33765, "s": 33747, "text": "Pattern Searching" }, { "code": null, "e": 33863, "s": 33765, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33907, "s": 33863, "text": "Boyer Moore Algorithm for Pattern Searching" }, { "code": null, "e": 33948, "s": 33907, "text": "Search a Word in a 2D Grid of characters" }, { "code": null, "e": 34000, "s": 33948, "text": "How to check if string contains only digits in Java" }, { "code": null, "e": 34087, "s": 34000, "text": "Check if a string contains uppercase, lowercase, special characters and numeric values" }, { "code": null, "e": 34130, "s": 34087, "text": "Applications of String Matching Algorithms" }, { "code": null, "e": 34176, "s": 34130, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 34201, "s": 34176, "text": "Reverse a string in Java" }, { "code": null, "e": 34261, "s": 34201, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 34276, "s": 34261, "text": "C++ Data Types" } ]
wxPython – change size of Button
26 Jun, 2020 In this article we are going to lean about SetSize() function associated with wx.Button class of wxPython. SetSize() function is simply used to change the size of the button present in the frame. SetSize function takes a wxSize argument to change the size of button. Syntax: wx.Button.SetSize(self, size) Parameters: Code Example: import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): self.locale = wx.Locale(wx.LANGUAGE_ENGLISH) # create parent panel for button self.pnl = wx.Panel(self) # create button at point (20, 20) self.st = wx.Button(self.pnl, id = 1, label ="Button", pos =(20, 20), size =(300, 40), name ="button") # change size of button self.st.SetSize((100, 50)) self.SetSize((350, 250)) self.SetTitle('wx.Button') self.Centre() def main(): app = wx.App() ex = Example(None) ex.Show() app.MainLoop() if __name__ == '__main__': main() Output Window: Python wxPython-Button Python-gui Python-wxPython Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jun, 2020" }, { "code": null, "e": 295, "s": 28, "text": "In this article we are going to lean about SetSize() function associated with wx.Button class of wxPython. SetSize() function is simply used to change the size of the button present in the frame. SetSize function takes a wxSize argument to change the size of button." }, { "code": null, "e": 333, "s": 295, "text": "Syntax: wx.Button.SetSize(self, size)" }, { "code": null, "e": 345, "s": 333, "text": "Parameters:" }, { "code": null, "e": 359, "s": 345, "text": "Code Example:" }, { "code": "import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): self.locale = wx.Locale(wx.LANGUAGE_ENGLISH) # create parent panel for button self.pnl = wx.Panel(self) # create button at point (20, 20) self.st = wx.Button(self.pnl, id = 1, label =\"Button\", pos =(20, 20), size =(300, 40), name =\"button\") # change size of button self.st.SetSize((100, 50)) self.SetSize((350, 250)) self.SetTitle('wx.Button') self.Centre() def main(): app = wx.App() ex = Example(None) ex.Show() app.MainLoop() if __name__ == '__main__': main()", "e": 1139, "s": 359, "text": null }, { "code": null, "e": 1154, "s": 1139, "text": "Output Window:" }, { "code": null, "e": 1177, "s": 1154, "text": "Python wxPython-Button" }, { "code": null, "e": 1188, "s": 1177, "text": "Python-gui" }, { "code": null, "e": 1204, "s": 1188, "text": "Python-wxPython" }, { "code": null, "e": 1211, "s": 1204, "text": "Python" } ]
Gradient Descent in Linear Regression
19 Nov, 2021 In linear regression, the model targets to get the best-fit regression line to predict the value of y based on the given input value (x). While training the model, the model calculates the cost function which measures the Root Mean Squared error between the predicted value (pred) and true value (y). The model targets to minimize the cost function. To minimize the cost function, the model needs to have the best value of θ1 and θ2. Initially model selects θ1 and θ2 values randomly and then iteratively update these value in order to minimize the cost function until it reaches the minimum. By the time model achieves the minimum cost function, it will have the best θ1 and θ2 values. Using these finally updated values of θ1 and θ2 in the hypothesis equation of linear equation, the model predicts the value of x in the best manner it can. Therefore, the question arises – How do θ1 and θ2 values get updated? Linear Regression Cost Function: Gradient Descent Algorithm For Linear Regression -> θj : Weights of the hypothesis. -> hθ(xi) : predicted y value for ith input. -> j : Feature index number (can be 0, 1, 2, ......, n). -> α : Learning Rate of Gradient Descent. We graph cost function as a function of parameter estimates i.e. parameter range of our hypothesis function and the cost resulting from selecting a particular set of parameters. We move downward towards pits in the graph, to find the minimum value. The way to do this is taking derivative of cost function as explained in the above figure. Gradient Descent step-downs the cost function in the direction of the steepest descent. The size of each step is determined by parameter α known as Learning Rate. In the Gradient Descent algorithm, one can infer two points : If slope is +ve : θj = θj – (+ve value). Hence value of θj decreases. If slope is -ve : θj = θj – (-ve value). Hence value of θj increases. The choice of correct learning rate is very important as it ensures that Gradient Descent converges in a reasonable time. : If we choose α to be very large, Gradient Descent can overshoot the minimum. It may fail to converge or even diverge. If we choose α to be very small, Gradient Descent will take small steps to reach local minima and will take a longer time to reach minima. For linear regression Cost, the Function graph is always convex shaped. Python3 # Implementation of gradient descent in linear regressionimport numpy as npimport matplotlib.pyplot as plt class Linear_Regression: def __init__(self, X, Y): self.X = X self.Y = Y self.b = [0, 0] def update_coeffs(self, learning_rate): Y_pred = self.predict() Y = self.Y m = len(Y) self.b[0] = self.b[0] - (learning_rate * ((1/m) * np.sum(Y_pred - Y))) self.b[1] = self.b[1] - (learning_rate * ((1/m) * np.sum((Y_pred - Y) * self.X))) def predict(self, X=[]): Y_pred = np.array([]) if not X: X = self.X b = self.b for x in X: Y_pred = np.append(Y_pred, b[0] + (b[1] * x)) return Y_pred def get_current_accuracy(self, Y_pred): p, e = Y_pred, self.Y n = len(Y_pred) return 1-sum( [ abs(p[i]-e[i])/e[i] for i in range(n) if e[i] != 0] )/n #def predict(self, b, yi): def compute_cost(self, Y_pred): m = len(self.Y) J = (1 / 2*m) * (np.sum(Y_pred - self.Y)**2) return J def plot_best_fit(self, Y_pred, fig): f = plt.figure(fig) plt.scatter(self.X, self.Y, color='b') plt.plot(self.X, Y_pred, color='g') f.show() def main(): X = np.array([i for i in range(11)]) Y = np.array([2*i for i in range(11)]) regressor = Linear_Regression(X, Y) iterations = 0 steps = 100 learning_rate = 0.01 costs = [] #original best-fit line Y_pred = regressor.predict() regressor.plot_best_fit(Y_pred, 'Initial Best Fit Line') while 1: Y_pred = regressor.predict() cost = regressor.compute_cost(Y_pred) costs.append(cost) regressor.update_coeffs(learning_rate) iterations += 1 if iterations % steps == 0: print(iterations, "epochs elapsed") print("Current accuracy is :", regressor.get_current_accuracy(Y_pred)) stop = input("Do you want to stop (y/*)??") if stop == "y": break #final best-fit line regressor.plot_best_fit(Y_pred, 'Final Best Fit Line') #plot to verify cost function decreases h = plt.figure('Verification') plt.plot(range(iterations), costs, color='b') h.show() # if user wants to predict using the regressor: regressor.predict([i for i in range(10)]) if __name__ == '__main__': main() Output: Note: Gradient descent sometimes is also implemented using Regularization. BhushanBorole bhanumahesh19931 thomasbenardo96 tanwarsinghvaibhav punamsingh628700 kashishsoda Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Nov, 2021" }, { "code": null, "e": 999, "s": 52, "text": "In linear regression, the model targets to get the best-fit regression line to predict the value of y based on the given input value (x). While training the model, the model calculates the cost function which measures the Root Mean Squared error between the predicted value (pred) and true value (y). The model targets to minimize the cost function. To minimize the cost function, the model needs to have the best value of θ1 and θ2. Initially model selects θ1 and θ2 values randomly and then iteratively update these value in order to minimize the cost function until it reaches the minimum. By the time model achieves the minimum cost function, it will have the best θ1 and θ2 values. Using these finally updated values of θ1 and θ2 in the hypothesis equation of linear equation, the model predicts the value of x in the best manner it can. Therefore, the question arises – How do θ1 and θ2 values get updated? Linear Regression Cost Function: " }, { "code": null, "e": 1052, "s": 1001, "text": "Gradient Descent Algorithm For Linear Regression " }, { "code": null, "e": 1247, "s": 1056, "text": "-> θj : Weights of the hypothesis.\n-> hθ(xi) : predicted y value for ith input.\n-> j : Feature index number (can be 0, 1, 2, ......, n).\n-> α : Learning Rate of Gradient Descent." }, { "code": null, "e": 1814, "s": 1247, "text": "We graph cost function as a function of parameter estimates i.e. parameter range of our hypothesis function and the cost resulting from selecting a particular set of parameters. We move downward towards pits in the graph, to find the minimum value. The way to do this is taking derivative of cost function as explained in the above figure. Gradient Descent step-downs the cost function in the direction of the steepest descent. The size of each step is determined by parameter α known as Learning Rate. In the Gradient Descent algorithm, one can infer two points : " }, { "code": null, "e": 1884, "s": 1814, "text": "If slope is +ve : θj = θj – (+ve value). Hence value of θj decreases." }, { "code": null, "e": 1954, "s": 1884, "text": "If slope is -ve : θj = θj – (-ve value). Hence value of θj increases." }, { "code": null, "e": 2080, "s": 1954, "text": "The choice of correct learning rate is very important as it ensures that Gradient Descent converges in a reasonable time. : " }, { "code": null, "e": 2200, "s": 2080, "text": "If we choose α to be very large, Gradient Descent can overshoot the minimum. It may fail to converge or even diverge. " }, { "code": null, "e": 2341, "s": 2200, "text": "If we choose α to be very small, Gradient Descent will take small steps to reach local minima and will take a longer time to reach minima. " }, { "code": null, "e": 2413, "s": 2341, "text": "For linear regression Cost, the Function graph is always convex shaped." }, { "code": null, "e": 2421, "s": 2413, "text": "Python3" }, { "code": "# Implementation of gradient descent in linear regressionimport numpy as npimport matplotlib.pyplot as plt class Linear_Regression: def __init__(self, X, Y): self.X = X self.Y = Y self.b = [0, 0] def update_coeffs(self, learning_rate): Y_pred = self.predict() Y = self.Y m = len(Y) self.b[0] = self.b[0] - (learning_rate * ((1/m) * np.sum(Y_pred - Y))) self.b[1] = self.b[1] - (learning_rate * ((1/m) * np.sum((Y_pred - Y) * self.X))) def predict(self, X=[]): Y_pred = np.array([]) if not X: X = self.X b = self.b for x in X: Y_pred = np.append(Y_pred, b[0] + (b[1] * x)) return Y_pred def get_current_accuracy(self, Y_pred): p, e = Y_pred, self.Y n = len(Y_pred) return 1-sum( [ abs(p[i]-e[i])/e[i] for i in range(n) if e[i] != 0] )/n #def predict(self, b, yi): def compute_cost(self, Y_pred): m = len(self.Y) J = (1 / 2*m) * (np.sum(Y_pred - self.Y)**2) return J def plot_best_fit(self, Y_pred, fig): f = plt.figure(fig) plt.scatter(self.X, self.Y, color='b') plt.plot(self.X, Y_pred, color='g') f.show() def main(): X = np.array([i for i in range(11)]) Y = np.array([2*i for i in range(11)]) regressor = Linear_Regression(X, Y) iterations = 0 steps = 100 learning_rate = 0.01 costs = [] #original best-fit line Y_pred = regressor.predict() regressor.plot_best_fit(Y_pred, 'Initial Best Fit Line') while 1: Y_pred = regressor.predict() cost = regressor.compute_cost(Y_pred) costs.append(cost) regressor.update_coeffs(learning_rate) iterations += 1 if iterations % steps == 0: print(iterations, \"epochs elapsed\") print(\"Current accuracy is :\", regressor.get_current_accuracy(Y_pred)) stop = input(\"Do you want to stop (y/*)??\") if stop == \"y\": break #final best-fit line regressor.plot_best_fit(Y_pred, 'Final Best Fit Line') #plot to verify cost function decreases h = plt.figure('Verification') plt.plot(range(iterations), costs, color='b') h.show() # if user wants to predict using the regressor: regressor.predict([i for i in range(10)]) if __name__ == '__main__': main()", "e": 4966, "s": 2421, "text": null }, { "code": null, "e": 4974, "s": 4966, "text": "Output:" }, { "code": null, "e": 5049, "s": 4974, "text": "Note: Gradient descent sometimes is also implemented using Regularization." }, { "code": null, "e": 5063, "s": 5049, "text": "BhushanBorole" }, { "code": null, "e": 5080, "s": 5063, "text": "bhanumahesh19931" }, { "code": null, "e": 5096, "s": 5080, "text": "thomasbenardo96" }, { "code": null, "e": 5115, "s": 5096, "text": "tanwarsinghvaibhav" }, { "code": null, "e": 5132, "s": 5115, "text": "punamsingh628700" }, { "code": null, "e": 5144, "s": 5132, "text": "kashishsoda" }, { "code": null, "e": 5161, "s": 5144, "text": "Machine Learning" }, { "code": null, "e": 5168, "s": 5161, "text": "Python" }, { "code": null, "e": 5185, "s": 5168, "text": "Machine Learning" } ]
How to Copy Struct Type Using Value and Pointer Reference in Golang?
22 Jun, 2020 A structure or struct in Golang is a user-defined data type that allows to combine data types of different kinds and act as a record.A struct variable in Golang can be copied to another variable easily using the assignment statement(=). Any changes made to the second struct will not be reflected back to the first struct. Example 1: // Golang program to illustrate copying// a structure to another variable package main import ( "fmt") // declaring a structuretype Student struct{ // declaring variables name string marks int64 stdid int64} // main functionfunc main() { // creating the instance of the // Student struct type std1 := Student{"Vani", 98, 20024} // prints the student struct fmt.Println(std1) // copying the struct student // to another variable by // using the assignment operator std2 := std1 // printing copied struct // this will have same values // as struct std1 fmt.Println(std2) // changing values of struct // std2 after copying std2.name = "Abc" std2.stdid = 20025 // printing updated struct fmt.Println(std2) } Output: {Vani 98 20024} {Vani 98 20024} {Abc 98 20025} In the case of pointer reference to the struct, the underlying memory location of the original struct and the pointer to the struct will be the same. Any changes made to the second struct will be reflected in the first struct also. Pointer to a struct is achieved by using the ampersand operator(&). It is allocated on the heap and its address is shared. Example 2: // Golang program to illustrate the// concept of a pointer to a struct package main import ( "fmt") // declaring a structuretype Person struct{ // declaring variables name string address string id int64} // main functionfunc main() { // creating the instance of the // Person struct type p1 := Person{"Vani", "Delhi", 20024} // prints the student struct fmt.Println(p1) // referencing the struct person // to another variable by // using the ampersand operator // Here, it is the pointer to the struct p2 := &p1 // printing pointer to the struct fmt.Println(p2) // changing values of struct p2 p2.name = "Abc" p2.address = "Hyderabad" // printing updated struct fmt.Println(p2) // struct p1 values will // also change since values // of p2 were also changed fmt.Println(p1) } Output: {Vani Delhi 20024} &{Vani Delhi 20024} &{Abc Hyderabad 20024} {Abc Hyderabad 20024} Golang-Pointers Golang-Program Picked Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jun, 2020" }, { "code": null, "e": 351, "s": 28, "text": "A structure or struct in Golang is a user-defined data type that allows to combine data types of different kinds and act as a record.A struct variable in Golang can be copied to another variable easily using the assignment statement(=). Any changes made to the second struct will not be reflected back to the first struct." }, { "code": null, "e": 362, "s": 351, "text": "Example 1:" }, { "code": "// Golang program to illustrate copying// a structure to another variable package main import ( \"fmt\") // declaring a structuretype Student struct{ // declaring variables name string marks int64 stdid int64} // main functionfunc main() { // creating the instance of the // Student struct type std1 := Student{\"Vani\", 98, 20024} // prints the student struct fmt.Println(std1) // copying the struct student // to another variable by // using the assignment operator std2 := std1 // printing copied struct // this will have same values // as struct std1 fmt.Println(std2) // changing values of struct // std2 after copying std2.name = \"Abc\" std2.stdid = 20025 // printing updated struct fmt.Println(std2) }", "e": 1219, "s": 362, "text": null }, { "code": null, "e": 1227, "s": 1219, "text": "Output:" }, { "code": null, "e": 1275, "s": 1227, "text": "{Vani 98 20024}\n{Vani 98 20024}\n{Abc 98 20025}\n" }, { "code": null, "e": 1630, "s": 1275, "text": "In the case of pointer reference to the struct, the underlying memory location of the original struct and the pointer to the struct will be the same. Any changes made to the second struct will be reflected in the first struct also. Pointer to a struct is achieved by using the ampersand operator(&). It is allocated on the heap and its address is shared." }, { "code": null, "e": 1641, "s": 1630, "text": "Example 2:" }, { "code": "// Golang program to illustrate the// concept of a pointer to a struct package main import ( \"fmt\") // declaring a structuretype Person struct{ // declaring variables name string address string id int64} // main functionfunc main() { // creating the instance of the // Person struct type p1 := Person{\"Vani\", \"Delhi\", 20024} // prints the student struct fmt.Println(p1) // referencing the struct person // to another variable by // using the ampersand operator // Here, it is the pointer to the struct p2 := &p1 // printing pointer to the struct fmt.Println(p2) // changing values of struct p2 p2.name = \"Abc\" p2.address = \"Hyderabad\" // printing updated struct fmt.Println(p2) // struct p1 values will // also change since values // of p2 were also changed fmt.Println(p1) }", "e": 2587, "s": 1641, "text": null }, { "code": null, "e": 2595, "s": 2587, "text": "Output:" }, { "code": null, "e": 2680, "s": 2595, "text": "{Vani Delhi 20024}\n&{Vani Delhi 20024}\n&{Abc Hyderabad 20024}\n{Abc Hyderabad 20024}\n" }, { "code": null, "e": 2696, "s": 2680, "text": "Golang-Pointers" }, { "code": null, "e": 2711, "s": 2696, "text": "Golang-Program" }, { "code": null, "e": 2718, "s": 2711, "text": "Picked" }, { "code": null, "e": 2730, "s": 2718, "text": "Go Language" } ]
PyQt5 – How to clear the content of label | clear and setText method
26 Mar, 2020 In this article, we will see how we can easily clear/erase the content of the label of PyQt5 application. This can be done in two ways – Using clear() method, this will clear the content of the label.Using setText() method with passing a blank string, this will update the content with blank string. Using clear() method, this will clear the content of the label. Using setText() method with passing a blank string, this will update the content with blank string. Syntax : label.clear() Argument : It takes no argument. Code : # importing the required libraries from PyQt5.QtWidgets import * from PyQt5 import QtCorefrom PyQt5.QtGui import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Label") # setting the geometry of window self.setGeometry(0, 0, 400, 300) # creating a label widget self.label_1 = QLabel("Label", self) # moving position self.label_1.move(100, 100) # setting up border self.label_1.setStyleSheet("border: 1px solid black;") # creating a label widget self.label_2 = QLabel("Hidden Label", self) # moving position self.label_2.move(100, 150) # setting up border self.label_2.setStyleSheet("border: 1px solid black;") # clearing the data self.label_2.clear() # 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 : Syntax : label.setText(“”) Argument : It takes string as argument, here string will be blank. Code : # importing the required libraries from PyQt5.QtWidgets import * from PyQt5 import QtCorefrom PyQt5.QtGui import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Label") # setting the geometry of window self.setGeometry(0, 0, 400, 300) # creating a label widget self.label_1 = QLabel("Label", self) # moving position self.label_1.move(100, 100) # setting up border self.label_1.setStyleSheet("border: 1px solid black;") # creating a label widget self.label_2 = QLabel("Hidden Label", self) # moving position self.label_2.move(100, 150) # setting up border self.label_2.setStyleSheet("border: 1px solid black;") # replacing content with blank self.label_2.setText("") # 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.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Mar, 2020" }, { "code": null, "e": 165, "s": 28, "text": "In this article, we will see how we can easily clear/erase the content of the label of PyQt5 application. This can be done in two ways –" }, { "code": null, "e": 328, "s": 165, "text": "Using clear() method, this will clear the content of the label.Using setText() method with passing a blank string, this will update the content with blank string." }, { "code": null, "e": 392, "s": 328, "text": "Using clear() method, this will clear the content of the label." }, { "code": null, "e": 492, "s": 392, "text": "Using setText() method with passing a blank string, this will update the content with blank string." }, { "code": null, "e": 515, "s": 492, "text": "Syntax : label.clear()" }, { "code": null, "e": 548, "s": 515, "text": "Argument : It takes no argument." }, { "code": null, "e": 555, "s": 548, "text": "Code :" }, { "code": "# importing the required libraries from PyQt5.QtWidgets import * from PyQt5 import QtCorefrom PyQt5.QtGui import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Label\") # setting the geometry of window self.setGeometry(0, 0, 400, 300) # creating a label widget self.label_1 = QLabel(\"Label\", self) # moving position self.label_1.move(100, 100) # setting up border self.label_1.setStyleSheet(\"border: 1px solid black;\") # creating a label widget self.label_2 = QLabel(\"Hidden Label\", self) # moving position self.label_2.move(100, 150) # setting up border self.label_2.setStyleSheet(\"border: 1px solid black;\") # clearing the data self.label_2.clear() # 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": 1631, "s": 555, "text": null }, { "code": null, "e": 1640, "s": 1631, "text": "Output :" }, { "code": null, "e": 1667, "s": 1640, "text": "Syntax : label.setText(“”)" }, { "code": null, "e": 1734, "s": 1667, "text": "Argument : It takes string as argument, here string will be blank." }, { "code": null, "e": 1741, "s": 1734, "text": "Code :" }, { "code": "# importing the required libraries from PyQt5.QtWidgets import * from PyQt5 import QtCorefrom PyQt5.QtGui import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Label\") # setting the geometry of window self.setGeometry(0, 0, 400, 300) # creating a label widget self.label_1 = QLabel(\"Label\", self) # moving position self.label_1.move(100, 100) # setting up border self.label_1.setStyleSheet(\"border: 1px solid black;\") # creating a label widget self.label_2 = QLabel(\"Hidden Label\", self) # moving position self.label_2.move(100, 150) # setting up border self.label_2.setStyleSheet(\"border: 1px solid black;\") # replacing content with blank self.label_2.setText(\"\") # 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": 2826, "s": 1741, "text": null }, { "code": null, "e": 2835, "s": 2826, "text": "Output :" }, { "code": null, "e": 2846, "s": 2835, "text": "Python-gui" }, { "code": null, "e": 2858, "s": 2846, "text": "Python-PyQt" }, { "code": null, "e": 2865, "s": 2858, "text": "Python" } ]
HTTP headers | Transfer-Encoding
31 Oct, 2019 The HTTP Transfer-Encoding is a response-type header that performs as the hop-by-hop header, the hop-by-hop header connection is the single transport-level connection must not be re-transmitted. This header is performing between two nodes (single transport-level connection). If there is multi-node connection then have to use other Transfer-Encoding values. There is an end-to-end Content-Encoding header that can be use to compress the data over the whole connection. syntax: Transfer-Encoding: chunked | compress | deflate | gzip | identity Directives: This header accepts five directives mentioned above and described below: chunked: This directive is used to send the series of data in a chunk format, but have to mentioned the length of each chunk before sending the chunk of the data in hexadecimal format like '\r\n' and then the chunk itself, followed by another '\r\n'. compress: It is a compression format using the Lempel-Ziv-Welch (LZW) algorithm. deflate: It is a compression format using the zlib structure, with the deflate compression algorithm. gzip: It is a compression format using the Lempel-Ziv coding (LZ77), with a 32-bit CRC. identity: This directive Indicates the identity function which is always acceptable. Note: The terminating chunks are the regular chunks, length of those chunks by default zero. Example: The chunk encoding for this header is useful when the server sending the huge amount of series of data to the client. The total size of the response may be unknown until the request has been completed. Suppose there is a large amount of data from a database query, a chunked response looks like this HTTP/1.0 200 OK Content-Type: text/plain Transfer-Encoding: chunked 0\r\n Mozilla\r\n 7\r\n Developer\r\n 9\r\n Network\r\n 0\r\n \r\n To check this Transfer-Encoding in action go to Inspect Element -> Network check the request header for Transfer-Encoding like below, Transfer-Encoding is highlighted you can see. Supported Browsers: The browsers are compatible with HTTP Transfer-Encoding header are listed below: Google Chrome Internet Explorer Firefox Safari Opera HTTP-headers Picked Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n31 Oct, 2019" }, { "code": null, "e": 522, "s": 52, "text": "The HTTP Transfer-Encoding is a response-type header that performs as the hop-by-hop header, the hop-by-hop header connection is the single transport-level connection must not be re-transmitted. This header is performing between two nodes (single transport-level connection). If there is multi-node connection then have to use other Transfer-Encoding values. There is an end-to-end Content-Encoding header that can be use to compress the data over the whole connection." }, { "code": null, "e": 530, "s": 522, "text": "syntax:" }, { "code": null, "e": 596, "s": 530, "text": "Transfer-Encoding: chunked | compress | deflate | gzip | identity" }, { "code": null, "e": 681, "s": 596, "text": "Directives: This header accepts five directives mentioned above and described below:" }, { "code": null, "e": 932, "s": 681, "text": "chunked: This directive is used to send the series of data in a chunk format, but have to mentioned the length of each chunk before sending the chunk of the data in hexadecimal format like '\\r\\n' and then the chunk itself, followed by another '\\r\\n'." }, { "code": null, "e": 1013, "s": 932, "text": "compress: It is a compression format using the Lempel-Ziv-Welch (LZW) algorithm." }, { "code": null, "e": 1115, "s": 1013, "text": "deflate: It is a compression format using the zlib structure, with the deflate compression algorithm." }, { "code": null, "e": 1203, "s": 1115, "text": "gzip: It is a compression format using the Lempel-Ziv coding (LZ77), with a 32-bit CRC." }, { "code": null, "e": 1288, "s": 1203, "text": "identity: This directive Indicates the identity function which is always acceptable." }, { "code": null, "e": 1381, "s": 1288, "text": "Note: The terminating chunks are the regular chunks, length of those chunks by default zero." }, { "code": null, "e": 1690, "s": 1381, "text": "Example: The chunk encoding for this header is useful when the server sending the huge amount of series of data to the client. The total size of the response may be unknown until the request has been completed. Suppose there is a large amount of data from a database query, a chunked response looks like this" }, { "code": null, "e": 1830, "s": 1690, "text": "HTTP/1.0 200 OK \nContent-Type: text/plain \nTransfer-Encoding: chunked\n\n0\\r\\n\nMozilla\\r\\n \n7\\r\\n\nDeveloper\\r\\n\n9\\r\\n\nNetwork\\r\\n\n0\\r\\n \n\\r\\n" }, { "code": null, "e": 2010, "s": 1830, "text": "To check this Transfer-Encoding in action go to Inspect Element -> Network check the request header for Transfer-Encoding like below, Transfer-Encoding is highlighted you can see." }, { "code": null, "e": 2111, "s": 2010, "text": "Supported Browsers: The browsers are compatible with HTTP Transfer-Encoding header are listed below:" }, { "code": null, "e": 2125, "s": 2111, "text": "Google Chrome" }, { "code": null, "e": 2143, "s": 2125, "text": "Internet Explorer" }, { "code": null, "e": 2151, "s": 2143, "text": "Firefox" }, { "code": null, "e": 2158, "s": 2151, "text": "Safari" }, { "code": null, "e": 2164, "s": 2158, "text": "Opera" }, { "code": null, "e": 2177, "s": 2164, "text": "HTTP-headers" }, { "code": null, "e": 2184, "s": 2177, "text": "Picked" }, { "code": null, "e": 2203, "s": 2184, "text": "Technical Scripter" }, { "code": null, "e": 2220, "s": 2203, "text": "Web Technologies" } ]
Python | Django News App
14 Dec, 2020 Django is a high-level framework which is written in Python which allows us to create server-side web applications. In this article, we will see how to create a News application using Django. We will be using News Api and fetch all the headline news from the api. Read more about the api here news api.Do the Following steps in command prompt or terminal: Open the newsproject folder using a text editor. The directory structure should look like this Create a “templates” folder in your newsapp and it in settings.pySettings .py In views.py –In views, we create a view named index which takes a request and renders an html as a response. Firstly we import newsapi from NewsApiClient. # importing apifrom django.shortcuts import renderfrom newsapi import NewsApiClient # Create your views here. def index(request): newsapi = NewsApiClient(api_key ='YOURAPIKEY') top = newsapi.get_top_headlines(sources ='techcrunch') l = top['articles'] desc =[] news =[] img =[] for i in range(len(l)): f = l[i] news.append(f['title']) desc.append(f['description']) img.append(f['urlToImage']) mylist = zip(news, desc, img) return render(request, 'index.html', context ={"mylist":mylist}) Create a index.html in templates folder. html <!DOCTYPE html><html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"><!-- Optional theme --> </head> <body> <div class="jumbotron" style="color:black"> <h1 style ="color:white"> Get The latest news on our website </h1> </div> <div class="container"> {% for new, des, i in mylist %} <img src="{{ i }}" alt=""> <h1>news:</h1> {{ new }} {{ value|linebreaks }} <h4>description:</h4>{{ des }} {{ value|linebreaks }} {% endfor %} </div> </body></html> Now map the views to urls.py from django.contrib import adminfrom django.urls import pathfrom newsapp import views urlpatterns = [ path('', views.index, name ='index'), path('admin/', admin.site.urls),] Your output of the project should look like this – roopsai Python Django Project Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Dec, 2020" }, { "code": null, "e": 412, "s": 54, "text": "Django is a high-level framework which is written in Python which allows us to create server-side web applications. In this article, we will see how to create a News application using Django. We will be using News Api and fetch all the headline news from the api. Read more about the api here news api.Do the Following steps in command prompt or terminal: " }, { "code": null, "e": 509, "s": 412, "text": "Open the newsproject folder using a text editor. The directory structure should look like this " }, { "code": null, "e": 589, "s": 509, "text": "Create a “templates” folder in your newsapp and it in settings.pySettings .py " }, { "code": null, "e": 746, "s": 589, "text": "In views.py –In views, we create a view named index which takes a request and renders an html as a response. Firstly we import newsapi from NewsApiClient. " }, { "code": "# importing apifrom django.shortcuts import renderfrom newsapi import NewsApiClient # Create your views here. def index(request): newsapi = NewsApiClient(api_key ='YOURAPIKEY') top = newsapi.get_top_headlines(sources ='techcrunch') l = top['articles'] desc =[] news =[] img =[] for i in range(len(l)): f = l[i] news.append(f['title']) desc.append(f['description']) img.append(f['urlToImage']) mylist = zip(news, desc, img) return render(request, 'index.html', context ={\"mylist\":mylist})", "e": 1302, "s": 746, "text": null }, { "code": null, "e": 1346, "s": 1302, "text": " Create a index.html in templates folder. " }, { "code": null, "e": 1351, "s": 1346, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\" dir=\"ltr\"> <head> <meta charset=\"utf-8\"> <title></title> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\" crossorigin=\"anonymous\"><!-- Optional theme --> </head> <body> <div class=\"jumbotron\" style=\"color:black\"> <h1 style =\"color:white\"> Get The latest news on our website </h1> </div> <div class=\"container\"> {% for new, des, i in mylist %} <img src=\"{{ i }}\" alt=\"\"> <h1>news:</h1> {{ new }} {{ value|linebreaks }} <h4>description:</h4>{{ des }} {{ value|linebreaks }} {% endfor %} </div> </body></html>", "e": 2151, "s": 1351, "text": null }, { "code": null, "e": 2183, "s": 2151, "text": " Now map the views to urls.py " }, { "code": "from django.contrib import adminfrom django.urls import pathfrom newsapp import views urlpatterns = [ path('', views.index, name ='index'), path('admin/', admin.site.urls),]", "e": 2363, "s": 2183, "text": null }, { "code": null, "e": 2416, "s": 2363, "text": "Your output of the project should look like this – " }, { "code": null, "e": 2424, "s": 2416, "text": "roopsai" }, { "code": null, "e": 2438, "s": 2424, "text": "Python Django" }, { "code": null, "e": 2446, "s": 2438, "text": "Project" }, { "code": null, "e": 2453, "s": 2446, "text": "Python" } ]
PHP Arrays
An array stores multiple values in one single variable: An array is a special variable, which can hold more than one value at a time. If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this: However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300? The solution is to create an array! An array can hold many values under a single name, and you can access the values by referring to an index number. In PHP, the array() function is used to create an array: In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index Associative arrays - Arrays with named keys Multidimensional arrays - Arrays containing one or more arrays The count() function is used to return the length (the number of elements) of an array: For a complete reference of all array functions, go to our complete PHP Array Reference. The reference contains a brief description, and examples of use, for each function! Use the correct function to output the number of items in an array. $fruits = array("Apple", "Banana", "Orange"); echo ; We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 56, "s": 0, "text": "An array stores multiple values in one single variable:" }, { "code": null, "e": 134, "s": 56, "text": "An array is a special variable, which can hold more than one value at a time." }, { "code": null, "e": 257, "s": 134, "text": "If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:" }, { "code": null, "e": 374, "s": 257, "text": "However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?" }, { "code": null, "e": 410, "s": 374, "text": "The solution is to create an array!" }, { "code": null, "e": 524, "s": 410, "text": "An array can hold many values under a single name, and you can access the values by referring to an index number." }, { "code": null, "e": 581, "s": 524, "text": "In PHP, the array() function is used to create an array:" }, { "code": null, "e": 622, "s": 581, "text": "In PHP, there are three types of arrays:" }, { "code": null, "e": 667, "s": 622, "text": "Indexed arrays - Arrays with a numeric index" }, { "code": null, "e": 711, "s": 667, "text": "Associative arrays - Arrays with named keys" }, { "code": null, "e": 774, "s": 711, "text": "Multidimensional arrays - Arrays containing one or more arrays" }, { "code": null, "e": 863, "s": 774, "text": "The count() function is used to return the length (the number of elements) of \nan array:" }, { "code": null, "e": 952, "s": 863, "text": "For a complete reference of all array functions, go to our complete PHP Array Reference." }, { "code": null, "e": 1036, "s": 952, "text": "The reference contains a brief description, and examples of use, for each function!" }, { "code": null, "e": 1104, "s": 1036, "text": "Use the correct function to output the number of items in an array." }, { "code": null, "e": 1158, "s": 1104, "text": "$fruits = array(\"Apple\", \"Banana\", \"Orange\");\necho ;\n" }, { "code": null, "e": 1191, "s": 1158, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1233, "s": 1191, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1340, "s": 1233, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1359, "s": 1340, "text": "[email protected]" } ]
How to Animate Bullets in Lists using CSS
To style bullets in an unordered list, we can use the list-style por The syntax of CSS li-style property as follows − li { list-style: /*value*/ } The following examples illustrate CSS li-style property. Live Demo <!DOCTYPE html> <html> <head> <style> li { margin: 3px 0; padding: 2%; width: 28%; line-height: 1.2%; list-style: none; border-radius: 5% 0 0 5%; box-shadow: -10px 2px 4px 0 chartreuse; color: cornflowerblue; } li:hover { box-shadow: -10px 2px 4px 0 blue!important; font-size: 1.4em; } </style> </head> <body> <ul> <li>a</li> <li>b</li> <li>c</li> <li>d</li> </ul> </body> </html> This gives the following output Live Demo <!DOCTYPE html> <html> <head> <style> ol { list-style: none; counter-reset: li; overflow: hidden; } li { margin-right: 10%; padding: 2%; width: 15%; float: left; line-height: 1.2%; font-weight: bold; counter-increment: li; box-shadow: inset 2px 14px 10px lightblue; } li:hover { box-shadow: inset 6px 14px 10px lightgreen!important; font-size: 1.4em; } li::before { content: counter(li); color: seagreen; display: inline-block; width: 40%; margin-left: -2em; } </style> </head> <body> <ol> <li>a</li> <li>b</li> <li>c</li> </ol> </body> </html> This gives the following output
[ { "code": null, "e": 1131, "s": 1062, "text": "To style bullets in an unordered list, we can use the list-style por" }, { "code": null, "e": 1180, "s": 1131, "text": "The syntax of CSS li-style property as follows −" }, { "code": null, "e": 1212, "s": 1180, "text": "li {\n list-style: /*value*/\n}" }, { "code": null, "e": 1269, "s": 1212, "text": "The following examples illustrate CSS li-style property." }, { "code": null, "e": 1280, "s": 1269, "text": " Live Demo" }, { "code": null, "e": 1889, "s": 1280, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n li {\n margin: 3px 0;\n padding: 2%;\n width: 28%;\n line-height: 1.2%;\n list-style: none;\n border-radius: 5% 0 0 5%;\n box-shadow: -10px 2px 4px 0 chartreuse;\n color: cornflowerblue;\n }\n li:hover {\n box-shadow: -10px 2px 4px 0 blue!important;\n font-size: 1.4em;\n }\n </style>\n </head>\n <body>\n <ul>\n <li>a</li>\n <li>b</li>\n <li>c</li>\n <li>d</li>\n </ul>\n </body>\n</html>" }, { "code": null, "e": 1921, "s": 1889, "text": "This gives the following output" }, { "code": null, "e": 1932, "s": 1921, "text": " Live Demo" }, { "code": null, "e": 2828, "s": 1932, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n ol {\n list-style: none;\n counter-reset: li;\n overflow: hidden;\n }\n li {\n margin-right: 10%;\n padding: 2%;\n width: 15%;\n float: left;\n line-height: 1.2%;\n font-weight: bold;\n counter-increment: li;\n box-shadow: inset 2px 14px 10px lightblue;\n }\n li:hover {\n box-shadow: inset 6px 14px 10px lightgreen!important;\n font-size: 1.4em;\n }\n li::before {\n content: counter(li);\n color: seagreen;\n display: inline-block;\n width: 40%;\n margin-left: -2em;\n }\n </style>\n </head>\n <body>\n <ol>\n <li>a</li>\n <li>b</li>\n <li>c</li>\n </ol>\n </body>\n</html>" }, { "code": null, "e": 2860, "s": 2828, "text": "This gives the following output" } ]
Trapping Rain Water | Practice | GeeksforGeeks
Given an array arr[] of N non-negative integers representing the height of blocks. If width of each block is 1, compute how much water can be trapped between the blocks during the rainy season. Example 1: Input: N = 6 arr[] = {3,0,0,2,0,4} Output: 10 Explanation: Example 2: Input: N = 4 arr[] = {7,4,0,9} Output: 10 Explanation: Water trapped by above block of height 4 is 3 units and above block of height 0 is 7 units. So, the total unit of water trapped is 10 units. Example 3: Input: N = 3 arr[] = {6,9,9} Output: 0 Explanation: No water will be trapped. Your Task: You don't need to read input or print anything. The task is to complete the function trappingWater() which takes arr[] and N as input parameters and returns the total amount of water that can be trapped. Expected Time Complexity: O(N) Expected Auxiliary Space: O(N) Constraints: 3 < N < 106 0 < Ai < 108 0 anuragshubham342 days ago static long trappingWater(int arr[], int n) { int i=0,j=n-1,low=arr[0],high=arr[n-1]; long result=0; while(i<j){ if(arr[i]<arr[j]){ if(arr[i]>low) { low=arr[i]; } else { result+=low-arr[i]; i++; } } else{ if(arr[j]>high){ high=arr[j]; } else{ result+=high-arr[j]; j--; } } } return result; } } 0 anuragshubham342 days ago static long trappingWater(int arr[], int n) { int[] left=new int[n]; int[] right=new int[n]; left[0]=arr[0]; for(int i=1;i<n;i++){ left[i]=Math.max(arr[i],left[i-1]); } right[n-1]=arr[n-1]; for(int j=n-2;j>=0;j--){ right[j]=Math.max(arr[j],right[j+1]); } long water=0; for(int i=0;i<n;i++){ water+=Math.min(left[i],right[i])-arr[i]; } return water; } 0 98rkgautam4 days ago class Solution{ // arr: input array // n: size of array // Function to find the trapped water between the blocks. static long trappingWater(int arr[], int n) { int i = 0 , j = n-1; long totalWater = 0; int leftMax = 0 , rightMax = 0; while(i <= j){ leftMax = Math.max(leftMax, arr[i]); rightMax = Math.max(rightMax, arr[j]); if(leftMax <= rightMax){ totalWater += leftMax - arr[i]; i++; }else if(leftMax >= rightMax) { totalWater += rightMax - arr[j]; j--; } } return totalWater; } } 0 diagovenk4 days ago Hello guys Easy java solution. Time complexity: O(n), Space complexity O(1). total time: 0.58 sec static long trappingWater(int arr[], int n) { // Your code here int leftIndex = 0; int rightIndex = n-1; long leftMax = 0; long rightMax = 0; long water = 0; while(leftIndex<=rightIndex){ if(arr[leftIndex] < arr[rightIndex]){ if(arr[leftIndex] >= leftMax){ leftMax = arr[leftIndex]; ++leftIndex; } else{ water += leftMax - arr[leftIndex]; ++leftIndex; } } else{ if(arr[rightIndex]>= rightMax){ rightMax = arr[rightIndex]; --rightIndex; } else{ water += rightMax - arr[rightIndex]; --rightIndex; } } } return water; } 0 iichipc14 days ago BLANKED!! 😥 class Solution{ // Function to find the trapped water between the blocks. public: long long trappingWater(int a[], int n){ int l=0, r=n-1; int n1, n2; while(l<n-1) { if(a[l]!=0 && a[l]>a[l+1]) { n1 = a[l]; break; } else l++; } while(r>0) { if(a[r]!=0 && a[r]>a[r-1]) { n2 = a[r]; break; } else r--; } int w = (r-l)-1; int ans = min(n1,n2)*w; for(int i=l+1;i<=r-1;i++) { if(a[i]!=0) ans -= a[i]; } return ans; } } ; debug it +2 15shivamk5 days ago C++ Solution long long trappingWater(int arr[], int n){ // code here int left[n] = {0}; int right[n] = {0}; left[0] = arr[0]; for(int i=1; i<n; i++){ left[i] = max(arr[i], left[i-1]); } right[n-1] = arr[n-1]; for(int j=n-2; j>=0; j--){ right[j] = max(arr[j], right[j+1]); } long long int water = 0; for(int i=0; i<n; i++){ water += min(left[i], right[i]) - arr[i]; } return water; } +1 aniket6518gadhe6 days ago JAVA SOLUTION Total Time Taken: 0.6/1.72 static long trappingWater(int arr[], int n) { int left_max=0,right_max=0,i=0; long water=0; n--; while(i<n){ if(arr[i]<arr[n]){ if(arr[i]>=left_max){ left_max=arr[i]; }else{ water+=left_max-arr[i]; } i++; }else{ if(arr[n]>=right_max){ right_max=arr[n]; }else{ water+=right_max-arr[n]; } n--; } } return water; } 0 putyavka1 week ago C++ TIME COMPLEXITY =O(N) and AUX SPACE =O(1) No need auxilary space. class Solution{ public: long long trappingWater(int arr[], int n){ int i = 0, j = n - 1; long long sum = 0; int i_val = 0; int j_val = 0; while (i < j) { while (arr[i] < arr[j]) { sum += max(0, i_val - arr[i]); i_val = max(i_val, arr[i]); i++; } while (i < j && arr[i] >= arr[j]) { sum += max(0, j_val - arr[j]); j_val = max(j_val, arr[j]); j--; } } return sum; }}; 0 shuklaakshita101 week ago C++ SOLUTION TIME COMPLEXITY =O(N) and AUX SPACE =O(N) long long trappingWater(int arr[], int n){ // code here long long res=0,l=0,r=n-1; long long max_l=0,max_r=0; while(l<=r) { if(arr[l]<=arr[r]){ if(arr[l]>=max_l) max_l=arr[l]; else res+= max_l - arr[l]; l++; } else { if(arr[r]>= max_r) max_r = arr[r]; else res+= max_r - arr[r]; r--; } } return res; } 0 lawbindpandey01w1 week ago Time complexity : O(n) and Aux Space : O(n) long long trappingWater(int arr[], int n){ // code here int lMax[n]; int rMax[n]; lMax[0] = arr[0]; rMax[n - 1] = arr[n - 1]; for(int i = 1; i < n; i++) lMax[i] = max(lMax[i - 1],arr[i]); for(int i = n - 2; i >= 0; i--) rMax[i] = max(rMax[i + 1], arr[i]); long long res = 0; for(int i = 0; i < n; i++) res += min(lMax[i], rMax[i]) - arr[i]; return res; } 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": 435, "s": 238, "text": "Given an array arr[] of N non-negative integers representing the height of blocks. If width of each block is 1, compute how much water can be trapped between the blocks during the rainy season. \n " }, { "code": null, "e": 446, "s": 435, "text": "Example 1:" }, { "code": null, "e": 508, "s": 446, "text": "Input:\nN = 6\narr[] = {3,0,0,2,0,4}\nOutput:\n10\nExplanation: \n\n" }, { "code": null, "e": 519, "s": 508, "text": "Example 2:" }, { "code": null, "e": 719, "s": 519, "text": "Input:\nN = 4\narr[] = {7,4,0,9}\nOutput:\n10\nExplanation:\nWater trapped by above \nblock of height 4 is 3 units and above \nblock of height 0 is 7 units. So, the \ntotal unit of water trapped is 10 units.\n" }, { "code": null, "e": 730, "s": 719, "text": "Example 3:" }, { "code": null, "e": 808, "s": 730, "text": "Input:\nN = 3\narr[] = {6,9,9}\nOutput:\n0\nExplanation:\nNo water will be trapped." }, { "code": null, "e": 1024, "s": 808, "text": "\nYour Task:\nYou don't need to read input or print anything. The task is to complete the function trappingWater() which takes arr[] and N as input parameters and returns the total amount of water that can be trapped." }, { "code": null, "e": 1087, "s": 1024, "text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 1126, "s": 1087, "text": "\nConstraints:\n3 < N < 106\n0 < Ai < 108" }, { "code": null, "e": 1128, "s": 1126, "text": "0" }, { "code": null, "e": 1154, "s": 1128, "text": "anuragshubham342 days ago" }, { "code": null, "e": 1769, "s": 1154, "text": "static long trappingWater(int arr[], int n) { int i=0,j=n-1,low=arr[0],high=arr[n-1]; long result=0; while(i<j){ if(arr[i]<arr[j]){ if(arr[i]>low) { low=arr[i]; } else { result+=low-arr[i]; i++; } } else{ if(arr[j]>high){ high=arr[j]; } else{ result+=high-arr[j]; j--; } } } return result; } }" }, { "code": null, "e": 1771, "s": 1769, "text": "0" }, { "code": null, "e": 1797, "s": 1771, "text": "anuragshubham342 days ago" }, { "code": null, "e": 2255, "s": 1797, "text": "static long trappingWater(int arr[], int n) { int[] left=new int[n]; int[] right=new int[n]; left[0]=arr[0]; for(int i=1;i<n;i++){ left[i]=Math.max(arr[i],left[i-1]); } right[n-1]=arr[n-1]; for(int j=n-2;j>=0;j--){ right[j]=Math.max(arr[j],right[j+1]); } long water=0; for(int i=0;i<n;i++){ water+=Math.min(left[i],right[i])-arr[i]; } return water; } " }, { "code": null, "e": 2257, "s": 2255, "text": "0" }, { "code": null, "e": 2278, "s": 2257, "text": "98rkgautam4 days ago" }, { "code": null, "e": 2962, "s": 2278, "text": "class Solution{\n \n // arr: input array\n // n: size of array\n // Function to find the trapped water between the blocks.\n static long trappingWater(int arr[], int n) { \n int i = 0 , j = n-1;\n long totalWater = 0;\n int leftMax = 0 , rightMax = 0;\n while(i <= j){\n leftMax = Math.max(leftMax, arr[i]);\n rightMax = Math.max(rightMax, arr[j]);\n if(leftMax <= rightMax){\n totalWater += leftMax - arr[i];\n i++;\n }else if(leftMax >= rightMax) {\n totalWater += rightMax - arr[j];\n j--;\n }\n }\n return totalWater;\n } \n}" }, { "code": null, "e": 2964, "s": 2962, "text": "0" }, { "code": null, "e": 2984, "s": 2964, "text": "diagovenk4 days ago" }, { "code": null, "e": 3082, "s": 2984, "text": "Hello guys Easy java solution. Time complexity: O(n), Space complexity O(1). total time: 0.58 sec" }, { "code": null, "e": 3963, "s": 3084, "text": "static long trappingWater(int arr[], int n) { // Your code here int leftIndex = 0; int rightIndex = n-1; long leftMax = 0; long rightMax = 0; long water = 0; while(leftIndex<=rightIndex){ if(arr[leftIndex] < arr[rightIndex]){ if(arr[leftIndex] >= leftMax){ leftMax = arr[leftIndex]; ++leftIndex; } else{ water += leftMax - arr[leftIndex]; ++leftIndex; } } else{ if(arr[rightIndex]>= rightMax){ rightMax = arr[rightIndex]; --rightIndex; } else{ water += rightMax - arr[rightIndex]; --rightIndex; } } } return water; } " }, { "code": null, "e": 3965, "s": 3963, "text": "0" }, { "code": null, "e": 3984, "s": 3965, "text": "iichipc14 days ago" }, { "code": null, "e": 3994, "s": 3984, "text": "BLANKED!!" }, { "code": null, "e": 3996, "s": 3994, "text": "😥" }, { "code": null, "e": 4012, "s": 3996, "text": "class Solution{" }, { "code": null, "e": 4707, "s": 4012, "text": " // Function to find the trapped water between the blocks. public: long long trappingWater(int a[], int n){ int l=0, r=n-1; int n1, n2; while(l<n-1) { if(a[l]!=0 && a[l]>a[l+1]) { n1 = a[l]; break; } else l++; } while(r>0) { if(a[r]!=0 && a[r]>a[r-1]) { n2 = a[r]; break; } else r--; } int w = (r-l)-1; int ans = min(n1,n2)*w; for(int i=l+1;i<=r-1;i++) { if(a[i]!=0) ans -= a[i]; } return ans; }" }, { "code": null, "e": 4711, "s": 4707, "text": "} ;" }, { "code": null, "e": 4722, "s": 4713, "text": "debug it" }, { "code": null, "e": 4727, "s": 4724, "text": "+2" }, { "code": null, "e": 4747, "s": 4727, "text": "15shivamk5 days ago" }, { "code": null, "e": 4760, "s": 4747, "text": "C++ Solution" }, { "code": null, "e": 5263, "s": 4762, "text": "long long trappingWater(int arr[], int n){ // code here int left[n] = {0}; int right[n] = {0}; left[0] = arr[0]; for(int i=1; i<n; i++){ left[i] = max(arr[i], left[i-1]); } right[n-1] = arr[n-1]; for(int j=n-2; j>=0; j--){ right[j] = max(arr[j], right[j+1]); } long long int water = 0; for(int i=0; i<n; i++){ water += min(left[i], right[i]) - arr[i]; } return water; }" }, { "code": null, "e": 5266, "s": 5263, "text": "+1" }, { "code": null, "e": 5292, "s": 5266, "text": "aniket6518gadhe6 days ago" }, { "code": null, "e": 5307, "s": 5292, "text": "JAVA SOLUTION " }, { "code": null, "e": 5325, "s": 5307, "text": "Total Time Taken:" }, { "code": null, "e": 5334, "s": 5325, "text": "0.6/1.72" }, { "code": null, "e": 5909, "s": 5336, "text": "static long trappingWater(int arr[], int n) { int left_max=0,right_max=0,i=0; long water=0; n--; while(i<n){ if(arr[i]<arr[n]){ if(arr[i]>=left_max){ left_max=arr[i]; }else{ water+=left_max-arr[i]; } i++; }else{ if(arr[n]>=right_max){ right_max=arr[n]; }else{ water+=right_max-arr[n]; } n--; } } return water; } " }, { "code": null, "e": 5911, "s": 5909, "text": "0" }, { "code": null, "e": 5930, "s": 5911, "text": "putyavka1 week ago" }, { "code": null, "e": 5935, "s": 5930, "text": "C++ " }, { "code": null, "e": 5977, "s": 5935, "text": "TIME COMPLEXITY =O(N) and AUX SPACE =O(1)" }, { "code": null, "e": 6001, "s": 5977, "text": "No need auxilary space." }, { "code": null, "e": 6539, "s": 6001, "text": "class Solution{ public: long long trappingWater(int arr[], int n){ int i = 0, j = n - 1; long long sum = 0; int i_val = 0; int j_val = 0; while (i < j) { while (arr[i] < arr[j]) { sum += max(0, i_val - arr[i]); i_val = max(i_val, arr[i]); i++; } while (i < j && arr[i] >= arr[j]) { sum += max(0, j_val - arr[j]); j_val = max(j_val, arr[j]); j--; } } return sum; }};" }, { "code": null, "e": 6541, "s": 6539, "text": "0" }, { "code": null, "e": 6567, "s": 6541, "text": "shuklaakshita101 week ago" }, { "code": null, "e": 6580, "s": 6567, "text": "C++ SOLUTION" }, { "code": null, "e": 6622, "s": 6580, "text": "TIME COMPLEXITY =O(N) and AUX SPACE =O(N)" }, { "code": null, "e": 7064, "s": 6622, "text": " long long trappingWater(int arr[], int n){ // code here long long res=0,l=0,r=n-1; long long max_l=0,max_r=0; while(l<=r) { if(arr[l]<=arr[r]){ if(arr[l]>=max_l) max_l=arr[l]; else res+= max_l - arr[l]; l++; } else { if(arr[r]>= max_r) max_r = arr[r]; else res+= max_r - arr[r]; r--; } } return res; }" }, { "code": null, "e": 7066, "s": 7064, "text": "0" }, { "code": null, "e": 7093, "s": 7066, "text": "lawbindpandey01w1 week ago" }, { "code": null, "e": 7137, "s": 7093, "text": "Time complexity : O(n) and Aux Space : O(n)" }, { "code": null, "e": 7615, "s": 7139, "text": "long long trappingWater(int arr[], int n){ // code here int lMax[n]; int rMax[n]; lMax[0] = arr[0]; rMax[n - 1] = arr[n - 1]; for(int i = 1; i < n; i++) lMax[i] = max(lMax[i - 1],arr[i]); for(int i = n - 2; i >= 0; i--) rMax[i] = max(rMax[i + 1], arr[i]); long long res = 0; for(int i = 0; i < n; i++) res += min(lMax[i], rMax[i]) - arr[i]; return res; }" }, { "code": null, "e": 7761, "s": 7615, "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": 7797, "s": 7761, "text": " Login to access your submissions. " }, { "code": null, "e": 7807, "s": 7797, "text": "\nProblem\n" }, { "code": null, "e": 7817, "s": 7807, "text": "\nContest\n" }, { "code": null, "e": 7880, "s": 7817, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8028, "s": 7880, "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": 8236, "s": 8028, "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": 8342, "s": 8236, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Gerrit - Installation
Before you can use Gerrit, you have to install Git and perform some basic configuration changes. Following are the steps to install Git client on different platforms. You can install the Git on Linux by using the software package management tool. For instance, if you are using Fedora, you can use as − sudo yum install git If you are using Debian-based distribution such as Ubuntu, then use the following command − sudo apt-get install git You can install Git on Windows by downloading it from the Git website. Just go to msysgit.github.io link and click on the download button. Git can be installed on Mac using the following command − brew install git Another way of installing Git is, by downloading it from Git website. Just go to Git install on Mac link, which will install Git for Mac platform. Print Add Notes Bookmark this page
[ { "code": null, "e": 2405, "s": 2238, "text": "Before you can use Gerrit, you have to install Git and perform some basic configuration changes. Following are the steps to install Git client on different platforms." }, { "code": null, "e": 2541, "s": 2405, "text": "You can install the Git on Linux by using the software package management tool. For instance, if you are using Fedora, you can use as −" }, { "code": null, "e": 2563, "s": 2541, "text": "sudo yum install git\n" }, { "code": null, "e": 2655, "s": 2563, "text": "If you are using Debian-based distribution such as Ubuntu, then use the following command −" }, { "code": null, "e": 2681, "s": 2655, "text": "sudo apt-get install git\n" }, { "code": null, "e": 2821, "s": 2681, "text": "You can install Git on Windows by downloading it from the Git website. Just go to msysgit.github.io link and click on the download button." }, { "code": null, "e": 2879, "s": 2821, "text": "Git can be installed on Mac using the following command −" }, { "code": null, "e": 2897, "s": 2879, "text": "brew install git\n" }, { "code": null, "e": 3044, "s": 2897, "text": "Another way of installing Git is, by downloading it from Git website. Just go to Git install on Mac link, which will install Git for Mac platform." }, { "code": null, "e": 3051, "s": 3044, "text": " Print" }, { "code": null, "e": 3062, "s": 3051, "text": " Add Notes" } ]
Pascal - Nested if-then Statements
It is always legal in Pascal programming to nest if-else statements, which means you can use one if or else if statement inside another if or else if statement(s). Pascal allows nesting to any level, however, if depends on Pascal implementation on a particular system. The syntax for a nested if statement is as follows − if( boolean_expression 1) then if(boolean_expression 2)then S1 else S2; You can nest else if-then-else in the similar way as you have nested if-then statement. Please note that, the nested if-then-else constructs gives rise to some ambiguity as to which else statement pairs with which if statement. The rule is that the else keyword matches the first if keyword (searching backwards) not already matched by an else keyword. The above syntax is equivalent to if( boolean_expression 1) then begin if(boolean_expression 2)then S1 else S2; end; It is not equivalent to if ( boolean_expression 1) then begin if exp2 then S1 end; else S2; Therefore, if the situation demands the later construct, then you must put begin and end keywords at the right place. program nested_ifelseChecking; var { local variable definition } a, b : integer; begin a := 100; b:= 200; (* check the boolean condition *) if (a = 100) then (* if condition is true then check the following *) if ( b = 200 ) then (* if nested if condition is true then print the following *) writeln('Value of a is 100 and value of b is 200' ); writeln('Exact value of a is: ', a ); writeln('Exact value of b is: ', b ); end. When the above code is compiled and executed, 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 94 Lectures 8.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2352, "s": 2083, "text": "It is always legal in Pascal programming to nest if-else statements, which means you can use one if or else if statement inside another if or else if statement(s). Pascal allows nesting to any level, however, if depends on Pascal implementation on a particular system." }, { "code": null, "e": 2405, "s": 2352, "text": "The syntax for a nested if statement is as follows −" }, { "code": null, "e": 2484, "s": 2405, "text": "if( boolean_expression 1) then\n if(boolean_expression 2)then S1\n\nelse\n S2;" }, { "code": null, "e": 2838, "s": 2484, "text": "You can nest else if-then-else in the similar way as you have nested if-then statement. Please note that, the nested if-then-else constructs gives rise to some ambiguity as to which else statement pairs with which if statement. The rule is that the else keyword matches the first if keyword (searching backwards) not already matched by an else keyword. " }, { "code": null, "e": 2872, "s": 2838, "text": "The above syntax is equivalent to" }, { "code": null, "e": 2977, "s": 2872, "text": "if( boolean_expression 1) then\nbegin\n if(boolean_expression 2)then\n S1\n \n else\n S2;\nend;" }, { "code": null, "e": 3001, "s": 2977, "text": "It is not equivalent to" }, { "code": null, "e": 3099, "s": 3001, "text": "if ( boolean_expression 1) then \nbegin \n if exp2 then \n S1 \nend; \n else \n S2;" }, { "code": null, "e": 3218, "s": 3099, "text": "Therefore, if the situation demands the later construct, then you must put begin and end keywords at the right place. " }, { "code": null, "e": 3708, "s": 3218, "text": "program nested_ifelseChecking;\nvar\n { local variable definition }\n a, b : integer;\n\nbegin\n a := 100;\n b:= 200;\n \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 nested if condition is true then print the following *)\n writeln('Value of a is 100 and value of b is 200' );\n \n writeln('Exact value of a is: ', a );\n writeln('Exact value of b is: ', b );\nend." }, { "code": null, "e": 3789, "s": 3708, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3873, "s": 3789, "text": "Value of a is 100 and b is 200\nExact value of a is : 100\nExact value of b is : 200\n" }, { "code": null, "e": 3908, "s": 3873, "text": "\n 94 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3931, "s": 3908, "text": " Stone River ELearning" }, { "code": null, "e": 3938, "s": 3931, "text": " Print" }, { "code": null, "e": 3949, "s": 3938, "text": " Add Notes" } ]
How to set values to list of parameters of IN clause on PreparedStatement using JDBC?
The IN clause in MYSQL database is used to specify the list of parameters in a query. For example, you need to retrieve contents of a table using specific IDs you can do so using the SELECT statement along with the IN clause as − mysql> SELECT * from sales where ID IN (1001, 1003, 1005); +------+-------------+--------------+--------------+--------------+-------+------------+ | ID | ProductName | CustomerName | DispatchDate | DeliveryTime | Price | Location | +------+-------------+--------------+--------------+--------------+-------+------------+ | 1001 | Key-Board | Raja | 2019-09-01 | 11:00:00 | 8500 | Hyderabad | | 1003 | Mouse | Puja | 2019-03-01 | 10:59:59 | 4500 | Vijayawada | | 1005 | Headset | Jalaja | 2019-04-06 | 11:08:59 | 7500 | Goa | +------+-------------+--------------+--------------+--------------+-------+------------+ 3 rows in set (0.03 sec) When you use the IN clause in prepared statement you can use bind variables for the parameters list (one for each) and set values for those later using the setter methods of the PreparedStatement interface and, after setting values to all the bind variables in the statement you can execute that particular statement using the execute() method. String query = "UPDATE sales SET price = price+1500 WHERE ProductName IN (?, ?, ? )"; PreparedStatement pstmt = con.prepareStatement(query); pstmt.setString(1, "Key-Board"); pstmt.setString(2, "Mouse"); pstmt.setString(3, "Headset"); pstmt.execute(); Let us create a table with name sales in MySQL database, with one of the columns as auto-incremented, using CREATE statement as shown below − CREATE TABLE Sales( ID INT PRIMARY KEY AUTO_INCREMENT, ProductName VARCHAR (20), CustomerName VARCHAR (20), DispatchDate date, DeliveryTime time, Price INT, Location VARCHAR(20) ); Now, we will insert 5 records in sales table using INSERT statements − insert into sales (ProductName, CustomerName, DispatchDate, DeliveryTime, Price, Location) values('Key-Board', 'Raja', DATE('2019-09-01'), TIME('11:00:00'), 7000, 'India'); insert into sales (ProductName, CustomerName, DispatchDate, DeliveryTime, Price, Location) values('Earphones', 'Roja', DATE('2019-05-01'), TIME('11:00:00'), 2000, 'Vishakhapatnam'); insert into sales (ProductName, CustomerName, DispatchDate, DeliveryTime, Price, Location) values('Mouse', 'Puja', DATE('2019-03-01'), TIME('10:59:59'), 3000, 'Vijayawada'); insert into sales (ProductName, CustomerName, DispatchDate, DeliveryTime, Price, Location) values('Mobile', 'Vanaja', DATE('2019-03-01'), TIME('10:10:52'), 9000, 'Chennai'); insert into sales (ProductName, CustomerName, DispatchDate, DeliveryTime, Price, Location) values('Headset', 'Jalaja', DATE('2019-04-06'), TIME('11:08:59'), 6000, 'Goa'); Following JDBC program establishes connection with the database and increases the price value of the products key-board, mouse and, Headset by 1500 each, using the IN clause. 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 PreparedStatement_IN_clause { public static void main(String args[]) throws SQLException { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/sample_database"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Inserting values to a table String query = "UPDATE sales SET price = price+1500 WHERE ProductName IN (?, ?, ? )"; PreparedStatement pstmt = con.prepareStatement(query); pstmt.setString(1, "Key-Board"); pstmt.setString(2, "Mouse"); pstmt.setString(3, "Headset"); pstmt.execute(); System.out.println("Price values updated ......"); System.out.println("Contents of the Sales table after the update: "); //Retrieving data Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select * from sales"); while(rs.next()) { System.out.print("Name: "+rs.getString("ProductName")+", "); System.out.print("Customer Name: "+rs.getString("CustomerName")+", "); System.out.print("Dispatch Date: "+rs.getDate("DispatchDate")+", "); System.out.print("Delivery Time: "+rs.getTime("DeliveryTime")+", "); System.out.print("Price: "+rs.getInt("Price")+", "); System.out.print("Location: "+rs.getString("Location")); System.out.println(); } } } Connection established...... Price values updated ...... Contents of the Sales table after the update: Name: Key-Board, Customer Name: Raja, Dispatch Date: 2019-09-01, Delivery Time: 11:00:00, Price: 8500, Location: Hyderabad Name: Earphones, Customer Name: Roja, Dispatch Date: 2019-05-01, Delivery Time: 11:00:00, Price: 2000, Location: Vishakhapatnam Name: Mouse, Customer Name: Puja, Dispatch Date: 2019-03-01, Delivery Time: 10:59:59, Price: 4500, Location: Vijayawada Name: Mobile, Customer Name: Vanaja, Dispatch Date: 2019-03-01, Delivery Time: 10:10:52, Price: 9000, Location: Chennai Name: Headset, Customer Name: Jalaja, Dispatch Date: 2019-04-06, Delivery Time: 11:08:59, Price: 7500, Location: Goa
[ { "code": null, "e": 1148, "s": 1062, "text": "The IN clause in MYSQL database is used to specify the list of parameters in a query." }, { "code": null, "e": 1292, "s": 1148, "text": "For example, you need to retrieve contents of a table using specific IDs you can do so using the SELECT statement along with the IN clause as −" }, { "code": null, "e": 1999, "s": 1292, "text": "mysql> SELECT * from sales where ID IN (1001, 1003, 1005);\n+------+-------------+--------------+--------------+--------------+-------+------------+\n| ID | ProductName | CustomerName | DispatchDate | DeliveryTime | Price | Location |\n+------+-------------+--------------+--------------+--------------+-------+------------+\n| 1001 | Key-Board | Raja | 2019-09-01 | 11:00:00 | 8500 | Hyderabad |\n| 1003 | Mouse | Puja | 2019-03-01 | 10:59:59 | 4500 | Vijayawada |\n| 1005 | Headset | Jalaja | 2019-04-06 | 11:08:59 | 7500 | Goa |\n+------+-------------+--------------+--------------+--------------+-------+------------+\n3 rows in set (0.03 sec)" }, { "code": null, "e": 2344, "s": 1999, "text": "When you use the IN clause in prepared statement you can use bind variables for the parameters list (one for each) and set values for those later using the setter methods of the PreparedStatement interface and, after setting values to all the bind variables in the statement you can execute that particular statement using the execute() method." }, { "code": null, "e": 2595, "s": 2344, "text": "String query = \"UPDATE sales SET price = price+1500 WHERE ProductName IN (?, ?, ? )\";\nPreparedStatement pstmt = con.prepareStatement(query);\npstmt.setString(1, \"Key-Board\");\npstmt.setString(2, \"Mouse\");\npstmt.setString(3, \"Headset\");\npstmt.execute();" }, { "code": null, "e": 2737, "s": 2595, "text": "Let us create a table with name sales in MySQL database, with one of the columns as auto-incremented, using CREATE statement as shown below −" }, { "code": null, "e": 2939, "s": 2737, "text": "CREATE TABLE Sales(\n ID INT PRIMARY KEY AUTO_INCREMENT,\n ProductName VARCHAR (20),\n CustomerName VARCHAR (20),\n DispatchDate date,\n DeliveryTime time,\n Price INT,\n Location VARCHAR(20)\n);" }, { "code": null, "e": 3010, "s": 2939, "text": "Now, we will insert 5 records in sales table using INSERT statements −" }, { "code": null, "e": 3884, "s": 3010, "text": "insert into sales (ProductName, CustomerName, DispatchDate, DeliveryTime, Price, Location) values('Key-Board', 'Raja', DATE('2019-09-01'), TIME('11:00:00'), 7000, 'India');\ninsert into sales (ProductName, CustomerName, DispatchDate, DeliveryTime, Price, Location) values('Earphones', 'Roja', DATE('2019-05-01'), TIME('11:00:00'), 2000, 'Vishakhapatnam');\ninsert into sales (ProductName, CustomerName, DispatchDate, DeliveryTime, Price, Location) values('Mouse', 'Puja', DATE('2019-03-01'), TIME('10:59:59'), 3000, 'Vijayawada');\ninsert into sales (ProductName, CustomerName, DispatchDate, DeliveryTime, Price, Location) values('Mobile', 'Vanaja', DATE('2019-03-01'), TIME('10:10:52'), 9000, 'Chennai');\ninsert into sales (ProductName, CustomerName, DispatchDate, DeliveryTime, Price, Location) values('Headset', 'Jalaja', DATE('2019-04-06'), TIME('11:08:59'), 6000, 'Goa');" }, { "code": null, "e": 4059, "s": 3884, "text": "Following JDBC program establishes connection with the database and increases the price value of the products key-board, mouse and, Headset by 1500 each, using the IN clause." }, { "code": null, "e": 5771, "s": 4059, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\npublic class PreparedStatement_IN_clause {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/sample_database\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Inserting values to a table\n String query = \"UPDATE sales SET price = price+1500 WHERE ProductName IN (?, ?, ? )\";\n PreparedStatement pstmt = con.prepareStatement(query);\n pstmt.setString(1, \"Key-Board\");\n pstmt.setString(2, \"Mouse\");\n pstmt.setString(3, \"Headset\");\n pstmt.execute();\n System.out.println(\"Price values updated ......\");\n System.out.println(\"Contents of the Sales table after the update: \");\n //Retrieving data\n Statement stmt = con.createStatement();\n ResultSet rs = stmt.executeQuery(\"select * from sales\");\n while(rs.next()) {\n System.out.print(\"Name: \"+rs.getString(\"ProductName\")+\", \");\n System.out.print(\"Customer Name: \"+rs.getString(\"CustomerName\")+\", \");\n System.out.print(\"Dispatch Date: \"+rs.getDate(\"DispatchDate\")+\", \");\n System.out.print(\"Delivery Time: \"+rs.getTime(\"DeliveryTime\")+\", \");\n System.out.print(\"Price: \"+rs.getInt(\"Price\")+\", \");\n System.out.print(\"Location: \"+rs.getString(\"Location\"));\n System.out.println();\n }\n }\n}" }, { "code": null, "e": 6482, "s": 5771, "text": "Connection established......\nPrice values updated ......\nContents of the Sales table after the update:\nName: Key-Board, Customer Name: Raja, Dispatch Date: 2019-09-01, Delivery Time: 11:00:00, Price: 8500, Location: Hyderabad\nName: Earphones, Customer Name: Roja, Dispatch Date: 2019-05-01, Delivery Time: 11:00:00, Price: 2000, Location: Vishakhapatnam\nName: Mouse, Customer Name: Puja, Dispatch Date: 2019-03-01, Delivery Time: 10:59:59, Price: 4500, Location: Vijayawada\nName: Mobile, Customer Name: Vanaja, Dispatch Date: 2019-03-01, Delivery Time: 10:10:52, Price: 9000, Location: Chennai\nName: Headset, Customer Name: Jalaja, Dispatch Date: 2019-04-06, Delivery Time: 11:08:59, Price: 7500, Location: Goa" } ]
Sort an Array of dates in ascending order using Custom Comparator - GeeksforGeeks
09 Aug, 2021 Given an array arr[] of N dates in the form of “DD-MM-YYYY”, the task is to sort these dates in ascending order. Examples: Input: arr[] = { “25-08-1996”, “03-08-1970”, “09-04-1994” } Output: 03-08-1970 09-04-1994 25-08-1996 Input: arr[] = { “03-08-1970”, “09-04-2020”, “19-04-2019′′”} Output: 03-08-1970 19-04-2019 09-04-2020 Approach: Create a Custom comparator function that compares two dates as below: First compare the year of the two elements. The element with greater year will come after the other element.If the year of both the dates is same then compare the months. The element with a greater month will come after the other element.If the month of both the dates is same then compare the dates. The element with greater date will come after the other element. First compare the year of the two elements. The element with greater year will come after the other element. If the year of both the dates is same then compare the months. The element with a greater month will come after the other element. If the month of both the dates is same then compare the dates. The element with greater date will come after the other element. Then sort the array using the defined custom comparator. In C++, it is done as: sort(initial position, ending position, comparator) Print the modified array. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to sort the// array of dates in the form of// "DD-MM-YYYY" using custom comparator #include <bits/stdc++.h>using namespace std; // Comparator to sort the array of datesint myCompare(string date1, string date2){ string day1 = date1.substr(0, 2); string month1 = date1.substr(3, 2); string year1 = date1.substr(6, 4); string day2 = date2.substr(0, 2); string month2 = date2.substr(3, 2); string year2 = date2.substr(6, 4); // Condition to check the year if (year1 < year2) return 1; if (year1 > year2) return 0; // Condition to check the month if (month1 < month2) return 1; if (month1 > month2) return 0; // Condition to check the day if (day1 < day2) return 1; if (day1 > day2) return 0;} // Function that prints the// dates in ascensding ordervoid printDatesAscending( vector<string> arr){ // Sort the dates using library // sort function with custom Comparator sort(arr.begin(), arr.end(), myCompare); // Loop to print the dates for (int i = 0; i < arr.size(); i++) cout << arr[i] << "\n";} // Driver Codeint main(){ vector<string> arr; arr.push_back("25-08-1996"); arr.push_back("03-08-1970"); arr.push_back("09-04-1994"); arr.push_back("29-08-1996"); arr.push_back("14-02-1972"); printDatesAscending(arr); return 0;} // Java implementation to sort the// array of dates in the form of// "DD-MM-YYYY" using custom comparatorimport java.util.*;import java.lang.*; class GFG{ // Function that prints the// dates in ascensding orderstatic void printDatesAscending(ArrayList<String> arr){ // Sort the dates using library // sort function with custom Comparator Collections.sort(arr,new Comparator<>() { public int compare(String date1, String date2) { String day1 = date1.substring(0, 2); String month1 = date1.substring(3, 5); String year1 = date1.substring(6); String day2 = date2.substring(0, 2); String month2 = date2.substring(3, 5); String year2 = date2.substring(6); // Condition to check the year if (year2.compareTo(year1) > 0) return -1; else if (year2.compareTo(year1) < 0) return 1; // Condition to check the month else if (month2.compareTo(month1) > 0) return -1; else if (month2.compareTo(month1) < 0) return 1; // Condition to check the day else if (day2.compareTo(day1) > 0) return -1; else return 1; } }); // Loop to print the dates for(int i = 0; i < arr.size(); i++) System.out.println(arr.get(i));} // Driver codepublic static void main(String[] args){ ArrayList<String> arr = new ArrayList<>(); arr.add("25-08-1996"); arr.add("03-08-1970"); arr.add("09-04-1994"); arr.add("29-08-1996"); arr.add("14-02-1972"); printDatesAscending(arr);}} // This code is contributed by offbeat # Python3 implementation to sort the# array of dates in the form of# "DD-MM-YYYY" using custom comparatorfrom functools import cmp_to_key # Comparator to sort the array of datesdef myCompare(date1, date2): day1 = date1[0 : 2] month1 = date1[3 : 3 + 2] year1 = date1[6 : 6 + 4] day2 = date2[0 : 2] month2 = date2[3 : 3 + 2] year2 = date2[6 : 6 + 4] # Condition to check the year if (year1 < year2): return -1 if (year1 > year2): return 1 # Condition to check the month if (month1 < month2): return -1 if (month1 > month2): return 1 # Condition to check the day if (day1 < day2): return -1 if (day1 > day2): return 1 # Function that prints the# dates in ascensding orderdef printDatesAscending(arr): # Sort the dates using library # sort function with custom Comparator arr = sorted(arr, key = cmp_to_key( lambda a, b: myCompare(a, b))) # Loop to print the dates for i in range(len(arr)): print(arr[i]) # Driver Codearr = []arr.append("25-08-1996")arr.append("03-08-1970")arr.append("09-04-1994")arr.append("29-08-1996")arr.append("14-02-1972") printDatesAscending(arr) # This code is contributed by shubhamsingh10 // C# implementation to sort the// array of dates in the form of// "DD-MM-YYYY" using custom comparatorusing System;using System.Collections.Generic;using System.Linq; class GFG{ // Comparator to sort the array of datesstatic int myCompare(string date1, string date2){ string day1 = date1.Substring(0, 2); string month1 = date1.Substring(3, 2); string year1 = date1.Substring(6, 4); string day2 = date2.Substring(0, 2); string month2 = date2.Substring(3, 2); string year2 = date2.Substring(6, 4); // Condition to check the year return string.Compare(year1, year2); // Condition to check the month return string.Compare(month1, month2); // Condition to check the day return string.Compare(day1, day2);} // Function that prints the// dates in ascensding orderstatic void printDatesAscending(List<string> arr){ // Sort the dates using library // sort function with custom Comparator arr.Sort(myCompare); // Loop to print the dates for(int i = 0; i < arr.Count; i++) Console.WriteLine(arr[i]);} // Driver Codestatic public void Main(){ List<string> arr = new List<string>(); arr.Add("25-08-1996"); arr.Add("03-08-1970"); arr.Add("09-04-1994"); arr.Add("29-08-1996"); arr.Add("14-02-1972"); printDatesAscending(arr);}} // This code is contributed by shubhamsingh10 <script>// Javascript implementation of the above approach // Comparator to sort the array of datesfunction myCompare(date1, date2){ var day1 = date1.substr(0, 2); var month1 = date1.substr(3, 2); var year1 = date1.substr(6, 4); var day2 = date2.substr(0, 2); var month2 = date2.substr(3, 2); var year2 = date2.substr(6, 4); // Condition to check the year if (year1 < year2) return -1; if (year1 > year2) return 1; // Condition to check the month if (month1 < month2) return -1; if (month1 > month2) return 1; // Condition to check the day if (day1 < day2) return -1; if (day1 > day2) return 1;} // Function that prints the// dates in ascensding orderfunction printDatesAscending( arr){ var n = arr.length; // Sort the dates using library // sort function with custom Comparator arr.sort(myCompare); // Loop to print the dates for (var i = 0; i < n; i++) document.write(arr[i] + "<br>");} // Driver Codevar arr = [];arr.push("25-08-1996");arr.push("03-08-1970");arr.push("09-04-1994");arr.push("29-08-1996");arr.push("14-02-1972"); printDatesAscending(arr);</script> 03-08-1970 14-02-1972 09-04-1994 25-08-1996 29-08-1996 Time Complexity: O(N*logN)Auxiliary Space: O(1) offbeat SHUBHAMSINGH10 pankajsharmagfg Algorithms Arrays Sorting Write From Home Arrays Sorting Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar Program for SSTF disk scheduling algorithm Quadratic Probing in Hashing Rail Fence Cipher - Encryption and Decryption SCAN (Elevator) Disk Scheduling Algorithms Arrays in Java Arrays in C/C++ Program for array rotation Stack Data Structure (Introduction and Program) Largest Sum Contiguous Subarray
[ { "code": null, "e": 24700, "s": 24672, "text": "\n09 Aug, 2021" }, { "code": null, "e": 24813, "s": 24700, "text": "Given an array arr[] of N dates in the form of “DD-MM-YYYY”, the task is to sort these dates in ascending order." }, { "code": null, "e": 24825, "s": 24813, "text": "Examples: " }, { "code": null, "e": 24926, "s": 24825, "text": "Input: arr[] = { “25-08-1996”, “03-08-1970”, “09-04-1994” } Output: 03-08-1970 09-04-1994 25-08-1996" }, { "code": null, "e": 25029, "s": 24926, "text": "Input: arr[] = { “03-08-1970”, “09-04-2020”, “19-04-2019′′”} Output: 03-08-1970 19-04-2019 09-04-2020 " }, { "code": null, "e": 25041, "s": 25029, "text": "Approach: " }, { "code": null, "e": 25477, "s": 25041, "text": "Create a Custom comparator function that compares two dates as below: First compare the year of the two elements. The element with greater year will come after the other element.If the year of both the dates is same then compare the months. The element with a greater month will come after the other element.If the month of both the dates is same then compare the dates. The element with greater date will come after the other element." }, { "code": null, "e": 25586, "s": 25477, "text": "First compare the year of the two elements. The element with greater year will come after the other element." }, { "code": null, "e": 25717, "s": 25586, "text": "If the year of both the dates is same then compare the months. The element with a greater month will come after the other element." }, { "code": null, "e": 25845, "s": 25717, "text": "If the month of both the dates is same then compare the dates. The element with greater date will come after the other element." }, { "code": null, "e": 25925, "s": 25845, "text": "Then sort the array using the defined custom comparator. In C++, it is done as:" }, { "code": null, "e": 25979, "s": 25925, "text": "sort(initial position, ending position, comparator) " }, { "code": null, "e": 26005, "s": 25979, "text": "Print the modified array." }, { "code": null, "e": 26057, "s": 26005, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26061, "s": 26057, "text": "C++" }, { "code": null, "e": 26066, "s": 26061, "text": "Java" }, { "code": null, "e": 26074, "s": 26066, "text": "Python3" }, { "code": null, "e": 26077, "s": 26074, "text": "C#" }, { "code": null, "e": 26088, "s": 26077, "text": "Javascript" }, { "code": "// C++ implementation to sort the// array of dates in the form of// \"DD-MM-YYYY\" using custom comparator #include <bits/stdc++.h>using namespace std; // Comparator to sort the array of datesint myCompare(string date1, string date2){ string day1 = date1.substr(0, 2); string month1 = date1.substr(3, 2); string year1 = date1.substr(6, 4); string day2 = date2.substr(0, 2); string month2 = date2.substr(3, 2); string year2 = date2.substr(6, 4); // Condition to check the year if (year1 < year2) return 1; if (year1 > year2) return 0; // Condition to check the month if (month1 < month2) return 1; if (month1 > month2) return 0; // Condition to check the day if (day1 < day2) return 1; if (day1 > day2) return 0;} // Function that prints the// dates in ascensding ordervoid printDatesAscending( vector<string> arr){ // Sort the dates using library // sort function with custom Comparator sort(arr.begin(), arr.end(), myCompare); // Loop to print the dates for (int i = 0; i < arr.size(); i++) cout << arr[i] << \"\\n\";} // Driver Codeint main(){ vector<string> arr; arr.push_back(\"25-08-1996\"); arr.push_back(\"03-08-1970\"); arr.push_back(\"09-04-1994\"); arr.push_back(\"29-08-1996\"); arr.push_back(\"14-02-1972\"); printDatesAscending(arr); return 0;}", "e": 27487, "s": 26088, "text": null }, { "code": "// Java implementation to sort the// array of dates in the form of// \"DD-MM-YYYY\" using custom comparatorimport java.util.*;import java.lang.*; class GFG{ // Function that prints the// dates in ascensding orderstatic void printDatesAscending(ArrayList<String> arr){ // Sort the dates using library // sort function with custom Comparator Collections.sort(arr,new Comparator<>() { public int compare(String date1, String date2) { String day1 = date1.substring(0, 2); String month1 = date1.substring(3, 5); String year1 = date1.substring(6); String day2 = date2.substring(0, 2); String month2 = date2.substring(3, 5); String year2 = date2.substring(6); // Condition to check the year if (year2.compareTo(year1) > 0) return -1; else if (year2.compareTo(year1) < 0) return 1; // Condition to check the month else if (month2.compareTo(month1) > 0) return -1; else if (month2.compareTo(month1) < 0) return 1; // Condition to check the day else if (day2.compareTo(day1) > 0) return -1; else return 1; } }); // Loop to print the dates for(int i = 0; i < arr.size(); i++) System.out.println(arr.get(i));} // Driver codepublic static void main(String[] args){ ArrayList<String> arr = new ArrayList<>(); arr.add(\"25-08-1996\"); arr.add(\"03-08-1970\"); arr.add(\"09-04-1994\"); arr.add(\"29-08-1996\"); arr.add(\"14-02-1972\"); printDatesAscending(arr);}} // This code is contributed by offbeat", "e": 29261, "s": 27487, "text": null }, { "code": "# Python3 implementation to sort the# array of dates in the form of# \"DD-MM-YYYY\" using custom comparatorfrom functools import cmp_to_key # Comparator to sort the array of datesdef myCompare(date1, date2): day1 = date1[0 : 2] month1 = date1[3 : 3 + 2] year1 = date1[6 : 6 + 4] day2 = date2[0 : 2] month2 = date2[3 : 3 + 2] year2 = date2[6 : 6 + 4] # Condition to check the year if (year1 < year2): return -1 if (year1 > year2): return 1 # Condition to check the month if (month1 < month2): return -1 if (month1 > month2): return 1 # Condition to check the day if (day1 < day2): return -1 if (day1 > day2): return 1 # Function that prints the# dates in ascensding orderdef printDatesAscending(arr): # Sort the dates using library # sort function with custom Comparator arr = sorted(arr, key = cmp_to_key( lambda a, b: myCompare(a, b))) # Loop to print the dates for i in range(len(arr)): print(arr[i]) # Driver Codearr = []arr.append(\"25-08-1996\")arr.append(\"03-08-1970\")arr.append(\"09-04-1994\")arr.append(\"29-08-1996\")arr.append(\"14-02-1972\") printDatesAscending(arr) # This code is contributed by shubhamsingh10", "e": 30532, "s": 29261, "text": null }, { "code": "// C# implementation to sort the// array of dates in the form of// \"DD-MM-YYYY\" using custom comparatorusing System;using System.Collections.Generic;using System.Linq; class GFG{ // Comparator to sort the array of datesstatic int myCompare(string date1, string date2){ string day1 = date1.Substring(0, 2); string month1 = date1.Substring(3, 2); string year1 = date1.Substring(6, 4); string day2 = date2.Substring(0, 2); string month2 = date2.Substring(3, 2); string year2 = date2.Substring(6, 4); // Condition to check the year return string.Compare(year1, year2); // Condition to check the month return string.Compare(month1, month2); // Condition to check the day return string.Compare(day1, day2);} // Function that prints the// dates in ascensding orderstatic void printDatesAscending(List<string> arr){ // Sort the dates using library // sort function with custom Comparator arr.Sort(myCompare); // Loop to print the dates for(int i = 0; i < arr.Count; i++) Console.WriteLine(arr[i]);} // Driver Codestatic public void Main(){ List<string> arr = new List<string>(); arr.Add(\"25-08-1996\"); arr.Add(\"03-08-1970\"); arr.Add(\"09-04-1994\"); arr.Add(\"29-08-1996\"); arr.Add(\"14-02-1972\"); printDatesAscending(arr);}} // This code is contributed by shubhamsingh10", "e": 31906, "s": 30532, "text": null }, { "code": "<script>// Javascript implementation of the above approach // Comparator to sort the array of datesfunction myCompare(date1, date2){ var day1 = date1.substr(0, 2); var month1 = date1.substr(3, 2); var year1 = date1.substr(6, 4); var day2 = date2.substr(0, 2); var month2 = date2.substr(3, 2); var year2 = date2.substr(6, 4); // Condition to check the year if (year1 < year2) return -1; if (year1 > year2) return 1; // Condition to check the month if (month1 < month2) return -1; if (month1 > month2) return 1; // Condition to check the day if (day1 < day2) return -1; if (day1 > day2) return 1;} // Function that prints the// dates in ascensding orderfunction printDatesAscending( arr){ var n = arr.length; // Sort the dates using library // sort function with custom Comparator arr.sort(myCompare); // Loop to print the dates for (var i = 0; i < n; i++) document.write(arr[i] + \"<br>\");} // Driver Codevar arr = [];arr.push(\"25-08-1996\");arr.push(\"03-08-1970\");arr.push(\"09-04-1994\");arr.push(\"29-08-1996\");arr.push(\"14-02-1972\"); printDatesAscending(arr);</script>", "e": 33099, "s": 31906, "text": null }, { "code": null, "e": 33154, "s": 33099, "text": "03-08-1970\n14-02-1972\n09-04-1994\n25-08-1996\n29-08-1996" }, { "code": null, "e": 33205, "s": 33156, "text": "Time Complexity: O(N*logN)Auxiliary Space: O(1) " }, { "code": null, "e": 33213, "s": 33205, "text": "offbeat" }, { "code": null, "e": 33228, "s": 33213, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 33244, "s": 33228, "text": "pankajsharmagfg" }, { "code": null, "e": 33255, "s": 33244, "text": "Algorithms" }, { "code": null, "e": 33262, "s": 33255, "text": "Arrays" }, { "code": null, "e": 33270, "s": 33262, "text": "Sorting" }, { "code": null, "e": 33286, "s": 33270, "text": "Write From Home" }, { "code": null, "e": 33293, "s": 33286, "text": "Arrays" }, { "code": null, "e": 33301, "s": 33293, "text": "Sorting" }, { "code": null, "e": 33312, "s": 33301, "text": "Algorithms" }, { "code": null, "e": 33410, "s": 33312, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33435, "s": 33410, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 33478, "s": 33435, "text": "Program for SSTF disk scheduling algorithm" }, { "code": null, "e": 33507, "s": 33478, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 33553, "s": 33507, "text": "Rail Fence Cipher - Encryption and Decryption" }, { "code": null, "e": 33596, "s": 33553, "text": "SCAN (Elevator) Disk Scheduling Algorithms" }, { "code": null, "e": 33611, "s": 33596, "text": "Arrays in Java" }, { "code": null, "e": 33627, "s": 33611, "text": "Arrays in C/C++" }, { "code": null, "e": 33654, "s": 33627, "text": "Program for array rotation" }, { "code": null, "e": 33702, "s": 33654, "text": "Stack Data Structure (Introduction and Program)" } ]
C library function - putc()
The C library function int putc(int char, FILE *stream) writes a character (an unsigned char) specified by the argument char to the specified stream and advances the position indicator for the stream. Following is the declaration for putc() function. int putc(int char, FILE *stream) char − This is the character to be written. The character is passed as its int promotion. char − This is the character to be written. The character is passed as its int promotion. stream − This is the pointer to a FILE object that identifies the stream where the character is to be written. stream − This is the pointer to a FILE object that identifies the stream where the character is to be written. This function returns the character written as an unsigned char cast to an int or EOF on error. The following example shows the usage of putc() function. #include <stdio.h> int main () { FILE *fp; int ch; fp = fopen("file.txt", "w"); for( ch = 33 ; ch <= 100; ch++ ) { putc(ch, fp); } fclose(fp); return(0); } Let us compile and run the above program that will create a file file.txt in the current directory which will have following content − !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcd Now let's see the content of the above file using the following program − #include <stdio.h> int main () { FILE *fp; int c; fp = fopen("file.txt","r"); while(1) { c = fgetc(fp); if( feof(fp) ) { break ; } printf("%c", c); } fclose(fp); return(0); } Let us compile and run the above program to produce the following result − !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcd 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": 2208, "s": 2007, "text": "The C library function int putc(int char, FILE *stream) writes a character (an unsigned char) specified by the argument char to the specified stream and advances the position indicator for the stream." }, { "code": null, "e": 2258, "s": 2208, "text": "Following is the declaration for putc() function." }, { "code": null, "e": 2291, "s": 2258, "text": "int putc(int char, FILE *stream)" }, { "code": null, "e": 2381, "s": 2291, "text": "char − This is the character to be written. The character is passed as its int promotion." }, { "code": null, "e": 2471, "s": 2381, "text": "char − This is the character to be written. The character is passed as its int promotion." }, { "code": null, "e": 2582, "s": 2471, "text": "stream − This is the pointer to a FILE object that identifies the stream where the character is to be written." }, { "code": null, "e": 2693, "s": 2582, "text": "stream − This is the pointer to a FILE object that identifies the stream where the character is to be written." }, { "code": null, "e": 2789, "s": 2693, "text": "This function returns the character written as an unsigned char cast to an int or EOF on error." }, { "code": null, "e": 2847, "s": 2789, "text": "The following example shows the usage of putc() function." }, { "code": null, "e": 3036, "s": 2847, "text": "#include <stdio.h>\n\nint main () {\n FILE *fp;\n int ch;\n\n fp = fopen(\"file.txt\", \"w\");\n for( ch = 33 ; ch <= 100; ch++ ) {\n putc(ch, fp);\n }\n fclose(fp);\n \n return(0);\n}" }, { "code": null, "e": 3171, "s": 3036, "text": "Let us compile and run the above program that will create a file file.txt in the current directory which will have following content −" }, { "code": null, "e": 3241, "s": 3171, "text": "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcd\n" }, { "code": null, "e": 3315, "s": 3241, "text": "Now let's see the content of the above file using the following program −" }, { "code": null, "e": 3546, "s": 3315, "text": "#include <stdio.h>\n\nint main () {\n FILE *fp;\n int c;\n\n fp = fopen(\"file.txt\",\"r\");\n while(1) {\n c = fgetc(fp);\n if( feof(fp) ) {\n break ;\n }\n printf(\"%c\", c);\n }\n fclose(fp);\n return(0);\n}" }, { "code": null, "e": 3621, "s": 3546, "text": "Let us compile and run the above program to produce the following result −" }, { "code": null, "e": 3691, "s": 3621, "text": "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcd\n" }, { "code": null, "e": 3724, "s": 3691, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3739, "s": 3724, "text": " Nishant Malik" }, { "code": null, "e": 3774, "s": 3739, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3789, "s": 3774, "text": " Nishant Malik" }, { "code": null, "e": 3824, "s": 3789, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3838, "s": 3824, "text": " Asif Hussain" }, { "code": null, "e": 3871, "s": 3838, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3889, "s": 3871, "text": " Richa Maheshwari" }, { "code": null, "e": 3924, "s": 3889, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3943, "s": 3924, "text": " Vandana Annavaram" }, { "code": null, "e": 3976, "s": 3943, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 3988, "s": 3976, "text": " Amit Diwan" }, { "code": null, "e": 3995, "s": 3988, "text": " Print" }, { "code": null, "e": 4006, "s": 3995, "text": " Add Notes" } ]
Scope resolution operator in C++ - GeeksforGeeks
06 Aug, 2019 In C++, scope resolution operator is ::. It is used for following purposes. 1) To access a global variable when there is a local variable with same name: // C++ program to show that we can access a global variable// using scope resolution operator :: when there is a local // variable with same name #include<iostream> using namespace std; int x; // Global x int main(){ int x = 10; // Local x cout << "Value of global x is " << ::x; cout << "\nValue of local x is " << x; return 0;} Output: Value of global x is 0 Value of local x is 10 2) To define a function outside a class. // C++ program to show that scope resolution operator :: is used// to define a function outside a class#include<iostream> using namespace std; class A {public: // Only declaration void fun();}; // Definition outside class using ::void A::fun(){ cout << "fun() called";} int main(){ A a; a.fun(); return 0;} Output: fun() called 3) To access a class’s static variables. // C++ program to show that :: can be used to access static// members when there is a local variable with same name#include<iostream>using namespace std; class Test{ static int x; public: static int y; // Local parameter 'a' hides class member // 'a', but we can access it using :: void func(int x) { // We can access class's static variable // even if there is a local variable cout << "Value of static x is " << Test::x; cout << "\nValue of local x is " << x; }}; // In C++, static members must be explicitly defined // like thisint Test::x = 1;int Test::y = 2; int main(){ Test obj; int x = 3 ; obj.func(x); cout << "\nTest::y = " << Test::y; return 0;} Output: Value of static x is 1 Value of local x is 3 Test::y = 2; 4) In case of multiple Inheritance:If same variable name exists in two ancestor classes, we can use scope resolution operator to distinguish. // Use of scope resolution operator in multiple inheritance.#include<iostream>using namespace std; class A{protected: int x;public: A() { x = 10; }}; class B{protected: int x;public: B() { x = 20; }}; class C: public A, public B{public: void fun() { cout << "A's x is " << A::x; cout << "\nB's x is " << B::x; }}; int main(){ C c; c.fun(); return 0;} Output: A's x is 10 B's x is 20 5) For namespaceIf a class having the same name exists inside two namespace we can use the namespace name with the scope resolution operator to refer that class without any conflicts // Use of scope resolution operator for namespace.#include<iostream> int main(){ std::cout << "Hello" << std::endl; } Here, cout and endl belong to the std namespace. 6) Refer to a class inside another class:If a class exists inside another class we can use the nesting class to refer the nested class using the scope resolution operator // Use of scope resolution class inside another class.#include<iostream>using namespace std; class outside{public: int x; class inside { public: int x; static int y; int foo(); };};int outside::inside::y = 5; int main(){ outside A; outside::inside B; } Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above ZK. C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C++ Classes and Objects Socket Programming in C/C++ Operator Overloading in C++ Multidimensional Arrays in C / C++ Templates in C++ with Examples rand() and srand() in C/C++ C++ Data Types unordered_map in C++ STL Iterators in C++ STL getline (string) in C++
[ { "code": null, "e": 24168, "s": 24140, "text": "\n06 Aug, 2019" }, { "code": null, "e": 24244, "s": 24168, "text": "In C++, scope resolution operator is ::. It is used for following purposes." }, { "code": null, "e": 24322, "s": 24244, "text": "1) To access a global variable when there is a local variable with same name:" }, { "code": "// C++ program to show that we can access a global variable// using scope resolution operator :: when there is a local // variable with same name #include<iostream> using namespace std; int x; // Global x int main(){ int x = 10; // Local x cout << \"Value of global x is \" << ::x; cout << \"\\nValue of local x is \" << x; return 0;}", "e": 24663, "s": 24322, "text": null }, { "code": null, "e": 24671, "s": 24663, "text": "Output:" }, { "code": null, "e": 24718, "s": 24671, "text": "Value of global x is 0\nValue of local x is 10\n" }, { "code": null, "e": 24759, "s": 24718, "text": "2) To define a function outside a class." }, { "code": "// C++ program to show that scope resolution operator :: is used// to define a function outside a class#include<iostream> using namespace std; class A {public: // Only declaration void fun();}; // Definition outside class using ::void A::fun(){ cout << \"fun() called\";} int main(){ A a; a.fun(); return 0;}", "e": 25084, "s": 24759, "text": null }, { "code": null, "e": 25092, "s": 25084, "text": "Output:" }, { "code": null, "e": 25106, "s": 25092, "text": "fun() called\n" }, { "code": null, "e": 25147, "s": 25106, "text": "3) To access a class’s static variables." }, { "code": "// C++ program to show that :: can be used to access static// members when there is a local variable with same name#include<iostream>using namespace std; class Test{ static int x; public: static int y; // Local parameter 'a' hides class member // 'a', but we can access it using :: void func(int x) { // We can access class's static variable // even if there is a local variable cout << \"Value of static x is \" << Test::x; cout << \"\\nValue of local x is \" << x; }}; // In C++, static members must be explicitly defined // like thisint Test::x = 1;int Test::y = 2; int main(){ Test obj; int x = 3 ; obj.func(x); cout << \"\\nTest::y = \" << Test::y; return 0;}", "e": 25888, "s": 25147, "text": null }, { "code": null, "e": 25896, "s": 25888, "text": "Output:" }, { "code": null, "e": 25955, "s": 25896, "text": "Value of static x is 1\nValue of local x is 3\nTest::y = 2;\n" }, { "code": null, "e": 26097, "s": 25955, "text": "4) In case of multiple Inheritance:If same variable name exists in two ancestor classes, we can use scope resolution operator to distinguish." }, { "code": "// Use of scope resolution operator in multiple inheritance.#include<iostream>using namespace std; class A{protected: int x;public: A() { x = 10; }}; class B{protected: int x;public: B() { x = 20; }}; class C: public A, public B{public: void fun() { cout << \"A's x is \" << A::x; cout << \"\\nB's x is \" << B::x; }}; int main(){ C c; c.fun(); return 0;}", "e": 26489, "s": 26097, "text": null }, { "code": null, "e": 26497, "s": 26489, "text": "Output:" }, { "code": null, "e": 26521, "s": 26497, "text": "A's x is 10\nB's x is 20" }, { "code": null, "e": 26704, "s": 26521, "text": "5) For namespaceIf a class having the same name exists inside two namespace we can use the namespace name with the scope resolution operator to refer that class without any conflicts" }, { "code": "// Use of scope resolution operator for namespace.#include<iostream> int main(){ std::cout << \"Hello\" << std::endl; }", "e": 26829, "s": 26704, "text": null }, { "code": null, "e": 26879, "s": 26829, "text": "Here, cout and endl belong to the std namespace.\n" }, { "code": null, "e": 27050, "s": 26879, "text": "6) Refer to a class inside another class:If a class exists inside another class we can use the nesting class to refer the nested class using the scope resolution operator" }, { "code": "// Use of scope resolution class inside another class.#include<iostream>using namespace std; class outside{public: int x; class inside { public: int x; static int y; int foo(); };};int outside::inside::y = 5; int main(){ outside A; outside::inside B; }", "e": 27374, "s": 27050, "text": null }, { "code": null, "e": 27498, "s": 27374, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 27502, "s": 27498, "text": "ZK." }, { "code": null, "e": 27506, "s": 27502, "text": "C++" }, { "code": null, "e": 27510, "s": 27506, "text": "CPP" }, { "code": null, "e": 27608, "s": 27510, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27617, "s": 27608, "text": "Comments" }, { "code": null, "e": 27630, "s": 27617, "text": "Old Comments" }, { "code": null, "e": 27654, "s": 27630, "text": "C++ Classes and Objects" }, { "code": null, "e": 27682, "s": 27654, "text": "Socket Programming in C/C++" }, { "code": null, "e": 27710, "s": 27682, "text": "Operator Overloading in C++" }, { "code": null, "e": 27745, "s": 27710, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 27776, "s": 27745, "text": "Templates in C++ with Examples" }, { "code": null, "e": 27804, "s": 27776, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 27819, "s": 27804, "text": "C++ Data Types" }, { "code": null, "e": 27844, "s": 27819, "text": "unordered_map in C++ STL" }, { "code": null, "e": 27865, "s": 27844, "text": "Iterators in C++ STL" } ]
Credit Risk Management: EDA & Feature Engineering | by Andrew Nguyen | Towards Data Science
What are the common use cases in the financial industry that Data Science can be of great help to? Credit Score Cards are one of the common risk control methods in the financial industry which uses personal information and transactional records to identify and evaluate the creditworthiness of existing and potential customers. There are a number of different use cases leveraging this measure such as loan management, credit card approval, credit limit extension, etc. That said, this project’s applicability varies depending on the problem a financial institution is facing. The core engine which makes this project usable is the processing and transformation of input data to engender the output of high predictability from the existing/new input that best addresses the issues. This end-to-end project is divided into 3 parts: Explanatory Data Analysis (EDA) & Feature EngineeringFeature Scaling and Selection (Bonus: Imbalanced Data Handling)Machine Learning Modelling (Classification) Explanatory Data Analysis (EDA) & Feature Engineering Feature Scaling and Selection (Bonus: Imbalanced Data Handling) Machine Learning Modelling (Classification) Note: As the project aims to boost my capability in Data Science, in short for the sake of self-study and self-improvement, instead of only applying the best performing technique, the project will divide the dataset into 2 smaller sub-sets to test which produces a better result. So let’s kick off with the 1st part of the project: EDA & Feature Engineering Let’s import the necessary libraries and the two datasets: import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snsapplication = pd.read_csv("application_record.csv")credit = pd.read_csv("credit_record.csv") As shared above, while the Application dataset provides all data points from the personal information submitted by the existing banking customers (e.g. id, gender, income, etc.), the Credit dataset maps each corresponding id with his/her loan repayment status (e.g. X stands for no loan of the month, C for paid off and >0 implying the number of payment-overdue months). For better usability of the Credit information, I cleaned up the dataset by converting the “Status” columns to numeric as well as grouped it by Customer ID and the latest month: credit.status = credit.status.replace({'X':-2, 'C': -1})credit.status = credit.status.astype('int')credit.status = credit.status.apply(lambda x:x+1) credit_month = credit.groupby('id').months_balance.max().reset_index()record = pd.merge(credit_month, credit, how="inner", on=["id", "months_balance"])record.head() When all had been set, I then combined the newly processed dataset with the Application utilizing “inner merge”. On top of this, if you refer back to the original dataset, “Birth_date” and “Employment” are the number of days counted backwards from today, which is a bit difficult to understand initially. As such, I decided to convert these variables into positive numbers and years instead. df['age'] = df.birth_date.apply(lambda x: round(x/-365,0))df['year_of_employment'] = df.employment.apply(lambda x: round(x/-365,0) if x<0 else 0)df = df.drop(columns=["birth_date","employment"]) Moving on, two highlights of every EDA that I suggest you to never ignore are (1) checking null values and (2) handling outliers. The former ensures that we have a 100% clean dataset before processing and plugging into modelling while the latter helps avoid your dataset getting overly skewed as a result of marginally extreme outliers. df.isnull().sum()df.occupation_type = df.occupation_type.fillna("Others") “Occupation Type” is the only variable that has null values (NaN), so I went ahead filling those values with “Others”. Using df.describe and sns.boxplot, I was able to find out that “Annual Income” and “Fam Members” are two variables that have outliers in the dataset, visually as below: To remove outliers, I wrote a function which can be easily applied across variables with similar issues at once: def remove_outlier(col): q25 = col.quantile(0.25) q75 = col.quantile(0.75) iqr = q75 - q25 cutoff = iqr*1.5 lower = q25 - cutoff upper = q75 + cutoff return lower, upper#Remove outliers for Annual Incomelower_1, upper_1 = remove_outlier(df.annual_income)df = df.loc[(df.annual_income > lower_1) & (df.annual_income < upper_1)] #Remove outliers for Fam Memberslower_2, upper_2 = remove_outlier(df.fam_members)df = df.loc[(df.annual_fam_members > lower_2) & (df.fam_members < upper_2)] We’re almost done with EDA, coming down to define the “target” variable, which you might have heard somewhere in most classification lessons. Going back to the topic of this project, Credit Risk Management, we need to determine how we should handle the loan repayment status of the customers. With this dataset, I defined “target = 0” for those who didn’t have any loan or paid off that month while the remaining data, any overdue loan, was mapped to “target = 1”. df['target'] = Nonedf.loc[df.status < 1,'target']=0df.loc[df.status >= 1,'target']=1df.target = pd.to_numeric(df.target) What is Feature Engineering and what does it do to help pre-process the data prior to modelling? According to Wikipedia, Feature engineering is the process of using domain knowledge to extract features from raw data via data mining techniques. These features can be used to improve the performance of machine learning algorithms. In fact, Feature Engineering requires not only domain knowledge but also the understanding of the dataset and the goal of achievement. Particularly, with our dataset, there are quite a number of different features, which we call as independent variables, which have the correlation with the repayment status, which is the target variable (0 or 1). As such, in order to tune out an insightful and actionable model, we need to “engineer” those features by transforming existing and/or adding supporting data, which makes Feature Engineering different from EDA. As I have mentioned from the beginning, we will never know which is a better approach until we test it. That being said, I decided to test out 2 scenarios, WITH and WITHOUT touching the target variable, and see if there is any significant difference in the result produced later on. Before diving into the implementation, we should be aware that there is no “one-size-fit-all” technique for Feature Engineering as it depends on how you process your features. In this project, I leveraged “Category Encoding” in my dataset, since the majority of the data is categorical, which should be converted to numerical for easier processing in most machine learning models. df_a = df #for encoding without targetdf_b = df #for encoding with targetx_a = df_a.iloc[:, 1:-1]y_a = df_a.iloc[:, -1]from sklearn.model_selection import train_test_splitx_a_train, x_a_test, y_a_train, y_a_test = train_test_split(x_a, y_a, test_size=0.3, random_state=1) Two separate dataset were created for two scenarios, so that we are able to manipulate each dataset without fearing it getting mixed up. Also, an important highlight to note before processing is that we are highly recommended to split the dataset to train and test sets to avoid data leakage. Essentially, if we split after processing, the data of the test set has been exposed, hence not being objective enough to compare against the train set in the modelling phase. Depending on the variable type, we will apply the suitable technique to each. If you refer back to the dataset, there are 3 types of variable: (1) binary, (2) nominal and (3) continuous. While binary and continuous variables are pretty much self-explanatory, nominal variable refers to a group of different categories that has no intrinsic order to each other. For binary variables in our dataset (e.g. gender, car, property), we can choose either Label Encoder or Label Binarizer from sklearn library, which will map the original data to 0 or 1: #Option 1: Label Encoder (applied to >2 categories per variable)from sklearn.preprocessing import LabelEncoder, LabelBinarizerle = LabelEncoder()gender_le = le.fit_transform(x_a_train.gender)#Option 2: LabelBinarizer (applied to 2 categories per variable)bn = LabelBinarizer()gender_bn = np.array(x_a_train.gender).reshape(-1,1)gender_bn = bn.fit_transform(gender_bn) Nominal variables (e.g. income type, education, family status, housing type, occupation type) are categorical which needs converting to numerical prior to modelling. Two common methods of encoding a category is (1) Dummy Encoding and (2) One Hot Encoder, which basically creates n columns as n unique categories within that variable and assigns 0 or 1 depending on the absence/presence of each category in each column. The difference between these methods is that Dummy Encoding coverts into n-1 sub-variables while One Hot Encoder converts into n sub-variables. #Option 1: Dummy Encoding: kn - k variablesincome_type_dummy = pd.get_dummies(x_a_train.income_type)#Option 2: OneHotEcnoder: kn variablesfrom sklearn.preprocessing import OneHotEncoderonehot = OneHotEncoder(sparse=False, drop='first', handle_unknown='error')income_type_onehot = onehot.fit_transform(x_a_train.income_type.to_numpy().reshape(-1,1))income_type_onehot = pd.DataFrame(income_type_onehot, columns=onehot.get_feature_names(['income_type'])) Dummy Encoding can easily be done via pd.get_dummies() as it’s a part of pandas library already. For One Hot Encoder, we need to import it from sklearn library and transform each variable, individually or all at the same time. One Hot Encoder was designed to keep the consistency in the number of categories across train and test sets (e.g. handling categories that do not appear in either), so it’s more highly recommended than Dummy Encoding due to easier control with “handle_unknown= “error””. However, one of the drawbacks of One Hot Encoder is multicollinearity, which refers to variables or sub-variables highly linearly related to one another and hence reduces the accuracy of our models. This can be rectified or avoided by assigning the parameter of “drop= ‘first’” which helps remove one of the sub-variables after encoding. Continuous variables are numeric variables that have an infinite number of values between any two values. Essentially, it takes forever to count! Let’s look at the distribution of each continuous variable in our data set visually: The left figure illustrates the range of age of the customers while the right shows the distribution of different income buckets. Two of the common methods to handle this type of variable is (1) Fixed-width Binning and (2) Adaptive Binning. Particularly, the former creates sub-categories from the pre-defined bins (e.g. age — 10–20, 20–30, 30–40, etc) while the latter relies on the distribution of the data. The pros and cons of Fixed-width Binning is that it’s easy and simple to encode the variable yet relatively subjective without taking into consideration the data itself. As such, I suggest opting for Adaptive Binning which closely looks at the data distribution. From what I observed, instead of converting into 2-bin categories, I decided to go for “quantiles” since the original distribution is widely ranged, after which Label Encoding was applied. #Convert each variable into 5 equal categories/eachx_a_train['age_binned'] = pd.qcut(x_a_train.age, q=[0, .25, .50, .75, 1])x_a_train['annual_income_binned'] = pd.qcut(x_a_train.annual_income, q=[0, .25, .50, .75, 1])#Apply Label Encoder to assign the label to each category without biasx_a_train['age'] = le.fit_transform(x_a_train['age_binned'])x_a_train['annual_income'] = le.fit_transform(x_a_train['annual_income_binned']) Tada! We have engineered all necessary variables without ever touching the target variable! Now, let’s move to the other prior to fitting each to the modelling phase. As the correlation with the target variable is leveraged in this method, we should encode all independent variables in the same way for better objectivity. Again, pre-requisite has to be followed: train_test_split before processing x_b = df_b.iloc[:, 1:-1]y_b = df_b.iloc[:, -1]from sklearn.model_selection import train_test_splitx_b_train, x_b_test, y_b_train, y_b_test = train_test_split(x_b, y_b, test_size=0.3, random_state=1) Among the techniques for category encoding with the involvement of the target, I found 3 common options which are widely used: (1) Weight-of-Evidence Encoder (WOE), (2) Target Encoder, and (3) Leave-One-Out Encoder (LOO). In brief, WOE Encoder: Weight-of-evidence encoding is a widely used technique in credit risk modelling which gets the maximum difference among the unique categories in each variable related to the target. This can be easily understood with its mathematical calculation as below — the natural log of % Good (in this case, target = 0) / % Bad (target = 1): Target Encoder & LOO Encoder: while the former method replaces a categorical value with the mean of the target variable across all rows in the dataset, the latter does the same but excludes the row itself. The reason being is to avoid direct target leakage from using too much information before modelling. #Option 1: WOE Encoderimport category_encoders as cewoe = ce.WOEEncoder()def woe_encoder(col, target): for i in range(len(x_b_train.columns)): col.iloc[:,i] = woe.fit_transform(col, target) return coldf_woe_train = woe_encoder(x_b_train, y_b_train)#Option 2: Target Encoderfrom category_encoders import TargetEncoderte = TargetEncoder()def target_encoder(col, target): for i in range(len(x_b_train.columns)): col.iloc[:,i] = te.fit_transform(col, target) return coldf_te_train = target_encoder(x_b_train, y_b_train) After testing both methods, it seems that the newly encoded dataset between the two is not much of a difference to each other. Hence, I opted for the dataset with WOE Encoder for the following steps of this project. However, please test out on other datasets, which might produce a different result possibly due to different data distribution. Voila! That’s a wrap for the 1st part of this project! As shared above, the project was created as a repository of learning notes and highlights along the journey of improving my Data Science skillsets. Hence, I have tested out multiple methods per each section in order to find out the best performing technique for use moving forward. Do look out for the next 2 parts which covers Feature Scaling/Selection and Machine Learning Modelling! In the meantime, let’s connect: Github: https://github.com/andrewnguyen07LinkedIn: www.linkedin.com/in/andrewnguyen07
[ { "code": null, "e": 270, "s": 171, "text": "What are the common use cases in the financial industry that Data Science can be of great help to?" }, { "code": null, "e": 641, "s": 270, "text": "Credit Score Cards are one of the common risk control methods in the financial industry which uses personal information and transactional records to identify and evaluate the creditworthiness of existing and potential customers. There are a number of different use cases leveraging this measure such as loan management, credit card approval, credit limit extension, etc." }, { "code": null, "e": 953, "s": 641, "text": "That said, this project’s applicability varies depending on the problem a financial institution is facing. The core engine which makes this project usable is the processing and transformation of input data to engender the output of high predictability from the existing/new input that best addresses the issues." }, { "code": null, "e": 1002, "s": 953, "text": "This end-to-end project is divided into 3 parts:" }, { "code": null, "e": 1162, "s": 1002, "text": "Explanatory Data Analysis (EDA) & Feature EngineeringFeature Scaling and Selection (Bonus: Imbalanced Data Handling)Machine Learning Modelling (Classification)" }, { "code": null, "e": 1216, "s": 1162, "text": "Explanatory Data Analysis (EDA) & Feature Engineering" }, { "code": null, "e": 1280, "s": 1216, "text": "Feature Scaling and Selection (Bonus: Imbalanced Data Handling)" }, { "code": null, "e": 1324, "s": 1280, "text": "Machine Learning Modelling (Classification)" }, { "code": null, "e": 1604, "s": 1324, "text": "Note: As the project aims to boost my capability in Data Science, in short for the sake of self-study and self-improvement, instead of only applying the best performing technique, the project will divide the dataset into 2 smaller sub-sets to test which produces a better result." }, { "code": null, "e": 1682, "s": 1604, "text": "So let’s kick off with the 1st part of the project: EDA & Feature Engineering" }, { "code": null, "e": 1741, "s": 1682, "text": "Let’s import the necessary libraries and the two datasets:" }, { "code": null, "e": 1923, "s": 1741, "text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snsapplication = pd.read_csv(\"application_record.csv\")credit = pd.read_csv(\"credit_record.csv\")" }, { "code": null, "e": 2294, "s": 1923, "text": "As shared above, while the Application dataset provides all data points from the personal information submitted by the existing banking customers (e.g. id, gender, income, etc.), the Credit dataset maps each corresponding id with his/her loan repayment status (e.g. X stands for no loan of the month, C for paid off and >0 implying the number of payment-overdue months)." }, { "code": null, "e": 2472, "s": 2294, "text": "For better usability of the Credit information, I cleaned up the dataset by converting the “Status” columns to numeric as well as grouped it by Customer ID and the latest month:" }, { "code": null, "e": 2786, "s": 2472, "text": "credit.status = credit.status.replace({'X':-2, 'C': -1})credit.status = credit.status.astype('int')credit.status = credit.status.apply(lambda x:x+1) credit_month = credit.groupby('id').months_balance.max().reset_index()record = pd.merge(credit_month, credit, how=\"inner\", on=[\"id\", \"months_balance\"])record.head()" }, { "code": null, "e": 3178, "s": 2786, "text": "When all had been set, I then combined the newly processed dataset with the Application utilizing “inner merge”. On top of this, if you refer back to the original dataset, “Birth_date” and “Employment” are the number of days counted backwards from today, which is a bit difficult to understand initially. As such, I decided to convert these variables into positive numbers and years instead." }, { "code": null, "e": 3373, "s": 3178, "text": "df['age'] = df.birth_date.apply(lambda x: round(x/-365,0))df['year_of_employment'] = df.employment.apply(lambda x: round(x/-365,0) if x<0 else 0)df = df.drop(columns=[\"birth_date\",\"employment\"])" }, { "code": null, "e": 3710, "s": 3373, "text": "Moving on, two highlights of every EDA that I suggest you to never ignore are (1) checking null values and (2) handling outliers. The former ensures that we have a 100% clean dataset before processing and plugging into modelling while the latter helps avoid your dataset getting overly skewed as a result of marginally extreme outliers." }, { "code": null, "e": 3784, "s": 3710, "text": "df.isnull().sum()df.occupation_type = df.occupation_type.fillna(\"Others\")" }, { "code": null, "e": 3903, "s": 3784, "text": "“Occupation Type” is the only variable that has null values (NaN), so I went ahead filling those values with “Others”." }, { "code": null, "e": 4072, "s": 3903, "text": "Using df.describe and sns.boxplot, I was able to find out that “Annual Income” and “Fam Members” are two variables that have outliers in the dataset, visually as below:" }, { "code": null, "e": 4185, "s": 4072, "text": "To remove outliers, I wrote a function which can be easily applied across variables with similar issues at once:" }, { "code": null, "e": 4690, "s": 4185, "text": "def remove_outlier(col): q25 = col.quantile(0.25) q75 = col.quantile(0.75) iqr = q75 - q25 cutoff = iqr*1.5 lower = q25 - cutoff upper = q75 + cutoff return lower, upper#Remove outliers for Annual Incomelower_1, upper_1 = remove_outlier(df.annual_income)df = df.loc[(df.annual_income > lower_1) & (df.annual_income < upper_1)] #Remove outliers for Fam Memberslower_2, upper_2 = remove_outlier(df.fam_members)df = df.loc[(df.annual_fam_members > lower_2) & (df.fam_members < upper_2)]" }, { "code": null, "e": 4832, "s": 4690, "text": "We’re almost done with EDA, coming down to define the “target” variable, which you might have heard somewhere in most classification lessons." }, { "code": null, "e": 5155, "s": 4832, "text": "Going back to the topic of this project, Credit Risk Management, we need to determine how we should handle the loan repayment status of the customers. With this dataset, I defined “target = 0” for those who didn’t have any loan or paid off that month while the remaining data, any overdue loan, was mapped to “target = 1”." }, { "code": null, "e": 5276, "s": 5155, "text": "df['target'] = Nonedf.loc[df.status < 1,'target']=0df.loc[df.status >= 1,'target']=1df.target = pd.to_numeric(df.target)" }, { "code": null, "e": 5373, "s": 5276, "text": "What is Feature Engineering and what does it do to help pre-process the data prior to modelling?" }, { "code": null, "e": 5397, "s": 5373, "text": "According to Wikipedia," }, { "code": null, "e": 5606, "s": 5397, "text": "Feature engineering is the process of using domain knowledge to extract features from raw data via data mining techniques. These features can be used to improve the performance of machine learning algorithms." }, { "code": null, "e": 6165, "s": 5606, "text": "In fact, Feature Engineering requires not only domain knowledge but also the understanding of the dataset and the goal of achievement. Particularly, with our dataset, there are quite a number of different features, which we call as independent variables, which have the correlation with the repayment status, which is the target variable (0 or 1). As such, in order to tune out an insightful and actionable model, we need to “engineer” those features by transforming existing and/or adding supporting data, which makes Feature Engineering different from EDA." }, { "code": null, "e": 6448, "s": 6165, "text": "As I have mentioned from the beginning, we will never know which is a better approach until we test it. That being said, I decided to test out 2 scenarios, WITH and WITHOUT touching the target variable, and see if there is any significant difference in the result produced later on." }, { "code": null, "e": 6829, "s": 6448, "text": "Before diving into the implementation, we should be aware that there is no “one-size-fit-all” technique for Feature Engineering as it depends on how you process your features. In this project, I leveraged “Category Encoding” in my dataset, since the majority of the data is categorical, which should be converted to numerical for easier processing in most machine learning models." }, { "code": null, "e": 7101, "s": 6829, "text": "df_a = df #for encoding without targetdf_b = df #for encoding with targetx_a = df_a.iloc[:, 1:-1]y_a = df_a.iloc[:, -1]from sklearn.model_selection import train_test_splitx_a_train, x_a_test, y_a_train, y_a_test = train_test_split(x_a, y_a, test_size=0.3, random_state=1)" }, { "code": null, "e": 7238, "s": 7101, "text": "Two separate dataset were created for two scenarios, so that we are able to manipulate each dataset without fearing it getting mixed up." }, { "code": null, "e": 7570, "s": 7238, "text": "Also, an important highlight to note before processing is that we are highly recommended to split the dataset to train and test sets to avoid data leakage. Essentially, if we split after processing, the data of the test set has been exposed, hence not being objective enough to compare against the train set in the modelling phase." }, { "code": null, "e": 7648, "s": 7570, "text": "Depending on the variable type, we will apply the suitable technique to each." }, { "code": null, "e": 7931, "s": 7648, "text": "If you refer back to the dataset, there are 3 types of variable: (1) binary, (2) nominal and (3) continuous. While binary and continuous variables are pretty much self-explanatory, nominal variable refers to a group of different categories that has no intrinsic order to each other." }, { "code": null, "e": 8117, "s": 7931, "text": "For binary variables in our dataset (e.g. gender, car, property), we can choose either Label Encoder or Label Binarizer from sklearn library, which will map the original data to 0 or 1:" }, { "code": null, "e": 8485, "s": 8117, "text": "#Option 1: Label Encoder (applied to >2 categories per variable)from sklearn.preprocessing import LabelEncoder, LabelBinarizerle = LabelEncoder()gender_le = le.fit_transform(x_a_train.gender)#Option 2: LabelBinarizer (applied to 2 categories per variable)bn = LabelBinarizer()gender_bn = np.array(x_a_train.gender).reshape(-1,1)gender_bn = bn.fit_transform(gender_bn)" }, { "code": null, "e": 8904, "s": 8485, "text": "Nominal variables (e.g. income type, education, family status, housing type, occupation type) are categorical which needs converting to numerical prior to modelling. Two common methods of encoding a category is (1) Dummy Encoding and (2) One Hot Encoder, which basically creates n columns as n unique categories within that variable and assigns 0 or 1 depending on the absence/presence of each category in each column." }, { "code": null, "e": 9048, "s": 8904, "text": "The difference between these methods is that Dummy Encoding coverts into n-1 sub-variables while One Hot Encoder converts into n sub-variables." }, { "code": null, "e": 9501, "s": 9048, "text": "#Option 1: Dummy Encoding: kn - k variablesincome_type_dummy = pd.get_dummies(x_a_train.income_type)#Option 2: OneHotEcnoder: kn variablesfrom sklearn.preprocessing import OneHotEncoderonehot = OneHotEncoder(sparse=False, drop='first', handle_unknown='error')income_type_onehot = onehot.fit_transform(x_a_train.income_type.to_numpy().reshape(-1,1))income_type_onehot = pd.DataFrame(income_type_onehot, columns=onehot.get_feature_names(['income_type']))" }, { "code": null, "e": 9728, "s": 9501, "text": "Dummy Encoding can easily be done via pd.get_dummies() as it’s a part of pandas library already. For One Hot Encoder, we need to import it from sklearn library and transform each variable, individually or all at the same time." }, { "code": null, "e": 9999, "s": 9728, "text": "One Hot Encoder was designed to keep the consistency in the number of categories across train and test sets (e.g. handling categories that do not appear in either), so it’s more highly recommended than Dummy Encoding due to easier control with “handle_unknown= “error””." }, { "code": null, "e": 10337, "s": 9999, "text": "However, one of the drawbacks of One Hot Encoder is multicollinearity, which refers to variables or sub-variables highly linearly related to one another and hence reduces the accuracy of our models. This can be rectified or avoided by assigning the parameter of “drop= ‘first’” which helps remove one of the sub-variables after encoding." }, { "code": null, "e": 10568, "s": 10337, "text": "Continuous variables are numeric variables that have an infinite number of values between any two values. Essentially, it takes forever to count! Let’s look at the distribution of each continuous variable in our data set visually:" }, { "code": null, "e": 10978, "s": 10568, "text": "The left figure illustrates the range of age of the customers while the right shows the distribution of different income buckets. Two of the common methods to handle this type of variable is (1) Fixed-width Binning and (2) Adaptive Binning. Particularly, the former creates sub-categories from the pre-defined bins (e.g. age — 10–20, 20–30, 30–40, etc) while the latter relies on the distribution of the data." }, { "code": null, "e": 11430, "s": 10978, "text": "The pros and cons of Fixed-width Binning is that it’s easy and simple to encode the variable yet relatively subjective without taking into consideration the data itself. As such, I suggest opting for Adaptive Binning which closely looks at the data distribution. From what I observed, instead of converting into 2-bin categories, I decided to go for “quantiles” since the original distribution is widely ranged, after which Label Encoding was applied." }, { "code": null, "e": 11858, "s": 11430, "text": "#Convert each variable into 5 equal categories/eachx_a_train['age_binned'] = pd.qcut(x_a_train.age, q=[0, .25, .50, .75, 1])x_a_train['annual_income_binned'] = pd.qcut(x_a_train.annual_income, q=[0, .25, .50, .75, 1])#Apply Label Encoder to assign the label to each category without biasx_a_train['age'] = le.fit_transform(x_a_train['age_binned'])x_a_train['annual_income'] = le.fit_transform(x_a_train['annual_income_binned'])" }, { "code": null, "e": 12025, "s": 11858, "text": "Tada! We have engineered all necessary variables without ever touching the target variable! Now, let’s move to the other prior to fitting each to the modelling phase." }, { "code": null, "e": 12181, "s": 12025, "text": "As the correlation with the target variable is leveraged in this method, we should encode all independent variables in the same way for better objectivity." }, { "code": null, "e": 12257, "s": 12181, "text": "Again, pre-requisite has to be followed: train_test_split before processing" }, { "code": null, "e": 12456, "s": 12257, "text": "x_b = df_b.iloc[:, 1:-1]y_b = df_b.iloc[:, -1]from sklearn.model_selection import train_test_splitx_b_train, x_b_test, y_b_train, y_b_test = train_test_split(x_b, y_b, test_size=0.3, random_state=1)" }, { "code": null, "e": 12678, "s": 12456, "text": "Among the techniques for category encoding with the involvement of the target, I found 3 common options which are widely used: (1) Weight-of-Evidence Encoder (WOE), (2) Target Encoder, and (3) Leave-One-Out Encoder (LOO)." }, { "code": null, "e": 12688, "s": 12678, "text": "In brief," }, { "code": null, "e": 13033, "s": 12688, "text": "WOE Encoder: Weight-of-evidence encoding is a widely used technique in credit risk modelling which gets the maximum difference among the unique categories in each variable related to the target. This can be easily understood with its mathematical calculation as below — the natural log of % Good (in this case, target = 0) / % Bad (target = 1):" }, { "code": null, "e": 13340, "s": 13033, "text": "Target Encoder & LOO Encoder: while the former method replaces a categorical value with the mean of the target variable across all rows in the dataset, the latter does the same but excludes the row itself. The reason being is to avoid direct target leakage from using too much information before modelling." }, { "code": null, "e": 13882, "s": 13340, "text": "#Option 1: WOE Encoderimport category_encoders as cewoe = ce.WOEEncoder()def woe_encoder(col, target): for i in range(len(x_b_train.columns)): col.iloc[:,i] = woe.fit_transform(col, target) return coldf_woe_train = woe_encoder(x_b_train, y_b_train)#Option 2: Target Encoderfrom category_encoders import TargetEncoderte = TargetEncoder()def target_encoder(col, target): for i in range(len(x_b_train.columns)): col.iloc[:,i] = te.fit_transform(col, target) return coldf_te_train = target_encoder(x_b_train, y_b_train)" }, { "code": null, "e": 14226, "s": 13882, "text": "After testing both methods, it seems that the newly encoded dataset between the two is not much of a difference to each other. Hence, I opted for the dataset with WOE Encoder for the following steps of this project. However, please test out on other datasets, which might produce a different result possibly due to different data distribution." }, { "code": null, "e": 14281, "s": 14226, "text": "Voila! That’s a wrap for the 1st part of this project!" }, { "code": null, "e": 14563, "s": 14281, "text": "As shared above, the project was created as a repository of learning notes and highlights along the journey of improving my Data Science skillsets. Hence, I have tested out multiple methods per each section in order to find out the best performing technique for use moving forward." }, { "code": null, "e": 14699, "s": 14563, "text": "Do look out for the next 2 parts which covers Feature Scaling/Selection and Machine Learning Modelling! In the meantime, let’s connect:" } ]
How (NOT) To Predict Stock Prices With LSTMs | by Viraf | Towards Data Science
Not so recently, a brilliant and ‘original’ idea suddenly struck me — what if I could predict stock prices using Machine Learning. After all, a time series can be easily modeled with an LSTM. I could see myself getting rich overnight! If this is so easy, why hasn’t anyone done it yet? Very excited at my bright prospects, I powered up my laptop, opened Google, and keyed in “predict stock prices LSTM python.” The results poured in — and very quickly, I realized that my idea was not very original. Well, so much for that. Anyway, I went through many of these articles, and each one of them seemed to have gotten surprisingly good results. But the tutorial ends there — no one put it to test with real money. Why aren’t these people millionaires yet? Something was fishy. As a disclaimer, note that none of the contents of this article is financial advice and is purely educational. Quite obvious, I know, but needs to be said. On the contrary, I am trying to educate you on how to not be fooled by this, and start using your head. Nowadays, with Stocks and Machine Learning both becoming so hands-on, easy-to-use, and accessible, it has become really hard to not fall into this trap, where an incomplete, half-baked knowledge of both fields can lead you into serious trouble. Let’s get started on how to NOT use an LSTM for predicting stock prices. The flow of this article is as follows: A simple introduction to LSTMs. Get historical stock data in python. Create a dataset in a format suitable for the LSTM model. Build and train the LSTM model with TensorFlow Keras. Predict and interpret the results. Long-Short-Term-Memory (LSTM) networks are a type of neural network commonly used to predict time series data. In simple words, they have a memory/cache functionality which helps them learn the long term dependencies and relations in the data. So, looking at the previous N data points, they can predict the next (or next few) points by learning the patterns. I am going to keep this part quite simple. If you want more clarity on how an LSTM functions, I recommend going through this, but you should pretty much understand the main gist and purpose of this article even without an in-depth understanding. There are multiple options to get access to historical stock prices in python, but one of the simplest libraries is yfinance. Quite convenient and free, it gets the job done by scraping data from yahoo finance. !pip install yfinance# Import the required librariesimport yfinance as yfimport pandas as pdimport matplotlib.pyplot as pltfrom pandas.plotting import register_matplotlib_convertersregister_matplotlib_converters() For this article, I will take up the stock prices of ‘Reliance,’ but this is valid for all other instruments as well. The following piece of code downloads stock price data for Reliance over 15 years with a resolution of 1 day and stores it in a pandas dataframe. You can vary these parameters as you deem fit for your experiments. Printing out the head of the pandas dataframe, you can see the various parameters available for the stock data. Plotting out the ‘close’ price to visualize the data, see how nicely the stock has risen in the last few years. The steep drop in March 2020 (due to COVID) is also visible. But it has seemingly beaten this downfall and risen to a new high yet again. A question to ask yourself here — do you think an ML model will be able to capture all this randomness? Let’s fix our problem statement now — the LSTM model shall see the close prices for the last 10 days (called the time_step) and predict the close price for the next day. For simplicity, let’s test on only the final 200 days. We can train on the rest of the data. We have 3486 data points to train on (will increase depending on the day you execute the code). (Note that you can vary this according to your requirements, but I feel this should be sufficient to put forth my point). # Get Close datadf = data[['Close']].copy()# Split data into train and testtrain, test = df.iloc[0:-200], df.iloc[-200:len(df)]print(len(train), len(test))>>> 3486 200 Now, we need to normalize our data. One common mistake people make at this stage is that they normalize the test data separately as well. But in a practical scenario, the test data will be in real-time, so you won’t know the minimum or maximum or average values beforehand! If you provide the model with this information from the future, you basically end up providing a trend or guideline that the predicted prices need to follow. I have seen so many authors make this error, and I don’t blame them since it took me a while to realize this too. To tackle this issue, we will use the minimum and maximum of the training data to normalize the test data as well. This should work as a decent approximation (of course, there are better ways to do it, for example, take min and max values of only last N prices). Finally, let’s structure the data so that our LSTM model can easily read them. The LSTM requires input in the form of [samples, time_steps, features]. The following code creates the dataset in this needed format. For our model, we will be using the TensorFlow Keras library in python. The simple sequential model has an LSTM layer followed by a dropout (to reduce over-fitting) and a final dense layer (our output prediction). We shall use the ever-dependable ‘Adam’ optimizer with Mean Absolute Error loss. Train it for about 50 epochs. Remember to keep shuffle = False (since the sequence of samples is important — kind of the whole point here :P). The summary of the model is as shown in the picture below. The model is very minimal, but you can try and play around with a few more layers and whatnot. Be careful not to overfit the data though (even with this small model the data overfits). Post-training, plot the loss as: plt.plot(history.history['loss'], label='train')plt.legend();plt.show() The training loss has clearly reduced over the epochs (with some ripples). The model seems to have trained well. Or has it? Let’s evaluate it. Pass the test set through the model. Rescale the results (remember, we had normalized it earlier) and finally plot them out to see how it performed visually. Look at the predictions in the image below! They are shockingly good! The model seems to have predicted the COVID fall as well! This is brilliant! We can make millions in the stock market now! Most tutorials end here. The authors’ final words being ‘The results look promising, tweak the parameters, alter the model, etc.’ But wait, before you go quit your job to become a full-time trader, let’s zoom into the results once! Can you see what is happening now? The predicted price is trailing the true price by 1 time-step. The model is just predicting a value close to the previous price it sees, as this is the best prediction for the next price. Let me make it easier for you. Let’s plot the true price value with a lag of 1 day in the image below. See how the shapes of the plots match — now it is clearer to see that our model is just trying to mimic the last price it sees. What seems to be the problem? The LSTM is not doing anything wrong! As you know, stocks are quite dynamic and random (for all practical purposes). The model is giving the best possible guess for a random walk problem, which turns out to be the previous day’s price. But this means that the model is not predicting anything useful for trading/investing. And that is why blindly using this in practice is very dangerous. I am not saying that the task of predicting stock prices is impossible. It definitely is possible — there are several algorithms and trading bots out there, which employ some amount of machine learning — but it is not going to be so damn straightforward. A little more effort will be required to formulate the problem statement, inputs, and model. Some good direction to head in would be predicting changes in value (a derivative or second derivative) instead of the value itself. Predicting only the stock price movements (binary classification problem) could be another option. Or to use an ensemble of models to achieve combined/different goals. I’d recommend that you try to gain stronger domain knowledge in these fields first, followed by explorations — don’t restrict yourself to these ideas or other ideas you see on the internet. I am not saying I am an expert in these fields — I am just putting forward the conclusions I got to after my explorations with this topic, so feel free to point out my errors or add anything I missed. Thank you for your time. Can an ML model literally read visual stock price charts? Check out my article below to see the results! towardsdatascience.com Why waste time and effort in trying to predict the stock market when you can do this... medium.com Or, check out some of my other machine learning articles. I’m sure you’ll find them useful...
[ { "code": null, "e": 458, "s": 172, "text": "Not so recently, a brilliant and ‘original’ idea suddenly struck me — what if I could predict stock prices using Machine Learning. After all, a time series can be easily modeled with an LSTM. I could see myself getting rich overnight! If this is so easy, why hasn’t anyone done it yet?" }, { "code": null, "e": 945, "s": 458, "text": "Very excited at my bright prospects, I powered up my laptop, opened Google, and keyed in “predict stock prices LSTM python.” The results poured in — and very quickly, I realized that my idea was not very original. Well, so much for that. Anyway, I went through many of these articles, and each one of them seemed to have gotten surprisingly good results. But the tutorial ends there — no one put it to test with real money. Why aren’t these people millionaires yet? Something was fishy." }, { "code": null, "e": 1205, "s": 945, "text": "As a disclaimer, note that none of the contents of this article is financial advice and is purely educational. Quite obvious, I know, but needs to be said. On the contrary, I am trying to educate you on how to not be fooled by this, and start using your head." }, { "code": null, "e": 1450, "s": 1205, "text": "Nowadays, with Stocks and Machine Learning both becoming so hands-on, easy-to-use, and accessible, it has become really hard to not fall into this trap, where an incomplete, half-baked knowledge of both fields can lead you into serious trouble." }, { "code": null, "e": 1563, "s": 1450, "text": "Let’s get started on how to NOT use an LSTM for predicting stock prices. The flow of this article is as follows:" }, { "code": null, "e": 1595, "s": 1563, "text": "A simple introduction to LSTMs." }, { "code": null, "e": 1632, "s": 1595, "text": "Get historical stock data in python." }, { "code": null, "e": 1690, "s": 1632, "text": "Create a dataset in a format suitable for the LSTM model." }, { "code": null, "e": 1744, "s": 1690, "text": "Build and train the LSTM model with TensorFlow Keras." }, { "code": null, "e": 1779, "s": 1744, "text": "Predict and interpret the results." }, { "code": null, "e": 2139, "s": 1779, "text": "Long-Short-Term-Memory (LSTM) networks are a type of neural network commonly used to predict time series data. In simple words, they have a memory/cache functionality which helps them learn the long term dependencies and relations in the data. So, looking at the previous N data points, they can predict the next (or next few) points by learning the patterns." }, { "code": null, "e": 2385, "s": 2139, "text": "I am going to keep this part quite simple. If you want more clarity on how an LSTM functions, I recommend going through this, but you should pretty much understand the main gist and purpose of this article even without an in-depth understanding." }, { "code": null, "e": 2596, "s": 2385, "text": "There are multiple options to get access to historical stock prices in python, but one of the simplest libraries is yfinance. Quite convenient and free, it gets the job done by scraping data from yahoo finance." }, { "code": null, "e": 2810, "s": 2596, "text": "!pip install yfinance# Import the required librariesimport yfinance as yfimport pandas as pdimport matplotlib.pyplot as pltfrom pandas.plotting import register_matplotlib_convertersregister_matplotlib_converters()" }, { "code": null, "e": 2928, "s": 2810, "text": "For this article, I will take up the stock prices of ‘Reliance,’ but this is valid for all other instruments as well." }, { "code": null, "e": 3142, "s": 2928, "text": "The following piece of code downloads stock price data for Reliance over 15 years with a resolution of 1 day and stores it in a pandas dataframe. You can vary these parameters as you deem fit for your experiments." }, { "code": null, "e": 3254, "s": 3142, "text": "Printing out the head of the pandas dataframe, you can see the various parameters available for the stock data." }, { "code": null, "e": 3504, "s": 3254, "text": "Plotting out the ‘close’ price to visualize the data, see how nicely the stock has risen in the last few years. The steep drop in March 2020 (due to COVID) is also visible. But it has seemingly beaten this downfall and risen to a new high yet again." }, { "code": null, "e": 3608, "s": 3504, "text": "A question to ask yourself here — do you think an ML model will be able to capture all this randomness?" }, { "code": null, "e": 3778, "s": 3608, "text": "Let’s fix our problem statement now — the LSTM model shall see the close prices for the last 10 days (called the time_step) and predict the close price for the next day." }, { "code": null, "e": 3967, "s": 3778, "text": "For simplicity, let’s test on only the final 200 days. We can train on the rest of the data. We have 3486 data points to train on (will increase depending on the day you execute the code)." }, { "code": null, "e": 4089, "s": 3967, "text": "(Note that you can vary this according to your requirements, but I feel this should be sufficient to put forth my point)." }, { "code": null, "e": 4257, "s": 4089, "text": "# Get Close datadf = data[['Close']].copy()# Split data into train and testtrain, test = df.iloc[0:-200], df.iloc[-200:len(df)]print(len(train), len(test))>>> 3486 200" }, { "code": null, "e": 4803, "s": 4257, "text": "Now, we need to normalize our data. One common mistake people make at this stage is that they normalize the test data separately as well. But in a practical scenario, the test data will be in real-time, so you won’t know the minimum or maximum or average values beforehand! If you provide the model with this information from the future, you basically end up providing a trend or guideline that the predicted prices need to follow. I have seen so many authors make this error, and I don’t blame them since it took me a while to realize this too." }, { "code": null, "e": 5066, "s": 4803, "text": "To tackle this issue, we will use the minimum and maximum of the training data to normalize the test data as well. This should work as a decent approximation (of course, there are better ways to do it, for example, take min and max values of only last N prices)." }, { "code": null, "e": 5279, "s": 5066, "text": "Finally, let’s structure the data so that our LSTM model can easily read them. The LSTM requires input in the form of [samples, time_steps, features]. The following code creates the dataset in this needed format." }, { "code": null, "e": 5717, "s": 5279, "text": "For our model, we will be using the TensorFlow Keras library in python. The simple sequential model has an LSTM layer followed by a dropout (to reduce over-fitting) and a final dense layer (our output prediction). We shall use the ever-dependable ‘Adam’ optimizer with Mean Absolute Error loss. Train it for about 50 epochs. Remember to keep shuffle = False (since the sequence of samples is important — kind of the whole point here :P)." }, { "code": null, "e": 5961, "s": 5717, "text": "The summary of the model is as shown in the picture below. The model is very minimal, but you can try and play around with a few more layers and whatnot. Be careful not to overfit the data though (even with this small model the data overfits)." }, { "code": null, "e": 5994, "s": 5961, "text": "Post-training, plot the loss as:" }, { "code": null, "e": 6066, "s": 5994, "text": "plt.plot(history.history['loss'], label='train')plt.legend();plt.show()" }, { "code": null, "e": 6209, "s": 6066, "text": "The training loss has clearly reduced over the epochs (with some ripples). The model seems to have trained well. Or has it? Let’s evaluate it." }, { "code": null, "e": 6367, "s": 6209, "text": "Pass the test set through the model. Rescale the results (remember, we had normalized it earlier) and finally plot them out to see how it performed visually." }, { "code": null, "e": 6560, "s": 6367, "text": "Look at the predictions in the image below! They are shockingly good! The model seems to have predicted the COVID fall as well! This is brilliant! We can make millions in the stock market now!" }, { "code": null, "e": 6792, "s": 6560, "text": "Most tutorials end here. The authors’ final words being ‘The results look promising, tweak the parameters, alter the model, etc.’ But wait, before you go quit your job to become a full-time trader, let’s zoom into the results once!" }, { "code": null, "e": 7015, "s": 6792, "text": "Can you see what is happening now? The predicted price is trailing the true price by 1 time-step. The model is just predicting a value close to the previous price it sees, as this is the best prediction for the next price." }, { "code": null, "e": 7246, "s": 7015, "text": "Let me make it easier for you. Let’s plot the true price value with a lag of 1 day in the image below. See how the shapes of the plots match — now it is clearer to see that our model is just trying to mimic the last price it sees." }, { "code": null, "e": 7665, "s": 7246, "text": "What seems to be the problem? The LSTM is not doing anything wrong! As you know, stocks are quite dynamic and random (for all practical purposes). The model is giving the best possible guess for a random walk problem, which turns out to be the previous day’s price. But this means that the model is not predicting anything useful for trading/investing. And that is why blindly using this in practice is very dangerous." }, { "code": null, "e": 7920, "s": 7665, "text": "I am not saying that the task of predicting stock prices is impossible. It definitely is possible — there are several algorithms and trading bots out there, which employ some amount of machine learning — but it is not going to be so damn straightforward." }, { "code": null, "e": 8504, "s": 7920, "text": "A little more effort will be required to formulate the problem statement, inputs, and model. Some good direction to head in would be predicting changes in value (a derivative or second derivative) instead of the value itself. Predicting only the stock price movements (binary classification problem) could be another option. Or to use an ensemble of models to achieve combined/different goals. I’d recommend that you try to gain stronger domain knowledge in these fields first, followed by explorations — don’t restrict yourself to these ideas or other ideas you see on the internet." }, { "code": null, "e": 8730, "s": 8504, "text": "I am not saying I am an expert in these fields — I am just putting forward the conclusions I got to after my explorations with this topic, so feel free to point out my errors or add anything I missed. Thank you for your time." }, { "code": null, "e": 8835, "s": 8730, "text": "Can an ML model literally read visual stock price charts? Check out my article below to see the results!" }, { "code": null, "e": 8858, "s": 8835, "text": "towardsdatascience.com" }, { "code": null, "e": 8946, "s": 8858, "text": "Why waste time and effort in trying to predict the stock market when you can do this..." }, { "code": null, "e": 8957, "s": 8946, "text": "medium.com" } ]
Program to find the last two digits of x^y - GeeksforGeeks
16 Apr, 2020 The task is to find the last two digits of x^y. Since the digits with which it can end are 0-9, Hence this problem can be divided into 5 cases: Case 1: when x ends with 1For finding the last two digit of a number, when the number ends with 1 then we have to do following steps shown as in the figure.Example: 21^48So, Last two digit of 21^48 is 81.Example: 31^35So, Last two digit of 31^35 is 51.Case 2: when x ends with 3, 7, 9For finding the last two digit of a number, when the number ends with 3, 7, 9 then we have to apply cyclicity concept to convert the last digit as a 1.cyclicity of 3:3^1 = 33^2 = 93^3 = 73^4 = 1cyclicity of 7:7^1 = 77^2 = 97^3 = 37^4 = 1cyclicity of 9:9^1 = 99^2 = 1Example1: 23^34Solution:Last digit of 23^34 is 3 so, we use cyclicity of 3 .3^4 gives 1 so, we take 23^4((23)^4)^8 * (23)^2last two digit of (23)^4) is 41, so we take (41)^8 and solve according to the given diagram.So last digit of (41)^8 is 21 .solve (23)^2, the last digit of (23)^2 is 29.Now multiply last digit of (41)^8 i.e 21 with the last digit of (23)^2 i.e 29i.e 21 * 29 = 609So, Last two non zero digit of 23^34 is 09.Example2: 37^45Solution:Last digit of 37^45 is 7 so, we use cyclicity of 7 .7^4 gives 1 so, we take 37^4((37)^4)^11 * (37)^1last two digit of (37)^4) is 61, so we take (61)^11 and solve according to the diagram.So last digit of (61)^11 is 61 .solve (37)^1, the last digit of (37)^1 is 37.Now multiply last digit of (61)^11 i.e 61 with the last digit of (37)^1 i.e 37i.e 61 * 37 = 2257So, Last two non zero digit of 37^45 is 57.Example3: 59^22Solution:Last digit of 59^22 is 9 so, we use cyclicity of 9 .9^2 gives 1 so, we take 59^2((59)^2)^11last two digit of (59)^2 is 81, so we take (81)^11 and solve according to the diagram.So last digit of (81)^11 is 81 .So, Last two non zero digit of 59^22 is 81.Case 3: when x ends with 2, 4, 6, 8For finding the last digit of a number ends with 2, 4, 6, 8; We use number 76 which is a type of magic number because its square, cube and etc contain last 2 digit numbers as itself i.e 76.Take an example :square of 76 = 5776, its last two digit =76cube of 76 = 438976, its last two digit=76So we take two cases:if (2^10)^even power then it always return 76 .if (2^10)^odd power then it always return 24 .Steps for finding last two digits Firstly, convert given number in to these formats if (2^10)^power. Here power will be odd or even according to the question. Now, check power will be odd or even. if power is odd then its value will be 24. if power is even then its value will be 76. ExamplesExample1: Find last 2 digit of 2^453.Solution:Step 1:- conversion2^453 = (2^10)^45 * 2^3Step 2:- odd power so we take 24= 24 * 8= 192So, Last two non zero digits of 2^453 are 92.Example2: Find last 2 digits of 4^972.Solution:step 1:- conversion4^972 = (2^2)^972= 2^1944= (2^10)^194 * 2^4step 2:- even power so, we take 76= 76 * 16= 1216So, Last two non zero digits of 4^972 are 16.Example3: Find last 2 digits of 6^600.Solution:step 1:- conversion6^600 = (2)^600 * (3)^600= (2^10)^60 * ((3)^4)^150 {Apply case 2 in (3)^600}step 2:- (2^10)^60 has even power so, we take 76 as the last digitstep 3:- Solve ((3)^4)^150, we get 01 as the last digitstep 4:- last digit of (2^10)^60 i.e 76 multiply with the last digit of ((3)^4)^150 i.e 01step 5:- i.e 76 * 01 = 76So, Last two non zero of 6^600 is 76.Example4: Find last 2 digits of 8^330.Solution:step 1:- conversion8^33 = (2^3)^110= (2)^330step 2:- (2^10)^33 has odd power so, we take 24 as the last digitSo, Last two non zero digits of 8^330 are 24.Case 4: when x ends with 5For finding the last two digit of a number, when the number ends with 5 then we have to follow the table which is given below.Example1: Find last 2 digit of 25^25.Solution:first digit of number is 2 i.e evenLast digit of a power is 5 i.e oddNow, even-odd combination gives last digit as a 25So, the last two non zero digits of 25^25 are 25.Example2: Find last 2 digit of 25^222.Solution:first digit of number is 2 i.e evenLast digit of a power is 2 i.e evenNow, even-even combination gives last digit as a 25So, the last two non zero digits of 25^222 are 25.Example3: Find last 2 digit of 165^222.Solution:first digit of number is 1 i.e oddLast digit of a power is 2 i.e evenNow, odd-even combination gives last digit as a 25So, the last two non zero digits of 165^222 are 25.Example4: Find last 2 digit of 165^221.Solution:first digit of number is 1 i.e oddLast digit of a power is 1 i.e oddNow, odd-odd combination gives last digit as a 75So, the last two non zero digits of 165^221 are 75.Case 5: when x ends with 0For finding the last two digit of a number, when the number ends with 0 then we have to check next digit and according to the digit calculate the last digit.Example: Find last 2 digit of 150^221.Solution:150 last digit is 0 so we check next digit i.e 5 and apply case 4first digit of number is 1 i.e oddLast digit of a power is 1 i.e oddNow, odd-odd combination gives last digit as a 75So, the last two non zero digits of 165^221 is 75. Case 1: when x ends with 1For finding the last two digit of a number, when the number ends with 1 then we have to do following steps shown as in the figure.Example: 21^48So, Last two digit of 21^48 is 81.Example: 31^35So, Last two digit of 31^35 is 51. For finding the last two digit of a number, when the number ends with 1 then we have to do following steps shown as in the figure. Example: 21^48 So, Last two digit of 21^48 is 81. Example: 31^35 So, Last two digit of 31^35 is 51. Case 2: when x ends with 3, 7, 9For finding the last two digit of a number, when the number ends with 3, 7, 9 then we have to apply cyclicity concept to convert the last digit as a 1.cyclicity of 3:3^1 = 33^2 = 93^3 = 73^4 = 1cyclicity of 7:7^1 = 77^2 = 97^3 = 37^4 = 1cyclicity of 9:9^1 = 99^2 = 1Example1: 23^34Solution:Last digit of 23^34 is 3 so, we use cyclicity of 3 .3^4 gives 1 so, we take 23^4((23)^4)^8 * (23)^2last two digit of (23)^4) is 41, so we take (41)^8 and solve according to the given diagram.So last digit of (41)^8 is 21 .solve (23)^2, the last digit of (23)^2 is 29.Now multiply last digit of (41)^8 i.e 21 with the last digit of (23)^2 i.e 29i.e 21 * 29 = 609So, Last two non zero digit of 23^34 is 09.Example2: 37^45Solution:Last digit of 37^45 is 7 so, we use cyclicity of 7 .7^4 gives 1 so, we take 37^4((37)^4)^11 * (37)^1last two digit of (37)^4) is 61, so we take (61)^11 and solve according to the diagram.So last digit of (61)^11 is 61 .solve (37)^1, the last digit of (37)^1 is 37.Now multiply last digit of (61)^11 i.e 61 with the last digit of (37)^1 i.e 37i.e 61 * 37 = 2257So, Last two non zero digit of 37^45 is 57.Example3: 59^22Solution:Last digit of 59^22 is 9 so, we use cyclicity of 9 .9^2 gives 1 so, we take 59^2((59)^2)^11last two digit of (59)^2 is 81, so we take (81)^11 and solve according to the diagram.So last digit of (81)^11 is 81 .So, Last two non zero digit of 59^22 is 81. For finding the last two digit of a number, when the number ends with 3, 7, 9 then we have to apply cyclicity concept to convert the last digit as a 1. cyclicity of 3: 3^1 = 33^2 = 93^3 = 73^4 = 1 cyclicity of 7: 7^1 = 77^2 = 97^3 = 37^4 = 1 cyclicity of 9: 9^1 = 99^2 = 1 Example1: 23^34Solution: Last digit of 23^34 is 3 so, we use cyclicity of 3 . 3^4 gives 1 so, we take 23^4 ((23)^4)^8 * (23)^2 last two digit of (23)^4) is 41, so we take (41)^8 and solve according to the given diagram. So last digit of (41)^8 is 21 . solve (23)^2, the last digit of (23)^2 is 29. Now multiply last digit of (41)^8 i.e 21 with the last digit of (23)^2 i.e 29 i.e 21 * 29 = 609 So, Last two non zero digit of 23^34 is 09. Example2: 37^45Solution: Last digit of 37^45 is 7 so, we use cyclicity of 7 . 7^4 gives 1 so, we take 37^4 ((37)^4)^11 * (37)^1 last two digit of (37)^4) is 61, so we take (61)^11 and solve according to the diagram. So last digit of (61)^11 is 61 . solve (37)^1, the last digit of (37)^1 is 37. Now multiply last digit of (61)^11 i.e 61 with the last digit of (37)^1 i.e 37 i.e 61 * 37 = 2257 So, Last two non zero digit of 37^45 is 57. Example3: 59^22Solution: Last digit of 59^22 is 9 so, we use cyclicity of 9 . 9^2 gives 1 so, we take 59^2 ((59)^2)^11 last two digit of (59)^2 is 81, so we take (81)^11 and solve according to the diagram. So last digit of (81)^11 is 81 . So, Last two non zero digit of 59^22 is 81. Case 3: when x ends with 2, 4, 6, 8For finding the last digit of a number ends with 2, 4, 6, 8; We use number 76 which is a type of magic number because its square, cube and etc contain last 2 digit numbers as itself i.e 76.Take an example :square of 76 = 5776, its last two digit =76cube of 76 = 438976, its last two digit=76So we take two cases:if (2^10)^even power then it always return 76 .if (2^10)^odd power then it always return 24 .Steps for finding last two digits Firstly, convert given number in to these formats if (2^10)^power. Here power will be odd or even according to the question. Now, check power will be odd or even. if power is odd then its value will be 24. if power is even then its value will be 76. ExamplesExample1: Find last 2 digit of 2^453.Solution:Step 1:- conversion2^453 = (2^10)^45 * 2^3Step 2:- odd power so we take 24= 24 * 8= 192So, Last two non zero digits of 2^453 are 92.Example2: Find last 2 digits of 4^972.Solution:step 1:- conversion4^972 = (2^2)^972= 2^1944= (2^10)^194 * 2^4step 2:- even power so, we take 76= 76 * 16= 1216So, Last two non zero digits of 4^972 are 16.Example3: Find last 2 digits of 6^600.Solution:step 1:- conversion6^600 = (2)^600 * (3)^600= (2^10)^60 * ((3)^4)^150 {Apply case 2 in (3)^600}step 2:- (2^10)^60 has even power so, we take 76 as the last digitstep 3:- Solve ((3)^4)^150, we get 01 as the last digitstep 4:- last digit of (2^10)^60 i.e 76 multiply with the last digit of ((3)^4)^150 i.e 01step 5:- i.e 76 * 01 = 76So, Last two non zero of 6^600 is 76.Example4: Find last 2 digits of 8^330.Solution:step 1:- conversion8^33 = (2^3)^110= (2)^330step 2:- (2^10)^33 has odd power so, we take 24 as the last digitSo, Last two non zero digits of 8^330 are 24. For finding the last digit of a number ends with 2, 4, 6, 8; We use number 76 which is a type of magic number because its square, cube and etc contain last 2 digit numbers as itself i.e 76. Take an example : square of 76 = 5776, its last two digit =76cube of 76 = 438976, its last two digit=76 So we take two cases: if (2^10)^even power then it always return 76 .if (2^10)^odd power then it always return 24 . if (2^10)^even power then it always return 76 . if (2^10)^odd power then it always return 24 . Steps for finding last two digits Firstly, convert given number in to these formats if (2^10)^power. Here power will be odd or even according to the question. Now, check power will be odd or even. if power is odd then its value will be 24. if power is even then its value will be 76. Firstly, convert given number in to these formats if (2^10)^power. Here power will be odd or even according to the question. Now, check power will be odd or even. if power is odd then its value will be 24. if power is even then its value will be 76. Examples Example1: Find last 2 digit of 2^453. Solution: Step 1:- conversion2^453 = (2^10)^45 * 2^3 Step 2:- odd power so we take 24= 24 * 8= 192 So, Last two non zero digits of 2^453 are 92. Example2: Find last 2 digits of 4^972. Solution: step 1:- conversion4^972 = (2^2)^972= 2^1944= (2^10)^194 * 2^4 step 2:- even power so, we take 76= 76 * 16= 1216 So, Last two non zero digits of 4^972 are 16. Example3: Find last 2 digits of 6^600. Solution: step 1:- conversion6^600 = (2)^600 * (3)^600= (2^10)^60 * ((3)^4)^150 {Apply case 2 in (3)^600} step 2:- (2^10)^60 has even power so, we take 76 as the last digit step 3:- Solve ((3)^4)^150, we get 01 as the last digit step 4:- last digit of (2^10)^60 i.e 76 multiply with the last digit of ((3)^4)^150 i.e 01 step 5:- i.e 76 * 01 = 76 So, Last two non zero of 6^600 is 76. Example4: Find last 2 digits of 8^330. Solution: step 1:- conversion8^33 = (2^3)^110= (2)^330 step 2:- (2^10)^33 has odd power so, we take 24 as the last digit So, Last two non zero digits of 8^330 are 24. Case 4: when x ends with 5For finding the last two digit of a number, when the number ends with 5 then we have to follow the table which is given below.Example1: Find last 2 digit of 25^25.Solution:first digit of number is 2 i.e evenLast digit of a power is 5 i.e oddNow, even-odd combination gives last digit as a 25So, the last two non zero digits of 25^25 are 25.Example2: Find last 2 digit of 25^222.Solution:first digit of number is 2 i.e evenLast digit of a power is 2 i.e evenNow, even-even combination gives last digit as a 25So, the last two non zero digits of 25^222 are 25.Example3: Find last 2 digit of 165^222.Solution:first digit of number is 1 i.e oddLast digit of a power is 2 i.e evenNow, odd-even combination gives last digit as a 25So, the last two non zero digits of 165^222 are 25.Example4: Find last 2 digit of 165^221.Solution:first digit of number is 1 i.e oddLast digit of a power is 1 i.e oddNow, odd-odd combination gives last digit as a 75So, the last two non zero digits of 165^221 are 75. For finding the last two digit of a number, when the number ends with 5 then we have to follow the table which is given below. Example1: Find last 2 digit of 25^25. Solution: first digit of number is 2 i.e even Last digit of a power is 5 i.e odd Now, even-odd combination gives last digit as a 25 So, the last two non zero digits of 25^25 are 25. Example2: Find last 2 digit of 25^222. Solution: first digit of number is 2 i.e even Last digit of a power is 2 i.e even Now, even-even combination gives last digit as a 25 So, the last two non zero digits of 25^222 are 25. Example3: Find last 2 digit of 165^222. Solution: first digit of number is 1 i.e odd Last digit of a power is 2 i.e even Now, odd-even combination gives last digit as a 25 So, the last two non zero digits of 165^222 are 25. Example4: Find last 2 digit of 165^221. Solution: first digit of number is 1 i.e odd Last digit of a power is 1 i.e odd Now, odd-odd combination gives last digit as a 75 So, the last two non zero digits of 165^221 are 75. Case 5: when x ends with 0For finding the last two digit of a number, when the number ends with 0 then we have to check next digit and according to the digit calculate the last digit.Example: Find last 2 digit of 150^221.Solution:150 last digit is 0 so we check next digit i.e 5 and apply case 4first digit of number is 1 i.e oddLast digit of a power is 1 i.e oddNow, odd-odd combination gives last digit as a 75So, the last two non zero digits of 165^221 is 75. For finding the last two digit of a number, when the number ends with 0 then we have to check next digit and according to the digit calculate the last digit. Example: Find last 2 digit of 150^221. Solution: 150 last digit is 0 so we check next digit i.e 5 and apply case 4 first digit of number is 1 i.e odd Last digit of a power is 1 i.e odd Now, odd-odd combination gives last digit as a 75 So, the last two non zero digits of 165^221 is 75. harshitSingh_11 number-digits Aptitude Mathematical Puzzles Mathematical Puzzles Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Puzzle | How much money did the man have before entering the bank? Aptitude | GATE CS 1998 | Question 49 Aptitude | Arithmetic Aptitude 4 | Question 3 Order and Ranking Questions & Answers Puzzle | Splitting a Cake with a Missing Piece in two equal portion Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 25957, "s": 25929, "text": "\n16 Apr, 2020" }, { "code": null, "e": 26005, "s": 25957, "text": "The task is to find the last two digits of x^y." }, { "code": null, "e": 26101, "s": 26005, "text": "Since the digits with which it can end are 0-9, Hence this problem can be divided into 5 cases:" }, { "code": null, "e": 30994, "s": 26101, "text": "Case 1: when x ends with 1For finding the last two digit of a number, when the number ends with 1 then we have to do following steps shown as in the figure.Example: 21^48So, Last two digit of 21^48 is 81.Example: 31^35So, Last two digit of 31^35 is 51.Case 2: when x ends with 3, 7, 9For finding the last two digit of a number, when the number ends with 3, 7, 9 then we have to apply cyclicity concept to convert the last digit as a 1.cyclicity of 3:3^1 = 33^2 = 93^3 = 73^4 = 1cyclicity of 7:7^1 = 77^2 = 97^3 = 37^4 = 1cyclicity of 9:9^1 = 99^2 = 1Example1: 23^34Solution:Last digit of 23^34 is 3 so, we use cyclicity of 3 .3^4 gives 1 so, we take 23^4((23)^4)^8 * (23)^2last two digit of (23)^4) is 41, so we take (41)^8 and solve according to the given diagram.So last digit of (41)^8 is 21 .solve (23)^2, the last digit of (23)^2 is 29.Now multiply last digit of (41)^8 i.e 21 with the last digit of (23)^2 i.e 29i.e 21 * 29 = 609So, Last two non zero digit of 23^34 is 09.Example2: 37^45Solution:Last digit of 37^45 is 7 so, we use cyclicity of 7 .7^4 gives 1 so, we take 37^4((37)^4)^11 * (37)^1last two digit of (37)^4) is 61, so we take (61)^11 and solve according to the diagram.So last digit of (61)^11 is 61 .solve (37)^1, the last digit of (37)^1 is 37.Now multiply last digit of (61)^11 i.e 61 with the last digit of (37)^1 i.e 37i.e 61 * 37 = 2257So, Last two non zero digit of 37^45 is 57.Example3: 59^22Solution:Last digit of 59^22 is 9 so, we use cyclicity of 9 .9^2 gives 1 so, we take 59^2((59)^2)^11last two digit of (59)^2 is 81, so we take (81)^11 and solve according to the diagram.So last digit of (81)^11 is 81 .So, Last two non zero digit of 59^22 is 81.Case 3: when x ends with 2, 4, 6, 8For finding the last digit of a number ends with 2, 4, 6, 8; We use number 76 which is a type of magic number because its square, cube and etc contain last 2 digit numbers as itself i.e 76.Take an example :square of 76 = 5776, its last two digit =76cube of 76 = 438976, its last two digit=76So we take two cases:if (2^10)^even power then it always return 76 .if (2^10)^odd power then it always return 24 .Steps for finding last two digits\nFirstly, convert given number in to these formats if (2^10)^power. \nHere power will be odd or even according to the question.\nNow, check power will be odd or even.\nif power is odd then its value will be 24.\nif power is even then its value will be 76.\nExamplesExample1: Find last 2 digit of 2^453.Solution:Step 1:- conversion2^453 = (2^10)^45 * 2^3Step 2:- odd power so we take 24= 24 * 8= 192So, Last two non zero digits of 2^453 are 92.Example2: Find last 2 digits of 4^972.Solution:step 1:- conversion4^972 = (2^2)^972= 2^1944= (2^10)^194 * 2^4step 2:- even power so, we take 76= 76 * 16= 1216So, Last two non zero digits of 4^972 are 16.Example3: Find last 2 digits of 6^600.Solution:step 1:- conversion6^600 = (2)^600 * (3)^600= (2^10)^60 * ((3)^4)^150 {Apply case 2 in (3)^600}step 2:- (2^10)^60 has even power so, we take 76 as the last digitstep 3:- Solve ((3)^4)^150, we get 01 as the last digitstep 4:- last digit of (2^10)^60 i.e 76 multiply with the last digit of ((3)^4)^150 i.e 01step 5:- i.e 76 * 01 = 76So, Last two non zero of 6^600 is 76.Example4: Find last 2 digits of 8^330.Solution:step 1:- conversion8^33 = (2^3)^110= (2)^330step 2:- (2^10)^33 has odd power so, we take 24 as the last digitSo, Last two non zero digits of 8^330 are 24.Case 4: when x ends with 5For finding the last two digit of a number, when the number ends with 5 then we have to follow the table which is given below.Example1: Find last 2 digit of 25^25.Solution:first digit of number is 2 i.e evenLast digit of a power is 5 i.e oddNow, even-odd combination gives last digit as a 25So, the last two non zero digits of 25^25 are 25.Example2: Find last 2 digit of 25^222.Solution:first digit of number is 2 i.e evenLast digit of a power is 2 i.e evenNow, even-even combination gives last digit as a 25So, the last two non zero digits of 25^222 are 25.Example3: Find last 2 digit of 165^222.Solution:first digit of number is 1 i.e oddLast digit of a power is 2 i.e evenNow, odd-even combination gives last digit as a 25So, the last two non zero digits of 165^222 are 25.Example4: Find last 2 digit of 165^221.Solution:first digit of number is 1 i.e oddLast digit of a power is 1 i.e oddNow, odd-odd combination gives last digit as a 75So, the last two non zero digits of 165^221 are 75.Case 5: when x ends with 0For finding the last two digit of a number, when the number ends with 0 then we have to check next digit and according to the digit calculate the last digit.Example: Find last 2 digit of 150^221.Solution:150 last digit is 0 so we check next digit i.e 5 and apply case 4first digit of number is 1 i.e oddLast digit of a power is 1 i.e oddNow, odd-odd combination gives last digit as a 75So, the last two non zero digits of 165^221 is 75." }, { "code": null, "e": 31247, "s": 30994, "text": "Case 1: when x ends with 1For finding the last two digit of a number, when the number ends with 1 then we have to do following steps shown as in the figure.Example: 21^48So, Last two digit of 21^48 is 81.Example: 31^35So, Last two digit of 31^35 is 51." }, { "code": null, "e": 31378, "s": 31247, "text": "For finding the last two digit of a number, when the number ends with 1 then we have to do following steps shown as in the figure." }, { "code": null, "e": 31393, "s": 31378, "text": "Example: 21^48" }, { "code": null, "e": 31428, "s": 31393, "text": "So, Last two digit of 21^48 is 81." }, { "code": null, "e": 31443, "s": 31428, "text": "Example: 31^35" }, { "code": null, "e": 31478, "s": 31443, "text": "So, Last two digit of 31^35 is 51." }, { "code": null, "e": 32908, "s": 31478, "text": "Case 2: when x ends with 3, 7, 9For finding the last two digit of a number, when the number ends with 3, 7, 9 then we have to apply cyclicity concept to convert the last digit as a 1.cyclicity of 3:3^1 = 33^2 = 93^3 = 73^4 = 1cyclicity of 7:7^1 = 77^2 = 97^3 = 37^4 = 1cyclicity of 9:9^1 = 99^2 = 1Example1: 23^34Solution:Last digit of 23^34 is 3 so, we use cyclicity of 3 .3^4 gives 1 so, we take 23^4((23)^4)^8 * (23)^2last two digit of (23)^4) is 41, so we take (41)^8 and solve according to the given diagram.So last digit of (41)^8 is 21 .solve (23)^2, the last digit of (23)^2 is 29.Now multiply last digit of (41)^8 i.e 21 with the last digit of (23)^2 i.e 29i.e 21 * 29 = 609So, Last two non zero digit of 23^34 is 09.Example2: 37^45Solution:Last digit of 37^45 is 7 so, we use cyclicity of 7 .7^4 gives 1 so, we take 37^4((37)^4)^11 * (37)^1last two digit of (37)^4) is 61, so we take (61)^11 and solve according to the diagram.So last digit of (61)^11 is 61 .solve (37)^1, the last digit of (37)^1 is 37.Now multiply last digit of (61)^11 i.e 61 with the last digit of (37)^1 i.e 37i.e 61 * 37 = 2257So, Last two non zero digit of 37^45 is 57.Example3: 59^22Solution:Last digit of 59^22 is 9 so, we use cyclicity of 9 .9^2 gives 1 so, we take 59^2((59)^2)^11last two digit of (59)^2 is 81, so we take (81)^11 and solve according to the diagram.So last digit of (81)^11 is 81 .So, Last two non zero digit of 59^22 is 81." }, { "code": null, "e": 33060, "s": 32908, "text": "For finding the last two digit of a number, when the number ends with 3, 7, 9 then we have to apply cyclicity concept to convert the last digit as a 1." }, { "code": null, "e": 33076, "s": 33060, "text": "cyclicity of 3:" }, { "code": null, "e": 33105, "s": 33076, "text": "3^1 = 33^2 = 93^3 = 73^4 = 1" }, { "code": null, "e": 33121, "s": 33105, "text": "cyclicity of 7:" }, { "code": null, "e": 33150, "s": 33121, "text": "7^1 = 77^2 = 97^3 = 37^4 = 1" }, { "code": null, "e": 33166, "s": 33150, "text": "cyclicity of 9:" }, { "code": null, "e": 33181, "s": 33166, "text": "9^1 = 99^2 = 1" }, { "code": null, "e": 33206, "s": 33181, "text": "Example1: 23^34Solution:" }, { "code": null, "e": 33259, "s": 33206, "text": "Last digit of 23^34 is 3 so, we use cyclicity of 3 ." }, { "code": null, "e": 33288, "s": 33259, "text": "3^4 gives 1 so, we take 23^4" }, { "code": null, "e": 33308, "s": 33288, "text": "((23)^4)^8 * (23)^2" }, { "code": null, "e": 33401, "s": 33308, "text": "last two digit of (23)^4) is 41, so we take (41)^8 and solve according to the given diagram." }, { "code": null, "e": 33433, "s": 33401, "text": "So last digit of (41)^8 is 21 ." }, { "code": null, "e": 33479, "s": 33433, "text": "solve (23)^2, the last digit of (23)^2 is 29." }, { "code": null, "e": 33557, "s": 33479, "text": "Now multiply last digit of (41)^8 i.e 21 with the last digit of (23)^2 i.e 29" }, { "code": null, "e": 33575, "s": 33557, "text": "i.e 21 * 29 = 609" }, { "code": null, "e": 33619, "s": 33575, "text": "So, Last two non zero digit of 23^34 is 09." }, { "code": null, "e": 33644, "s": 33619, "text": "Example2: 37^45Solution:" }, { "code": null, "e": 33697, "s": 33644, "text": "Last digit of 37^45 is 7 so, we use cyclicity of 7 ." }, { "code": null, "e": 33726, "s": 33697, "text": "7^4 gives 1 so, we take 37^4" }, { "code": null, "e": 33747, "s": 33726, "text": "((37)^4)^11 * (37)^1" }, { "code": null, "e": 33835, "s": 33747, "text": "last two digit of (37)^4) is 61, so we take (61)^11 and solve according to the diagram." }, { "code": null, "e": 33868, "s": 33835, "text": "So last digit of (61)^11 is 61 ." }, { "code": null, "e": 33914, "s": 33868, "text": "solve (37)^1, the last digit of (37)^1 is 37." }, { "code": null, "e": 33993, "s": 33914, "text": "Now multiply last digit of (61)^11 i.e 61 with the last digit of (37)^1 i.e 37" }, { "code": null, "e": 34012, "s": 33993, "text": "i.e 61 * 37 = 2257" }, { "code": null, "e": 34056, "s": 34012, "text": "So, Last two non zero digit of 37^45 is 57." }, { "code": null, "e": 34081, "s": 34056, "text": "Example3: 59^22Solution:" }, { "code": null, "e": 34134, "s": 34081, "text": "Last digit of 59^22 is 9 so, we use cyclicity of 9 ." }, { "code": null, "e": 34163, "s": 34134, "text": "9^2 gives 1 so, we take 59^2" }, { "code": null, "e": 34175, "s": 34163, "text": "((59)^2)^11" }, { "code": null, "e": 34262, "s": 34175, "text": "last two digit of (59)^2 is 81, so we take (81)^11 and solve according to the diagram." }, { "code": null, "e": 34295, "s": 34262, "text": "So last digit of (81)^11 is 81 ." }, { "code": null, "e": 34339, "s": 34295, "text": "So, Last two non zero digit of 59^22 is 81." }, { "code": null, "e": 36071, "s": 34339, "text": "Case 3: when x ends with 2, 4, 6, 8For finding the last digit of a number ends with 2, 4, 6, 8; We use number 76 which is a type of magic number because its square, cube and etc contain last 2 digit numbers as itself i.e 76.Take an example :square of 76 = 5776, its last two digit =76cube of 76 = 438976, its last two digit=76So we take two cases:if (2^10)^even power then it always return 76 .if (2^10)^odd power then it always return 24 .Steps for finding last two digits\nFirstly, convert given number in to these formats if (2^10)^power. \nHere power will be odd or even according to the question.\nNow, check power will be odd or even.\nif power is odd then its value will be 24.\nif power is even then its value will be 76.\nExamplesExample1: Find last 2 digit of 2^453.Solution:Step 1:- conversion2^453 = (2^10)^45 * 2^3Step 2:- odd power so we take 24= 24 * 8= 192So, Last two non zero digits of 2^453 are 92.Example2: Find last 2 digits of 4^972.Solution:step 1:- conversion4^972 = (2^2)^972= 2^1944= (2^10)^194 * 2^4step 2:- even power so, we take 76= 76 * 16= 1216So, Last two non zero digits of 4^972 are 16.Example3: Find last 2 digits of 6^600.Solution:step 1:- conversion6^600 = (2)^600 * (3)^600= (2^10)^60 * ((3)^4)^150 {Apply case 2 in (3)^600}step 2:- (2^10)^60 has even power so, we take 76 as the last digitstep 3:- Solve ((3)^4)^150, we get 01 as the last digitstep 4:- last digit of (2^10)^60 i.e 76 multiply with the last digit of ((3)^4)^150 i.e 01step 5:- i.e 76 * 01 = 76So, Last two non zero of 6^600 is 76.Example4: Find last 2 digits of 8^330.Solution:step 1:- conversion8^33 = (2^3)^110= (2)^330step 2:- (2^10)^33 has odd power so, we take 24 as the last digitSo, Last two non zero digits of 8^330 are 24." }, { "code": null, "e": 36261, "s": 36071, "text": "For finding the last digit of a number ends with 2, 4, 6, 8; We use number 76 which is a type of magic number because its square, cube and etc contain last 2 digit numbers as itself i.e 76." }, { "code": null, "e": 36279, "s": 36261, "text": "Take an example :" }, { "code": null, "e": 36365, "s": 36279, "text": "square of 76 = 5776, its last two digit =76cube of 76 = 438976, its last two digit=76" }, { "code": null, "e": 36387, "s": 36365, "text": "So we take two cases:" }, { "code": null, "e": 36481, "s": 36387, "text": "if (2^10)^even power then it always return 76 .if (2^10)^odd power then it always return 24 ." }, { "code": null, "e": 36529, "s": 36481, "text": "if (2^10)^even power then it always return 76 ." }, { "code": null, "e": 36576, "s": 36529, "text": "if (2^10)^odd power then it always return 24 ." }, { "code": null, "e": 36610, "s": 36576, "text": "Steps for finding last two digits" }, { "code": null, "e": 36864, "s": 36610, "text": "\nFirstly, convert given number in to these formats if (2^10)^power. \nHere power will be odd or even according to the question.\nNow, check power will be odd or even.\nif power is odd then its value will be 24.\nif power is even then its value will be 76.\n" }, { "code": null, "e": 36992, "s": 36864, "text": "Firstly, convert given number in to these formats if (2^10)^power. \nHere power will be odd or even according to the question.\n" }, { "code": null, "e": 37031, "s": 36992, "text": "Now, check power will be odd or even.\n" }, { "code": null, "e": 37075, "s": 37031, "text": "if power is odd then its value will be 24.\n" }, { "code": null, "e": 37119, "s": 37075, "text": "if power is even then its value will be 76." }, { "code": null, "e": 37128, "s": 37119, "text": "Examples" }, { "code": null, "e": 37166, "s": 37128, "text": "Example1: Find last 2 digit of 2^453." }, { "code": null, "e": 37176, "s": 37166, "text": "Solution:" }, { "code": null, "e": 37219, "s": 37176, "text": "Step 1:- conversion2^453 = (2^10)^45 * 2^3" }, { "code": null, "e": 37265, "s": 37219, "text": "Step 2:- odd power so we take 24= 24 * 8= 192" }, { "code": null, "e": 37311, "s": 37265, "text": "So, Last two non zero digits of 2^453 are 92." }, { "code": null, "e": 37350, "s": 37311, "text": "Example2: Find last 2 digits of 4^972." }, { "code": null, "e": 37360, "s": 37350, "text": "Solution:" }, { "code": null, "e": 37423, "s": 37360, "text": "step 1:- conversion4^972 = (2^2)^972= 2^1944= (2^10)^194 * 2^4" }, { "code": null, "e": 37473, "s": 37423, "text": "step 2:- even power so, we take 76= 76 * 16= 1216" }, { "code": null, "e": 37519, "s": 37473, "text": "So, Last two non zero digits of 4^972 are 16." }, { "code": null, "e": 37558, "s": 37519, "text": "Example3: Find last 2 digits of 6^600." }, { "code": null, "e": 37568, "s": 37558, "text": "Solution:" }, { "code": null, "e": 37664, "s": 37568, "text": "step 1:- conversion6^600 = (2)^600 * (3)^600= (2^10)^60 * ((3)^4)^150 {Apply case 2 in (3)^600}" }, { "code": null, "e": 37731, "s": 37664, "text": "step 2:- (2^10)^60 has even power so, we take 76 as the last digit" }, { "code": null, "e": 37787, "s": 37731, "text": "step 3:- Solve ((3)^4)^150, we get 01 as the last digit" }, { "code": null, "e": 37878, "s": 37787, "text": "step 4:- last digit of (2^10)^60 i.e 76 multiply with the last digit of ((3)^4)^150 i.e 01" }, { "code": null, "e": 37904, "s": 37878, "text": "step 5:- i.e 76 * 01 = 76" }, { "code": null, "e": 37942, "s": 37904, "text": "So, Last two non zero of 6^600 is 76." }, { "code": null, "e": 37981, "s": 37942, "text": "Example4: Find last 2 digits of 8^330." }, { "code": null, "e": 37991, "s": 37981, "text": "Solution:" }, { "code": null, "e": 38036, "s": 37991, "text": "step 1:- conversion8^33 = (2^3)^110= (2)^330" }, { "code": null, "e": 38102, "s": 38036, "text": "step 2:- (2^10)^33 has odd power so, we take 24 as the last digit" }, { "code": null, "e": 38148, "s": 38102, "text": "So, Last two non zero digits of 8^330 are 24." }, { "code": null, "e": 39167, "s": 38148, "text": "Case 4: when x ends with 5For finding the last two digit of a number, when the number ends with 5 then we have to follow the table which is given below.Example1: Find last 2 digit of 25^25.Solution:first digit of number is 2 i.e evenLast digit of a power is 5 i.e oddNow, even-odd combination gives last digit as a 25So, the last two non zero digits of 25^25 are 25.Example2: Find last 2 digit of 25^222.Solution:first digit of number is 2 i.e evenLast digit of a power is 2 i.e evenNow, even-even combination gives last digit as a 25So, the last two non zero digits of 25^222 are 25.Example3: Find last 2 digit of 165^222.Solution:first digit of number is 1 i.e oddLast digit of a power is 2 i.e evenNow, odd-even combination gives last digit as a 25So, the last two non zero digits of 165^222 are 25.Example4: Find last 2 digit of 165^221.Solution:first digit of number is 1 i.e oddLast digit of a power is 1 i.e oddNow, odd-odd combination gives last digit as a 75So, the last two non zero digits of 165^221 are 75." }, { "code": null, "e": 39294, "s": 39167, "text": "For finding the last two digit of a number, when the number ends with 5 then we have to follow the table which is given below." }, { "code": null, "e": 39332, "s": 39294, "text": "Example1: Find last 2 digit of 25^25." }, { "code": null, "e": 39342, "s": 39332, "text": "Solution:" }, { "code": null, "e": 39378, "s": 39342, "text": "first digit of number is 2 i.e even" }, { "code": null, "e": 39413, "s": 39378, "text": "Last digit of a power is 5 i.e odd" }, { "code": null, "e": 39464, "s": 39413, "text": "Now, even-odd combination gives last digit as a 25" }, { "code": null, "e": 39514, "s": 39464, "text": "So, the last two non zero digits of 25^25 are 25." }, { "code": null, "e": 39553, "s": 39514, "text": "Example2: Find last 2 digit of 25^222." }, { "code": null, "e": 39563, "s": 39553, "text": "Solution:" }, { "code": null, "e": 39599, "s": 39563, "text": "first digit of number is 2 i.e even" }, { "code": null, "e": 39635, "s": 39599, "text": "Last digit of a power is 2 i.e even" }, { "code": null, "e": 39687, "s": 39635, "text": "Now, even-even combination gives last digit as a 25" }, { "code": null, "e": 39738, "s": 39687, "text": "So, the last two non zero digits of 25^222 are 25." }, { "code": null, "e": 39778, "s": 39738, "text": "Example3: Find last 2 digit of 165^222." }, { "code": null, "e": 39788, "s": 39778, "text": "Solution:" }, { "code": null, "e": 39823, "s": 39788, "text": "first digit of number is 1 i.e odd" }, { "code": null, "e": 39859, "s": 39823, "text": "Last digit of a power is 2 i.e even" }, { "code": null, "e": 39910, "s": 39859, "text": "Now, odd-even combination gives last digit as a 25" }, { "code": null, "e": 39962, "s": 39910, "text": "So, the last two non zero digits of 165^222 are 25." }, { "code": null, "e": 40002, "s": 39962, "text": "Example4: Find last 2 digit of 165^221." }, { "code": null, "e": 40012, "s": 40002, "text": "Solution:" }, { "code": null, "e": 40047, "s": 40012, "text": "first digit of number is 1 i.e odd" }, { "code": null, "e": 40082, "s": 40047, "text": "Last digit of a power is 1 i.e odd" }, { "code": null, "e": 40132, "s": 40082, "text": "Now, odd-odd combination gives last digit as a 75" }, { "code": null, "e": 40184, "s": 40132, "text": "So, the last two non zero digits of 165^221 are 75." }, { "code": null, "e": 40647, "s": 40184, "text": "Case 5: when x ends with 0For finding the last two digit of a number, when the number ends with 0 then we have to check next digit and according to the digit calculate the last digit.Example: Find last 2 digit of 150^221.Solution:150 last digit is 0 so we check next digit i.e 5 and apply case 4first digit of number is 1 i.e oddLast digit of a power is 1 i.e oddNow, odd-odd combination gives last digit as a 75So, the last two non zero digits of 165^221 is 75." }, { "code": null, "e": 40805, "s": 40647, "text": "For finding the last two digit of a number, when the number ends with 0 then we have to check next digit and according to the digit calculate the last digit." }, { "code": null, "e": 40844, "s": 40805, "text": "Example: Find last 2 digit of 150^221." }, { "code": null, "e": 40854, "s": 40844, "text": "Solution:" }, { "code": null, "e": 40920, "s": 40854, "text": "150 last digit is 0 so we check next digit i.e 5 and apply case 4" }, { "code": null, "e": 40955, "s": 40920, "text": "first digit of number is 1 i.e odd" }, { "code": null, "e": 40990, "s": 40955, "text": "Last digit of a power is 1 i.e odd" }, { "code": null, "e": 41040, "s": 40990, "text": "Now, odd-odd combination gives last digit as a 75" }, { "code": null, "e": 41091, "s": 41040, "text": "So, the last two non zero digits of 165^221 is 75." }, { "code": null, "e": 41107, "s": 41091, "text": "harshitSingh_11" }, { "code": null, "e": 41121, "s": 41107, "text": "number-digits" }, { "code": null, "e": 41130, "s": 41121, "text": "Aptitude" }, { "code": null, "e": 41143, "s": 41130, "text": "Mathematical" }, { "code": null, "e": 41151, "s": 41143, "text": "Puzzles" }, { "code": null, "e": 41164, "s": 41151, "text": "Mathematical" }, { "code": null, "e": 41172, "s": 41164, "text": "Puzzles" }, { "code": null, "e": 41270, "s": 41172, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41337, "s": 41270, "text": "Puzzle | How much money did the man have before entering the bank?" }, { "code": null, "e": 41375, "s": 41337, "text": "Aptitude | GATE CS 1998 | Question 49" }, { "code": null, "e": 41421, "s": 41375, "text": "Aptitude | Arithmetic Aptitude 4 | Question 3" }, { "code": null, "e": 41459, "s": 41421, "text": "Order and Ranking Questions & Answers" }, { "code": null, "e": 41527, "s": 41459, "text": "Puzzle | Splitting a Cake with a Missing Piece in two equal portion" }, { "code": null, "e": 41557, "s": 41527, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 41617, "s": 41557, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 41632, "s": 41617, "text": "C++ Data Types" }, { "code": null, "e": 41675, "s": 41632, "text": "Set in C++ Standard Template Library (STL)" } ]
Byte equals() method in Java with examples - GeeksforGeeks
05 Dec, 2018 The equals() method of Byte class is a built in method in Java which is used to compare the equality given Object with the instance of Byte invoking the equals() method. Syntax ByteObject.equals(Object a) Parameters: It takes an Object type object a as input which is to be compared with the instance of the Byte object calling the equals method. Return Value: It return an boolean value. It returns true if the value of ‘a’ is equal to the value of ByteObject. Below is the implementation of equals() method in Java: Example 1: // Java code to demonstrate// Byte equals() method class GFG { public static void main(String[] args) { // creating a Byte object Byte a = new Byte("20"); // creating a Byte object Byte b = new Byte("20"); // equals method in Byte class boolean output = a.equals(b); // Printing the output System.out.println("Does " + a + " equals " + b + " : " + output); }} Does 20 equals 20 : true Example 2: // Java code to demonstrate// Byte equals() method class GFG { public static void main(String[] args) { // creating a Byte object Byte a = new Byte("2"); // creating a Byte object Byte b = new Byte("20"); // equals method in Byte class boolean output = a.equals(b); // Printing the output System.out.println("Does " + a + " equals " + b + " : " + output); }} Does 2 equals 20 : false Java - util package Java-Byte Java-Functions java-lang-reflect-package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java
[ { "code": null, "e": 26175, "s": 26147, "text": "\n05 Dec, 2018" }, { "code": null, "e": 26345, "s": 26175, "text": "The equals() method of Byte class is a built in method in Java which is used to compare the equality given Object with the instance of Byte invoking the equals() method." }, { "code": null, "e": 26352, "s": 26345, "text": "Syntax" }, { "code": null, "e": 26380, "s": 26352, "text": "ByteObject.equals(Object a)" }, { "code": null, "e": 26522, "s": 26380, "text": "Parameters: It takes an Object type object a as input which is to be compared with the instance of the Byte object calling the equals method." }, { "code": null, "e": 26637, "s": 26522, "text": "Return Value: It return an boolean value. It returns true if the value of ‘a’ is equal to the value of ByteObject." }, { "code": null, "e": 26693, "s": 26637, "text": "Below is the implementation of equals() method in Java:" }, { "code": null, "e": 26704, "s": 26693, "text": "Example 1:" }, { "code": "// Java code to demonstrate// Byte equals() method class GFG { public static void main(String[] args) { // creating a Byte object Byte a = new Byte(\"20\"); // creating a Byte object Byte b = new Byte(\"20\"); // equals method in Byte class boolean output = a.equals(b); // Printing the output System.out.println(\"Does \" + a + \" equals \" + b + \" : \" + output); }}", "e": 27164, "s": 26704, "text": null }, { "code": null, "e": 27190, "s": 27164, "text": "Does 20 equals 20 : true\n" }, { "code": null, "e": 27201, "s": 27190, "text": "Example 2:" }, { "code": "// Java code to demonstrate// Byte equals() method class GFG { public static void main(String[] args) { // creating a Byte object Byte a = new Byte(\"2\"); // creating a Byte object Byte b = new Byte(\"20\"); // equals method in Byte class boolean output = a.equals(b); // Printing the output System.out.println(\"Does \" + a + \" equals \" + b + \" : \" + output); }}", "e": 27660, "s": 27201, "text": null }, { "code": null, "e": 27686, "s": 27660, "text": "Does 2 equals 20 : false\n" }, { "code": null, "e": 27706, "s": 27686, "text": "Java - util package" }, { "code": null, "e": 27716, "s": 27706, "text": "Java-Byte" }, { "code": null, "e": 27731, "s": 27716, "text": "Java-Functions" }, { "code": null, "e": 27757, "s": 27731, "text": "java-lang-reflect-package" }, { "code": null, "e": 27762, "s": 27757, "text": "Java" }, { "code": null, "e": 27767, "s": 27762, "text": "Java" }, { "code": null, "e": 27865, "s": 27767, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27916, "s": 27865, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27946, "s": 27916, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27961, "s": 27946, "text": "Stream In Java" }, { "code": null, "e": 27980, "s": 27961, "text": "Interfaces in Java" }, { "code": null, "e": 28011, "s": 27980, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28029, "s": 28011, "text": "ArrayList in Java" }, { "code": null, "e": 28061, "s": 28029, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28081, "s": 28061, "text": "Stack Class in Java" }, { "code": null, "e": 28113, "s": 28081, "text": "Multidimensional Arrays in Java" } ]
Node.js zlib.unzip() Method - GeeksforGeeks
12 Oct, 2021 The zlib.unzip() method is an inbuilt application programming interface of the Zlib module which is used to decompress a chunk of data. Syntax: zlib.unzip( buffer, options, callback ) Parameters: This method accepts three parameters as mentioned above and described below: buffer: It can be of type Buffer, TypedArray, DataView, ArrayBuffer, and string. options: It is an optional parameter that holds the zlib options. callback: It holds the callback function. Return Value: It returns the chunk of data after decompression. Below examples illustrate the use of zlib.unzip() method in Node.js: Example 1: // Node.js program to demonstrate the // unzip() method // Including zlib moduleconst zlib = require("zlib"); // Declaring input and assigning// it a value stringvar input = "GfG"; // Calling gzip methodzlib.gzip(input, (err, buffer) => { // Calling unzip method zlib.unzip(buffer, (err, buffer) => { console.log(buffer.toString('utf8')); }); }); console.log("Data Decompressed..."); Output: Data Decompressed... GfG Example 2: // Node.js program to demonstrate the // unzip() method // Including zlib moduleconst zlib = require("zlib"); // Declaring input and assigning// it a value stringvar input = "GfG"; // Calling gzip methodzlib.gzip(input, (err, buffer) => { // Calling unzip method zlib.unzip(buffer, (err, buffer) => { console.log(buffer.toString('base64')); }); }); console.log("Data Decompressed..."); Output: Data Decompressed... R2ZH Reference: https://nodejs.org/api/zlib.html#zlib_zlib_unzip_buffer_options_callback Node.js-Zlib-module Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.writeFile() Method Node.js fs.readFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js How to use an ES6 import in Node.js? Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26095, "s": 26067, "text": "\n12 Oct, 2021" }, { "code": null, "e": 26231, "s": 26095, "text": "The zlib.unzip() method is an inbuilt application programming interface of the Zlib module which is used to decompress a chunk of data." }, { "code": null, "e": 26239, "s": 26231, "text": "Syntax:" }, { "code": null, "e": 26279, "s": 26239, "text": "zlib.unzip( buffer, options, callback )" }, { "code": null, "e": 26368, "s": 26279, "text": "Parameters: This method accepts three parameters as mentioned above and described below:" }, { "code": null, "e": 26449, "s": 26368, "text": "buffer: It can be of type Buffer, TypedArray, DataView, ArrayBuffer, and string." }, { "code": null, "e": 26515, "s": 26449, "text": "options: It is an optional parameter that holds the zlib options." }, { "code": null, "e": 26557, "s": 26515, "text": "callback: It holds the callback function." }, { "code": null, "e": 26621, "s": 26557, "text": "Return Value: It returns the chunk of data after decompression." }, { "code": null, "e": 26690, "s": 26621, "text": "Below examples illustrate the use of zlib.unzip() method in Node.js:" }, { "code": null, "e": 26701, "s": 26690, "text": "Example 1:" }, { "code": "// Node.js program to demonstrate the // unzip() method // Including zlib moduleconst zlib = require(\"zlib\"); // Declaring input and assigning// it a value stringvar input = \"GfG\"; // Calling gzip methodzlib.gzip(input, (err, buffer) => { // Calling unzip method zlib.unzip(buffer, (err, buffer) => { console.log(buffer.toString('utf8')); }); }); console.log(\"Data Decompressed...\");", "e": 27110, "s": 26701, "text": null }, { "code": null, "e": 27118, "s": 27110, "text": "Output:" }, { "code": null, "e": 27144, "s": 27118, "text": "Data Decompressed...\nGfG\n" }, { "code": null, "e": 27155, "s": 27144, "text": "Example 2:" }, { "code": "// Node.js program to demonstrate the // unzip() method // Including zlib moduleconst zlib = require(\"zlib\"); // Declaring input and assigning// it a value stringvar input = \"GfG\"; // Calling gzip methodzlib.gzip(input, (err, buffer) => { // Calling unzip method zlib.unzip(buffer, (err, buffer) => { console.log(buffer.toString('base64')); }); }); console.log(\"Data Decompressed...\");", "e": 27566, "s": 27155, "text": null }, { "code": null, "e": 27574, "s": 27566, "text": "Output:" }, { "code": null, "e": 27601, "s": 27574, "text": "Data Decompressed...\nR2ZH\n" }, { "code": null, "e": 27685, "s": 27601, "text": "Reference: https://nodejs.org/api/zlib.html#zlib_zlib_unzip_buffer_options_callback" }, { "code": null, "e": 27705, "s": 27685, "text": "Node.js-Zlib-module" }, { "code": null, "e": 27713, "s": 27705, "text": "Node.js" }, { "code": null, "e": 27730, "s": 27713, "text": "Web Technologies" }, { "code": null, "e": 27828, "s": 27730, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27858, "s": 27828, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 27887, "s": 27858, "text": "Node.js fs.readFile() Method" }, { "code": null, "e": 27944, "s": 27887, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 27998, "s": 27944, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 28035, "s": 27998, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 28075, "s": 28035, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28120, "s": 28075, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28163, "s": 28120, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28225, "s": 28163, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Javascript Program For Partitioning A Linked List Around A Given Value And Keeping The Original Order - GeeksforGeeks
11 Jan, 2022 Given a linked list and a value x, partition it such that all nodes less than x come first, then all nodes with a value equal to x, and finally nodes with a value greater than or equal to x. The original relative order of the nodes in each of the three partitions should be preserved. The partition must work in place.Examples: Input: 1->4->3->2->5->2->3, x = 3 Output: 1->2->2->3->3->4->5 Input: 1->4->2->10 x = 3 Output: 1->2->4->10 Input: 10->4->20->10->3 x = 3 Output: 3->10->4->20->10 To solve this problem we can use partition method of Quick Sort but this would not preserve the original relative order of the nodes in each of the two partitions.Below is the algorithm to solve this problem : Initialize first and last nodes of below three linked lists as NULL.Linked list of values smaller than x.Linked list of values equal to x.Linked list of values greater than x.Now iterate through the original linked list. If a node’s value is less than x then append it at the end of the smaller list. If the value is equal to x, then at the end of the equal list. And if a value is greater, then at the end of the greater list.Now concatenate three lists. Initialize first and last nodes of below three linked lists as NULL.Linked list of values smaller than x.Linked list of values equal to x.Linked list of values greater than x. Linked list of values smaller than x. Linked list of values equal to x. Linked list of values greater than x. Now iterate through the original linked list. If a node’s value is less than x then append it at the end of the smaller list. If the value is equal to x, then at the end of the equal list. And if a value is greater, then at the end of the greater list. Now concatenate three lists. Below is the implementation of the above idea. Javascript <script>// Javascript program to partition a // linked list around a given value. // Link list Node class Node { constructor() { this.data = 0; this.next = null; }} // A utility function to create // a new nodefunction newNode(data) { var new_node = new Node(); new_node.data = data; new_node.next = null; return new_node;} // Function to make two separate lists // and return head after concatenatingfunction partition(head, x) { /* Let us initialize first and last nodes of three linked lists 1) Linked list of values smaller than x. 2) Linked list of values equal to x. 3) Linked list of values greater than x. */ var smallerHead = null, smallerLast = null; var greaterLast = null, greaterHead = null; var equalHead = null, equalLast = null; // Now iterate original list and // connect nodes of appropriate // linked lists. while (head != null) { // If current node is equal to x, // append it to the list of x values if (head.data == x) { if (equalHead == null) equalHead = equalLast = head; else { equalLast.next = head; equalLast = equalLast.next; } } // If current node is less than X, // append it to the list of smaller // values else if (head.data < x) { if (smallerHead == null) smallerLast = smallerHead = head; else { smallerLast.next = head; smallerLast = head; } } // Append to the list of greater values else { if (greaterHead == null) greaterLast = greaterHead = head; else { greaterLast.next = head; greaterLast = head; } } head = head.next; } // Fix end of greater linked list to NULL // if this list has some nodes if (greaterLast != null) greaterLast.next = null; // Connect three lists // If smaller list is empty if (smallerHead == null) { if (equalHead == null) return greaterHead; equalLast.next = greaterHead; return equalHead; } // If smaller list is not empty // and equal list is empty if (equalHead == null) { smallerLast.next = greaterHead; return smallerHead; } // If both smaller and equal list // are non-empty smallerLast.next = equalHead; equalLast.next = greaterHead; return smallerHead;} // Function to print linked list function printList(head) { var temp = head; while (temp != null) { document.write(temp.data + " "); temp = temp.next; }} // Driver code// Start with the empty list var head = newNode(10);head.next = newNode(4);head.next.next = newNode(5);head.next.next.next = newNode(30);head.next.next.next.next = newNode(2);head.next.next.next.next.next = newNode(50); var x = 3;head = partition(head, x);printList(head);// This code is contributed by aashish1995 </script> Output: 2 10 4 5 30 50 Please refer complete article on Partitioning a linked list around a given value and keeping the original order for more details! arorakashish0911 Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Circular Linked List | Set 2 (Traversal) Swap nodes in a linked list without swapping data Program to implement Singly Linked List in C++ using class Circular Singly Linked List | Insertion Given a linked list which is sorted, how will you insert in sorted way Delete a node in a Doubly Linked List Real-time application of Data Structures Linked List Implementation in C# Insert a node at a specific position in a linked list Move last element to front of a given Linked List
[ { "code": null, "e": 26179, "s": 26151, "text": "\n11 Jan, 2022" }, { "code": null, "e": 26507, "s": 26179, "text": "Given a linked list and a value x, partition it such that all nodes less than x come first, then all nodes with a value equal to x, and finally nodes with a value greater than or equal to x. The original relative order of the nodes in each of the three partitions should be preserved. The partition must work in place.Examples:" }, { "code": null, "e": 26699, "s": 26507, "text": "Input: 1->4->3->2->5->2->3, \n x = 3\nOutput: 1->2->2->3->3->4->5\n\nInput: 1->4->2->10 \n x = 3\nOutput: 1->2->4->10\n\nInput: 10->4->20->10->3 \n x = 3\nOutput: 3->10->4->20->10 " }, { "code": null, "e": 26909, "s": 26699, "text": "To solve this problem we can use partition method of Quick Sort but this would not preserve the original relative order of the nodes in each of the two partitions.Below is the algorithm to solve this problem :" }, { "code": null, "e": 27365, "s": 26909, "text": "Initialize first and last nodes of below three linked lists as NULL.Linked list of values smaller than x.Linked list of values equal to x.Linked list of values greater than x.Now iterate through the original linked list. If a node’s value is less than x then append it at the end of the smaller list. If the value is equal to x, then at the end of the equal list. And if a value is greater, then at the end of the greater list.Now concatenate three lists." }, { "code": null, "e": 27541, "s": 27365, "text": "Initialize first and last nodes of below three linked lists as NULL.Linked list of values smaller than x.Linked list of values equal to x.Linked list of values greater than x." }, { "code": null, "e": 27579, "s": 27541, "text": "Linked list of values smaller than x." }, { "code": null, "e": 27613, "s": 27579, "text": "Linked list of values equal to x." }, { "code": null, "e": 27651, "s": 27613, "text": "Linked list of values greater than x." }, { "code": null, "e": 27904, "s": 27651, "text": "Now iterate through the original linked list. If a node’s value is less than x then append it at the end of the smaller list. If the value is equal to x, then at the end of the equal list. And if a value is greater, then at the end of the greater list." }, { "code": null, "e": 27933, "s": 27904, "text": "Now concatenate three lists." }, { "code": null, "e": 27980, "s": 27933, "text": "Below is the implementation of the above idea." }, { "code": null, "e": 27991, "s": 27980, "text": "Javascript" }, { "code": "<script>// Javascript program to partition a // linked list around a given value. // Link list Node class Node { constructor() { this.data = 0; this.next = null; }} // A utility function to create // a new nodefunction newNode(data) { var new_node = new Node(); new_node.data = data; new_node.next = null; return new_node;} // Function to make two separate lists // and return head after concatenatingfunction partition(head, x) { /* Let us initialize first and last nodes of three linked lists 1) Linked list of values smaller than x. 2) Linked list of values equal to x. 3) Linked list of values greater than x. */ var smallerHead = null, smallerLast = null; var greaterLast = null, greaterHead = null; var equalHead = null, equalLast = null; // Now iterate original list and // connect nodes of appropriate // linked lists. while (head != null) { // If current node is equal to x, // append it to the list of x values if (head.data == x) { if (equalHead == null) equalHead = equalLast = head; else { equalLast.next = head; equalLast = equalLast.next; } } // If current node is less than X, // append it to the list of smaller // values else if (head.data < x) { if (smallerHead == null) smallerLast = smallerHead = head; else { smallerLast.next = head; smallerLast = head; } } // Append to the list of greater values else { if (greaterHead == null) greaterLast = greaterHead = head; else { greaterLast.next = head; greaterLast = head; } } head = head.next; } // Fix end of greater linked list to NULL // if this list has some nodes if (greaterLast != null) greaterLast.next = null; // Connect three lists // If smaller list is empty if (smallerHead == null) { if (equalHead == null) return greaterHead; equalLast.next = greaterHead; return equalHead; } // If smaller list is not empty // and equal list is empty if (equalHead == null) { smallerLast.next = greaterHead; return smallerHead; } // If both smaller and equal list // are non-empty smallerLast.next = equalHead; equalLast.next = greaterHead; return smallerHead;} // Function to print linked list function printList(head) { var temp = head; while (temp != null) { document.write(temp.data + \" \"); temp = temp.next; }} // Driver code// Start with the empty list var head = newNode(10);head.next = newNode(4);head.next.next = newNode(5);head.next.next.next = newNode(30);head.next.next.next.next = newNode(2);head.next.next.next.next.next = newNode(50); var x = 3;head = partition(head, x);printList(head);// This code is contributed by aashish1995 </script>", "e": 31231, "s": 27991, "text": null }, { "code": null, "e": 31241, "s": 31231, "text": "Output: " }, { "code": null, "e": 31256, "s": 31241, "text": "2 10 4 5 30 50" }, { "code": null, "e": 31386, "s": 31256, "text": "Please refer complete article on Partitioning a linked list around a given value and keeping the original order for more details!" }, { "code": null, "e": 31403, "s": 31386, "text": "arorakashish0911" }, { "code": null, "e": 31415, "s": 31403, "text": "Linked List" }, { "code": null, "e": 31427, "s": 31415, "text": "Linked List" }, { "code": null, "e": 31525, "s": 31427, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31566, "s": 31525, "text": "Circular Linked List | Set 2 (Traversal)" }, { "code": null, "e": 31616, "s": 31566, "text": "Swap nodes in a linked list without swapping data" }, { "code": null, "e": 31675, "s": 31616, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 31715, "s": 31675, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 31786, "s": 31715, "text": "Given a linked list which is sorted, how will you insert in sorted way" }, { "code": null, "e": 31824, "s": 31786, "text": "Delete a node in a Doubly Linked List" }, { "code": null, "e": 31865, "s": 31824, "text": "Real-time application of Data Structures" }, { "code": null, "e": 31898, "s": 31865, "text": "Linked List Implementation in C#" }, { "code": null, "e": 31952, "s": 31898, "text": "Insert a node at a specific position in a linked list" } ]
LocalDate now() Method in Java with Examples - GeeksforGeeks
21 Jan, 2019 In LocalDate class, there are three types of now() method depending upon the parameters passed to it. now() method of a LocalDate class used to obtain the current date from the system clock in the default time-zone.This method will return LocalDate based on system clock with default time-zone to obtain the current date. Syntax: public static LocalDate now() Parameters: This method accepts no parameter. Return value: This method returns the current date using the system clock and default time-zone. Below programs illustrate the now() method:Program 1: // Java program to demonstrate// LocalDate.now() method import java.time.*; public class GFG { public static void main(String[] args) { // create an LocalDate object LocalDate lt = LocalDate.now(); // print result System.out.println("LocalDate : " + lt); }} LocalDate : 2019-01-21 now(Clock clock) method of a LocalDate class used to return the current date based on the specified clock passed as parameter. Syntax: public static LocalDate now(Clock clock) Parameters: This method accepts clock as parameter which is the clock to use. Return value: This method returns the current date. Below programs illustrate the now() method:Program 1: // Java program to demonstrate// LocalDate.now() method import java.time.*; public class GFG { public static void main(String[] args) { // create a clock Clock cl = Clock.systemUTC(); // create an LocalDate object using now(Clock) LocalDate lt = LocalDate.now(cl); // print result System.out.println("LocalDate : " + lt); }} LocalDate : 2019-01-21 now(ZoneId zone) method of a LocalDate class used to return the current date from system clock in the specified time-zone passed as parameter.Specifying the time-zone avoids dependence on the default time-zone. Syntax: public static LocalDate now(ZoneId zone) Parameters: This method accepts zone as parameter which is the zone to use. Return value: This method returns the current date-time. Below programs illustrate the now() method:Program 1: // Java program to demonstrate// LocalDate.now() method import java.time.*; public class GFG { public static void main(String[] args) { // create a clock ZoneId zid = ZoneId.of("Europe/Paris"); // create an LocalDate object using now(zoneId) LocalDate lt = LocalDate.now(zid); // print result System.out.println("LocalDate : " + lt); }} LocalDate : 2019-01-21 References:https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#now()https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#now(java.time.Clock)https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#now(java.time.ZoneId) Java-Functions Java-LocalDate Java-time package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Interfaces in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java Multithreading in Java Collections in Java
[ { "code": null, "e": 25427, "s": 25399, "text": "\n21 Jan, 2019" }, { "code": null, "e": 25529, "s": 25427, "text": "In LocalDate class, there are three types of now() method depending upon the parameters passed to it." }, { "code": null, "e": 25749, "s": 25529, "text": "now() method of a LocalDate class used to obtain the current date from the system clock in the default time-zone.This method will return LocalDate based on system clock with default time-zone to obtain the current date." }, { "code": null, "e": 25757, "s": 25749, "text": "Syntax:" }, { "code": null, "e": 25788, "s": 25757, "text": "public static LocalDate now()\n" }, { "code": null, "e": 25834, "s": 25788, "text": "Parameters: This method accepts no parameter." }, { "code": null, "e": 25931, "s": 25834, "text": "Return value: This method returns the current date using the system clock and default time-zone." }, { "code": null, "e": 25985, "s": 25931, "text": "Below programs illustrate the now() method:Program 1:" }, { "code": "// Java program to demonstrate// LocalDate.now() method import java.time.*; public class GFG { public static void main(String[] args) { // create an LocalDate object LocalDate lt = LocalDate.now(); // print result System.out.println(\"LocalDate : \" + lt); }}", "e": 26323, "s": 25985, "text": null }, { "code": null, "e": 26347, "s": 26323, "text": "LocalDate : 2019-01-21\n" }, { "code": null, "e": 26474, "s": 26347, "text": "now(Clock clock) method of a LocalDate class used to return the current date based on the specified clock passed as parameter." }, { "code": null, "e": 26482, "s": 26474, "text": "Syntax:" }, { "code": null, "e": 26524, "s": 26482, "text": "public static LocalDate now(Clock clock)\n" }, { "code": null, "e": 26602, "s": 26524, "text": "Parameters: This method accepts clock as parameter which is the clock to use." }, { "code": null, "e": 26654, "s": 26602, "text": "Return value: This method returns the current date." }, { "code": null, "e": 26708, "s": 26654, "text": "Below programs illustrate the now() method:Program 1:" }, { "code": "// Java program to demonstrate// LocalDate.now() method import java.time.*; public class GFG { public static void main(String[] args) { // create a clock Clock cl = Clock.systemUTC(); // create an LocalDate object using now(Clock) LocalDate lt = LocalDate.now(cl); // print result System.out.println(\"LocalDate : \" + lt); }}", "e": 27129, "s": 26708, "text": null }, { "code": null, "e": 27153, "s": 27129, "text": "LocalDate : 2019-01-21\n" }, { "code": null, "e": 27364, "s": 27153, "text": "now(ZoneId zone) method of a LocalDate class used to return the current date from system clock in the specified time-zone passed as parameter.Specifying the time-zone avoids dependence on the default time-zone." }, { "code": null, "e": 27372, "s": 27364, "text": "Syntax:" }, { "code": null, "e": 27414, "s": 27372, "text": "public static LocalDate now(ZoneId zone)\n" }, { "code": null, "e": 27490, "s": 27414, "text": "Parameters: This method accepts zone as parameter which is the zone to use." }, { "code": null, "e": 27547, "s": 27490, "text": "Return value: This method returns the current date-time." }, { "code": null, "e": 27601, "s": 27547, "text": "Below programs illustrate the now() method:Program 1:" }, { "code": "// Java program to demonstrate// LocalDate.now() method import java.time.*; public class GFG { public static void main(String[] args) { // create a clock ZoneId zid = ZoneId.of(\"Europe/Paris\"); // create an LocalDate object using now(zoneId) LocalDate lt = LocalDate.now(zid); // print result System.out.println(\"LocalDate : \" + lt); }}", "e": 28034, "s": 27601, "text": null }, { "code": null, "e": 28058, "s": 28034, "text": "LocalDate : 2019-01-21\n" }, { "code": null, "e": 28320, "s": 28058, "text": "References:https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#now()https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#now(java.time.Clock)https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#now(java.time.ZoneId)" }, { "code": null, "e": 28335, "s": 28320, "text": "Java-Functions" }, { "code": null, "e": 28350, "s": 28335, "text": "Java-LocalDate" }, { "code": null, "e": 28368, "s": 28350, "text": "Java-time package" }, { "code": null, "e": 28373, "s": 28368, "text": "Java" }, { "code": null, "e": 28378, "s": 28373, "text": "Java" }, { "code": null, "e": 28476, "s": 28378, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28491, "s": 28476, "text": "Stream In Java" }, { "code": null, "e": 28510, "s": 28491, "text": "Interfaces in Java" }, { "code": null, "e": 28528, "s": 28510, "text": "ArrayList in Java" }, { "code": null, "e": 28560, "s": 28528, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28580, "s": 28560, "text": "Stack Class in Java" }, { "code": null, "e": 28604, "s": 28580, "text": "Singleton Class in Java" }, { "code": null, "e": 28636, "s": 28604, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 28648, "s": 28636, "text": "Set in Java" }, { "code": null, "e": 28671, "s": 28648, "text": "Multithreading in Java" } ]
Check if a circle lies inside another circle or not - GeeksforGeeks
22 Oct, 2021 Given two circles with radii and centres given. The task is to check whether the smaller circle lies inside the bigger circle or not. Examples: Input: x1 = 10, y1 = 8, x2 = 1, y2 = 2, r1 = 30, r2 = 10 Output: The smaller circle lies completely inside the bigger circle without touching each other at a point of circumference. Input :x1 = 7, y1 = 8;x2 = 3, y2 = 5;r1 = 30, r2 = 25 Output :The smaller circle lies completely inside the bigger circle with touching each other at a point of circumference. Approach: Here three cases can come, The smaller circle lies completely inside the bigger circle without touching each other at a point of circumference. If this case happens, the sum of the distance between the centres and smaller radius is lesser than the bigger radius, then obviously the smaller circle lies completely inside the circle, without touching the circumference. The smaller circle lies completely inside the bigger circle with touching each other at a point of the circumference. If this case happens, the sum of the distance between the centres and smaller radius is equal to the bigger radius, then obviously the smaller circle lies completely inside the circle, with touching the circumference. The smaller does not lies inside the bigger circle completely.If this case happens, then sum of the distance between the centers and smaller radius is greater than the bigger radius, then obviously the smaller circle does not lies completely inside the circle. Below is the implementation of the above approach: CPP Java Python C# Javascript // C++ program to check if one circle// lies inside another circle or not. #include <bits/stdc++.h>using namespace std; void circle(int x1, int y1, int x2, int y2, int r1, int r2){ int distSq = sqrt(((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2))); if (distSq + r2 == r1) cout << "The smaller circle lies completely" << " inside the bigger circle with " << "touching each other " << "at a point of circumference. " << endl; else if (distSq + r2 < r1) cout << "The smaller circle lies completely" << " inside the bigger circle without" << " touching each other " << "at a point of circumference. " << endl; else cout << "The smaller does not lies inside" << " the bigger circle completely." << endl;} // Driver codeint main(){ int x1 = 10, y1 = 8; int x2 = 1, y2 = 2; int r1 = 30, r2 = 10; circle(x1, y1, x2, y2, r1, r2); return 0;} // Java program to check if one circle // lies inside another circle or not. import java.io.*; class GFG { static void circle(int x1, int y1, int x2, int y2, int r1, int r2) { int distSq = (int)Math.sqrt(((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2))); if (distSq + r2 == r1) { System.out.println("The smaller circle lies completely" + " inside the bigger circle with " + "touching each other " + "at a point of circumference. ") ; } else if (distSq + r2 < r1) { System.out.println("The smaller circle lies completely" + " inside the bigger circle without" + " touching each other " + "at a point of circumference.") ; } else { System.out.println("The smaller does not lies inside" + " the bigger circle completely.") ; } } // Driver code public static void main (String[] args) { int x1 = 10, y1 = 8; int x2 = 1, y2 = 2; int r1 = 30, r2 = 10; circle(x1, y1, x2, y2, r1, r2); }} // This code is contributed by ajit_00023. # Python3 program to check if one circle# lies inside another circle or not. def circle(x1, y1, x2,y2, r1, r2): distSq = (((x1 - x2)* (x1 - x2))+ ((y1 - y2)* (y1 - y2)))**(.5) if (distSq + r2 == r1): print("The smaller circle lies completely" " inside the bigger circle with " "touching each other " "at a point of circumference. ") elif (distSq + r2 < r1): print("The smaller circle lies completely" " inside the bigger circle without" " touching each other " "at a point of circumference. ") else: print("The smaller does not lies inside" " the bigger circle completely.") # Driver codex1 ,y1 = 10,8x2 ,y2 = 1, 2r1 ,r2 = 30,10circle(x1, y1, x2, y2, r1, r2) # This code is contributed by mohit kumar 29 // C# program to check if one circle // lies inside another circle or not. using System; class GFG{ static void circle(int x1, int y1, int x2, int y2, int r1, int r2) { int distSq = (int)Math.Sqrt(((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2))); if (distSq + r2 == r1) { Console.WriteLine("The smaller circle lies completely" + " inside the bigger circle with " + "touching each other " + "at a point of circumference. ") ; } else if (distSq + r2 < r1) { Console.WriteLine("The smaller circle lies completely" + " inside the bigger circle without" + " touching each other " + "at a point of circumference.") ; } else { Console.WriteLine("The smaller does not lies inside" + " the bigger circle completely.") ; } } // Driver code static public void Main () { int x1 = 10, y1 = 8; int x2 = 1, y2 = 2; int r1 = 30, r2 = 10; circle(x1, y1, x2, y2, r1, r2); }} // This code is contributed by AnkitRai01 PHP <?php // PHP program to check if one circle // lies inside another circle or not. function circle($x1, $y1, $x2, $y2, $r1, $r2) { $distSq = sqrt((($x1 - $x2) * ($x1 - $x2)) + (($y1 - $y2) * ($y1 - $y2))); if ($distSq + $r2 == $r1) echo "The smaller circle lies completely ", "inside the bigger circle with ", "touching each other ", "at a point of circumference. \n"; else if ($distSq + $r2 < $r1) echo "The smaller circle lies completely ", "inside the bigger circle without ", "touching each other ", "at a point of circumference. \n"; else echo "The smaller does not lies inside ", "the bigger circle completely. \n"; } // Driver code $x1 = 10; $y1 = 8; $x2 = 1; $y2 = 2; $r1 = 30; $r2 = 10; circle($x1, $y1, $x2, $y2, $r1, $r2); // This code is contributed by ihritik ?> <script>// javascript program to check if one circle // lies inside another circle or not. function circle(x1 , y1 , x2, y2 , r1 , r2) { var distSq = parseInt(Math.sqrt(((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2)))); if (distSq + r2 == r1) { document.write("The smaller circle lies completely" + " inside the bigger circle with " + "touching each other " + "at a point of circumference. ") ; } else if (distSq + r2 < r1) { document.write("The smaller circle lies completely" + " inside the bigger circle without" + " touching each other " + "at a point of circumference.") ; } else { document.write("The smaller does not lies inside" + " the bigger circle completely.") ; } } // Driver code var x1 = 10, y1 = 8; var x2 = 1, y2 = 2; var r1 = 30, r2 = 10; circle(x1, y1, x2, y2, r1, r2); // This code is contributed by Princi Singh </script> mohit kumar 29 ankthon jit_t ihritik princi singh anikaseth98 arorakashish0911 circle Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Check whether a given point lies inside a triangle or not Optimum location of point to minimize total distance Closest Pair of Points | O(nlogn) Implementation Polygon Clipping | Sutherland–Hodgman Algorithm Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26333, "s": 26305, "text": "\n22 Oct, 2021" }, { "code": null, "e": 26468, "s": 26333, "text": "Given two circles with radii and centres given. The task is to check whether the smaller circle lies inside the bigger circle or not. " }, { "code": null, "e": 26480, "s": 26468, "text": "Examples: " }, { "code": null, "e": 26846, "s": 26480, "text": "Input: x1 = 10, y1 = 8, x2 = 1, y2 = 2, r1 = 30, r2 = 10 \nOutput: The smaller circle lies completely inside\n the bigger circle without touching each other\n at a point of circumference. \n\n\nInput :x1 = 7, y1 = 8;x2 = 3, y2 = 5;r1 = 30, r2 = 25\nOutput :The smaller circle lies completely inside\n the bigger circle with touching each other\n at a point of circumference." }, { "code": null, "e": 26885, "s": 26846, "text": "Approach: Here three cases can come, " }, { "code": null, "e": 27226, "s": 26885, "text": "The smaller circle lies completely inside the bigger circle without touching each other at a point of circumference. If this case happens, the sum of the distance between the centres and smaller radius is lesser than the bigger radius, then obviously the smaller circle lies completely inside the circle, without touching the circumference." }, { "code": null, "e": 27562, "s": 27226, "text": "The smaller circle lies completely inside the bigger circle with touching each other at a point of the circumference. If this case happens, the sum of the distance between the centres and smaller radius is equal to the bigger radius, then obviously the smaller circle lies completely inside the circle, with touching the circumference." }, { "code": null, "e": 27823, "s": 27562, "text": "The smaller does not lies inside the bigger circle completely.If this case happens, then sum of the distance between the centers and smaller radius is greater than the bigger radius, then obviously the smaller circle does not lies completely inside the circle." }, { "code": null, "e": 27876, "s": 27823, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27880, "s": 27876, "text": "CPP" }, { "code": null, "e": 27885, "s": 27880, "text": "Java" }, { "code": null, "e": 27892, "s": 27885, "text": "Python" }, { "code": null, "e": 27895, "s": 27892, "text": "C#" }, { "code": null, "e": 27906, "s": 27895, "text": "Javascript" }, { "code": "// C++ program to check if one circle// lies inside another circle or not. #include <bits/stdc++.h>using namespace std; void circle(int x1, int y1, int x2, int y2, int r1, int r2){ int distSq = sqrt(((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2))); if (distSq + r2 == r1) cout << \"The smaller circle lies completely\" << \" inside the bigger circle with \" << \"touching each other \" << \"at a point of circumference. \" << endl; else if (distSq + r2 < r1) cout << \"The smaller circle lies completely\" << \" inside the bigger circle without\" << \" touching each other \" << \"at a point of circumference. \" << endl; else cout << \"The smaller does not lies inside\" << \" the bigger circle completely.\" << endl;} // Driver codeint main(){ int x1 = 10, y1 = 8; int x2 = 1, y2 = 2; int r1 = 30, r2 = 10; circle(x1, y1, x2, y2, r1, r2); return 0;}", "e": 28993, "s": 27906, "text": null }, { "code": "// Java program to check if one circle // lies inside another circle or not. import java.io.*; class GFG { static void circle(int x1, int y1, int x2, int y2, int r1, int r2) { int distSq = (int)Math.sqrt(((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2))); if (distSq + r2 == r1) { System.out.println(\"The smaller circle lies completely\" + \" inside the bigger circle with \" + \"touching each other \" + \"at a point of circumference. \") ; } else if (distSq + r2 < r1) { System.out.println(\"The smaller circle lies completely\" + \" inside the bigger circle without\" + \" touching each other \" + \"at a point of circumference.\") ; } else { System.out.println(\"The smaller does not lies inside\" + \" the bigger circle completely.\") ; } } // Driver code public static void main (String[] args) { int x1 = 10, y1 = 8; int x2 = 1, y2 = 2; int r1 = 30, r2 = 10; circle(x1, y1, x2, y2, r1, r2); }} // This code is contributed by ajit_00023.", "e": 30389, "s": 28993, "text": null }, { "code": "# Python3 program to check if one circle# lies inside another circle or not. def circle(x1, y1, x2,y2, r1, r2): distSq = (((x1 - x2)* (x1 - x2))+ ((y1 - y2)* (y1 - y2)))**(.5) if (distSq + r2 == r1): print(\"The smaller circle lies completely\" \" inside the bigger circle with \" \"touching each other \" \"at a point of circumference. \") elif (distSq + r2 < r1): print(\"The smaller circle lies completely\" \" inside the bigger circle without\" \" touching each other \" \"at a point of circumference. \") else: print(\"The smaller does not lies inside\" \" the bigger circle completely.\") # Driver codex1 ,y1 = 10,8x2 ,y2 = 1, 2r1 ,r2 = 30,10circle(x1, y1, x2, y2, r1, r2) # This code is contributed by mohit kumar 29", "e": 31210, "s": 30389, "text": null }, { "code": "// C# program to check if one circle // lies inside another circle or not. using System; class GFG{ static void circle(int x1, int y1, int x2, int y2, int r1, int r2) { int distSq = (int)Math.Sqrt(((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2))); if (distSq + r2 == r1) { Console.WriteLine(\"The smaller circle lies completely\" + \" inside the bigger circle with \" + \"touching each other \" + \"at a point of circumference. \") ; } else if (distSq + r2 < r1) { Console.WriteLine(\"The smaller circle lies completely\" + \" inside the bigger circle without\" + \" touching each other \" + \"at a point of circumference.\") ; } else { Console.WriteLine(\"The smaller does not lies inside\" + \" the bigger circle completely.\") ; } } // Driver code static public void Main () { int x1 = 10, y1 = 8; int x2 = 1, y2 = 2; int r1 = 30, r2 = 10; circle(x1, y1, x2, y2, r1, r2); }} // This code is contributed by AnkitRai01", "e": 32545, "s": 31210, "text": null }, { "code": null, "e": 32550, "s": 32545, "text": "PHP " }, { "code": null, "e": 33576, "s": 32550, "text": "\n<?php\n// PHP program to check if one circle\n// lies inside another circle or not.\n\nfunction circle($x1, $y1, $x2,\n $y2, $r1, $r2)\n{\n $distSq = sqrt((($x1 - $x2)\n * ($x1 - $x2))\n + (($y1 - $y2)\n * ($y1 - $y2)));\n\n if ($distSq + $r2 == $r1)\n echo \"The smaller circle lies completely \", \n \"inside the bigger circle with \", \n \"touching each other \", \n \"at a point of circumference. \\n\";\n \n else if ($distSq + $r2 < $r1)\n echo \"The smaller circle lies completely \",\n \"inside the bigger circle without \",\n \"touching each other \", \n \"at a point of circumference. \\n\";\n \n else\n echo \"The smaller does not lies inside \",\n \"the bigger circle completely. \\n\";\n \n}\n\n// Driver code\n\n$x1 = 10;\n$y1 = 8;\n$x2 = 1; \n$y2 = 2;\n$r1 = 30; \n$r2 = 10;\ncircle($x1, $y1, $x2, $y2, $r1, $r2);\n\n\n// This code is contributed by ihritik\n?>\n\n\n" }, { "code": "<script>// javascript program to check if one circle // lies inside another circle or not. function circle(x1 , y1 , x2, y2 , r1 , r2) { var distSq = parseInt(Math.sqrt(((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2)))); if (distSq + r2 == r1) { document.write(\"The smaller circle lies completely\" + \" inside the bigger circle with \" + \"touching each other \" + \"at a point of circumference. \") ; } else if (distSq + r2 < r1) { document.write(\"The smaller circle lies completely\" + \" inside the bigger circle without\" + \" touching each other \" + \"at a point of circumference.\") ; } else { document.write(\"The smaller does not lies inside\" + \" the bigger circle completely.\") ; } } // Driver code var x1 = 10, y1 = 8; var x2 = 1, y2 = 2; var r1 = 30, r2 = 10; circle(x1, y1, x2, y2, r1, r2); // This code is contributed by Princi Singh </script>", "e": 34712, "s": 33576, "text": null }, { "code": null, "e": 34727, "s": 34712, "text": "mohit kumar 29" }, { "code": null, "e": 34735, "s": 34727, "text": "ankthon" }, { "code": null, "e": 34741, "s": 34735, "text": "jit_t" }, { "code": null, "e": 34749, "s": 34741, "text": "ihritik" }, { "code": null, "e": 34762, "s": 34749, "text": "princi singh" }, { "code": null, "e": 34774, "s": 34762, "text": "anikaseth98" }, { "code": null, "e": 34791, "s": 34774, "text": "arorakashish0911" }, { "code": null, "e": 34798, "s": 34791, "text": "circle" }, { "code": null, "e": 34808, "s": 34798, "text": "Geometric" }, { "code": null, "e": 34821, "s": 34808, "text": "Mathematical" }, { "code": null, "e": 34834, "s": 34821, "text": "Mathematical" }, { "code": null, "e": 34844, "s": 34834, "text": "Geometric" }, { "code": null, "e": 34942, "s": 34844, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34993, "s": 34942, "text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)" }, { "code": null, "e": 35051, "s": 34993, "text": "Check whether a given point lies inside a triangle or not" }, { "code": null, "e": 35104, "s": 35051, "text": "Optimum location of point to minimize total distance" }, { "code": null, "e": 35153, "s": 35104, "text": "Closest Pair of Points | O(nlogn) Implementation" }, { "code": null, "e": 35201, "s": 35153, "text": "Polygon Clipping | Sutherland–Hodgman Algorithm" }, { "code": null, "e": 35231, "s": 35201, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 35291, "s": 35231, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 35306, "s": 35291, "text": "C++ Data Types" }, { "code": null, "e": 35349, "s": 35306, "text": "Set in C++ Standard Template Library (STL)" } ]
Batch Script - Replace a String - GeeksforGeeks
28 Nov, 2021 In this article, we are going to Replace a substring with any given string. @echo off set str=GFG is the platform for geeks. echo %str% set str=%str:the=best% echo %str% pause In the above example, we are going to replace ‘the’ by substring ‘best’ using %str:the=best% statement. Explanation : By using ‘ set ‘ we are getting input of any string set str=input string In the next line using ‘ echo %str% ‘ we are printing our string. Using ‘ %str:the=best%’ statement , we are replacing substring ‘the’ with ‘best’. Then using ‘pause’, to hold the screen until any key is pressed, so that we can read our output. Output : ‘the’ is replaced by ‘best’ @echo off set str=GFG is the platform for geeks. set word=best echo %str% call set str=%%str:the=%word%%% echo %str% pause Explanation : Everything is as same as before, we are trying to replace the word ‘the’ with ‘best’ but we can also do this by calling another variable ‘word’ which is equal to ‘best’. By using call there is another layer of variable expansion so we have to use ‘%’ for ‘word’ so that it will use ‘best’ as its value and replace the string. output by 2nd approach Batch-script Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples mv command in Linux with examples Docker - COPY Instruction SED command in Linux | Set 2 chown command in Linux with Examples nohup Command in Linux with Examples Named Pipe or FIFO with example C program Thread functions in C/C++ uniq Command in LINUX with examples Start/Stop/Restart Services Using Systemctl in Linux
[ { "code": null, "e": 25651, "s": 25623, "text": "\n28 Nov, 2021" }, { "code": null, "e": 25727, "s": 25651, "text": "In this article, we are going to Replace a substring with any given string." }, { "code": null, "e": 25832, "s": 25727, "text": "@echo off \nset str=GFG is the platform for geeks. \necho %str% \n\nset str=%str:the=best% \necho %str%\npause" }, { "code": null, "e": 25936, "s": 25832, "text": "In the above example, we are going to replace ‘the’ by substring ‘best’ using %str:the=best% statement." }, { "code": null, "e": 25950, "s": 25936, "text": "Explanation :" }, { "code": null, "e": 26002, "s": 25950, "text": "By using ‘ set ‘ we are getting input of any string" }, { "code": null, "e": 26023, "s": 26002, "text": "set str=input string" }, { "code": null, "e": 26089, "s": 26023, "text": "In the next line using ‘ echo %str% ‘ we are printing our string." }, { "code": null, "e": 26171, "s": 26089, "text": "Using ‘ %str:the=best%’ statement , we are replacing substring ‘the’ with ‘best’." }, { "code": null, "e": 26268, "s": 26171, "text": "Then using ‘pause’, to hold the screen until any key is pressed, so that we can read our output." }, { "code": null, "e": 26277, "s": 26268, "text": "Output :" }, { "code": null, "e": 26305, "s": 26277, "text": "‘the’ is replaced by ‘best’" }, { "code": null, "e": 26431, "s": 26305, "text": "@echo off \nset str=GFG is the platform for geeks.\nset word=best\necho %str% \n\ncall set str=%%str:the=%word%%%\necho %str%\npause" }, { "code": null, "e": 26445, "s": 26431, "text": "Explanation :" }, { "code": null, "e": 26615, "s": 26445, "text": "Everything is as same as before, we are trying to replace the word ‘the’ with ‘best’ but we can also do this by calling another variable ‘word’ which is equal to ‘best’." }, { "code": null, "e": 26771, "s": 26615, "text": "By using call there is another layer of variable expansion so we have to use ‘%’ for ‘word’ so that it will use ‘best’ as its value and replace the string." }, { "code": null, "e": 26794, "s": 26771, "text": "output by 2nd approach" }, { "code": null, "e": 26807, "s": 26794, "text": "Batch-script" }, { "code": null, "e": 26814, "s": 26807, "text": "Picked" }, { "code": null, "e": 26825, "s": 26814, "text": "Linux-Unix" }, { "code": null, "e": 26923, "s": 26825, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26958, "s": 26923, "text": "scp command in Linux with Examples" }, { "code": null, "e": 26992, "s": 26958, "text": "mv command in Linux with examples" }, { "code": null, "e": 27018, "s": 26992, "text": "Docker - COPY Instruction" }, { "code": null, "e": 27047, "s": 27018, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 27084, "s": 27047, "text": "chown command in Linux with Examples" }, { "code": null, "e": 27121, "s": 27084, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 27163, "s": 27121, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 27189, "s": 27163, "text": "Thread functions in C/C++" }, { "code": null, "e": 27225, "s": 27189, "text": "uniq Command in LINUX with examples" } ]
Select first or last N rows in a Dataframe using head() and tail() method in Python-Pandas - GeeksforGeeks
02 Jul, 2020 Let’s discuss how to select top or bottom N number of rows from a Dataframe using head() & tail() methods. 1) Select first N Rows from a Dataframe using head() method of Pandas DataFrame : Pandas head() method is used to return top n (5 by default) rows of a data frame or series Syntax: Dataframe.head(n). Parameters: (optional) n is integer value, number of rows to be returned. Return: Dataframe with top n rows . Let’s Create a dataframe # import pandas library as pdimport pandas as pd # List of Tuplesstudents = [('Ankit', 22, 'Up', 'Geu'), ('Ankita', 31, 'Delhi', 'Gehu'), ('Rahul', 16, 'Tokyo', 'Abes'), ('Simran', 41, 'Delhi', 'Gehu'), ('Shaurya', 33, 'Delhi', 'Geu'), ('Harshita', 35, 'Mumbai', 'Bhu' ), ('Swapnil', 35, 'Mp', 'Geu'), ('Priya', 35, 'Uk', 'Geu'), ('Jeet', 35, 'Guj', 'Gehu'), ('Ananya', 35, 'Up', 'Bhu') ] # Create a DataFrame object from# list of tuples along with columns# and indices.details = pd.DataFrame(students, columns =['Name', 'Age', 'Place', 'College'], index =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k']) details Output: Example 1: # Show first 5 rows of the details dataframe# from topdetails.head() Output: Example 2: # display top 3 rows of the dataframedetails.head(3) Output: Example 3: # display top 2 rows of the specific columnsdetails[['Name', 'Age']].head(2) Output: 2) Select last N Rows from a Dataframe using tail() method of Pandas DataFrame : Pandas tail() method is used to return bottom n (5 by default) rows of a data frame or series. Syntax: Dataframe.tail(n) Parameters: (optional) n is integer value, number of rows to be returned. Return: Dataframe with bottom n rows . Example 1: # Show bottom 5 rows of the dataframedetails.tail() Output: Example 2: # Show bottom 3 rows of the dataframedetails.tail(3) Output: Example 3: # Show bottom 2 rows of the specific# columns from dataframedetails[['Name', 'Age']].tail(2) Output: Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 26203, "s": 26175, "text": "\n02 Jul, 2020" }, { "code": null, "e": 26310, "s": 26203, "text": "Let’s discuss how to select top or bottom N number of rows from a Dataframe using head() & tail() methods." }, { "code": null, "e": 26392, "s": 26310, "text": "1) Select first N Rows from a Dataframe using head() method of Pandas DataFrame :" }, { "code": null, "e": 26483, "s": 26392, "text": "Pandas head() method is used to return top n (5 by default) rows of a data frame or series" }, { "code": null, "e": 26510, "s": 26483, "text": "Syntax: Dataframe.head(n)." }, { "code": null, "e": 26584, "s": 26510, "text": "Parameters: (optional) n is integer value, number of rows to be returned." }, { "code": null, "e": 26620, "s": 26584, "text": "Return: Dataframe with top n rows ." }, { "code": null, "e": 26645, "s": 26620, "text": "Let’s Create a dataframe" }, { "code": "# import pandas library as pdimport pandas as pd # List of Tuplesstudents = [('Ankit', 22, 'Up', 'Geu'), ('Ankita', 31, 'Delhi', 'Gehu'), ('Rahul', 16, 'Tokyo', 'Abes'), ('Simran', 41, 'Delhi', 'Gehu'), ('Shaurya', 33, 'Delhi', 'Geu'), ('Harshita', 35, 'Mumbai', 'Bhu' ), ('Swapnil', 35, 'Mp', 'Geu'), ('Priya', 35, 'Uk', 'Geu'), ('Jeet', 35, 'Guj', 'Gehu'), ('Ananya', 35, 'Up', 'Bhu') ] # Create a DataFrame object from# list of tuples along with columns# and indices.details = pd.DataFrame(students, columns =['Name', 'Age', 'Place', 'College'], index =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k']) details", "e": 27461, "s": 26645, "text": null }, { "code": null, "e": 27469, "s": 27461, "text": "Output:" }, { "code": null, "e": 27480, "s": 27469, "text": "Example 1:" }, { "code": "# Show first 5 rows of the details dataframe# from topdetails.head()", "e": 27549, "s": 27480, "text": null }, { "code": null, "e": 27557, "s": 27549, "text": "Output:" }, { "code": null, "e": 27568, "s": 27557, "text": "Example 2:" }, { "code": "# display top 3 rows of the dataframedetails.head(3)", "e": 27621, "s": 27568, "text": null }, { "code": null, "e": 27629, "s": 27621, "text": "Output:" }, { "code": null, "e": 27640, "s": 27629, "text": "Example 3:" }, { "code": "# display top 2 rows of the specific columnsdetails[['Name', 'Age']].head(2)", "e": 27717, "s": 27640, "text": null }, { "code": null, "e": 27725, "s": 27717, "text": "Output:" }, { "code": null, "e": 27806, "s": 27725, "text": "2) Select last N Rows from a Dataframe using tail() method of Pandas DataFrame :" }, { "code": null, "e": 27901, "s": 27806, "text": "Pandas tail() method is used to return bottom n (5 by default) rows of a data frame or series." }, { "code": null, "e": 27927, "s": 27901, "text": "Syntax: Dataframe.tail(n)" }, { "code": null, "e": 28001, "s": 27927, "text": "Parameters: (optional) n is integer value, number of rows to be returned." }, { "code": null, "e": 28040, "s": 28001, "text": "Return: Dataframe with bottom n rows ." }, { "code": null, "e": 28051, "s": 28040, "text": "Example 1:" }, { "code": "# Show bottom 5 rows of the dataframedetails.tail()", "e": 28103, "s": 28051, "text": null }, { "code": null, "e": 28111, "s": 28103, "text": "Output:" }, { "code": null, "e": 28122, "s": 28111, "text": "Example 2:" }, { "code": "# Show bottom 3 rows of the dataframedetails.tail(3)", "e": 28175, "s": 28122, "text": null }, { "code": null, "e": 28183, "s": 28175, "text": "Output:" }, { "code": null, "e": 28194, "s": 28183, "text": "Example 3:" }, { "code": "# Show bottom 2 rows of the specific# columns from dataframedetails[['Name', 'Age']].tail(2)", "e": 28287, "s": 28194, "text": null }, { "code": null, "e": 28295, "s": 28287, "text": "Output:" }, { "code": null, "e": 28319, "s": 28295, "text": "Python pandas-dataFrame" }, { "code": null, "e": 28333, "s": 28319, "text": "Python-pandas" }, { "code": null, "e": 28340, "s": 28333, "text": "Python" }, { "code": null, "e": 28438, "s": 28340, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28456, "s": 28438, "text": "Python Dictionary" }, { "code": null, "e": 28488, "s": 28456, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28510, "s": 28488, "text": "Enumerate() in Python" }, { "code": null, "e": 28552, "s": 28510, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28581, "s": 28552, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28625, "s": 28581, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28662, "s": 28625, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28698, "s": 28662, "text": "Convert integer to string in Python" }, { "code": null, "e": 28740, "s": 28698, "text": "Check if element exists in list in Python" } ]
Python program to print the binary value of the numbers from 1 to N - GeeksforGeeks
24 Jan, 2021 Given a positive number N, the task here is to print the binary value of numbers from 1 to N. For this purpose various approaches can be used. The binary representation of a number is its equivalent value using 1 and 0 only. Example for k = 15, binary value is 1 1 1 1 WORKING FOR METHOD 1 Approach Divide k by 2. Recursive call on the function and print remainder while returning from the recursive call. Repeat the above steps till the k is greater than 1. Repeat the above steps till we reach N Program: Python3 # code to print binary values of first 5 numbers # recursive functiondef Print_Binary_Values(num): # base condition if(num > 1): Print_Binary_Values(num // 2) print(num % 2, end="") # driver codeif __name__ == "__main__": N = 5 # looping N times for i in range(1, N+1): Print_Binary_Values(i) print(end=" ") Output 1 10 11 100 101 Approach Check if k > 1 Right shift the number by 1 bit and perform a recursive call on the function Print the bits of number Repeat the steps till we reach N Program: Python3 # code to print binary values of first 5 numbers # recursive function def Print_Binary_Values(num): # base condition if(num > 1): Print_Binary_Values(num >> 1) print(num & 1, end="") # driver codeif __name__ == "__main__": N = 5 # looping N times for i in range(1, N+1): Print_Binary_Values(i) print(end=" ") Output 1 10 11 100 101 bin() is an inbuilt python function that can convert any decimal number given to it as input to its equivalent binary. Syntax: bin (number) here number is the decimal number that gets converted to binary Program Python3 # code to print first 5 binary number using builtIn library def Print_Binary_Number(num): for i in range(1, num+1): # using bin to print binary value print(int(bin(i).split('0b')[1]), end=" ") # driver codeif __name__ == "__main__": num = 5 Print_Binary_Number(num) Output 1 10 11 100 101 Picked Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n24 Jan, 2021" }, { "code": null, "e": 25681, "s": 25537, "text": "Given a positive number N, the task here is to print the binary value of numbers from 1 to N. For this purpose various approaches can be used. " }, { "code": null, "e": 25807, "s": 25681, "text": "The binary representation of a number is its equivalent value using 1 and 0 only. Example for k = 15, binary value is 1 1 1 1" }, { "code": null, "e": 25828, "s": 25807, "text": "WORKING FOR METHOD 1" }, { "code": null, "e": 25837, "s": 25828, "text": "Approach" }, { "code": null, "e": 25852, "s": 25837, "text": "Divide k by 2." }, { "code": null, "e": 25944, "s": 25852, "text": "Recursive call on the function and print remainder while returning from the recursive call." }, { "code": null, "e": 25997, "s": 25944, "text": "Repeat the above steps till the k is greater than 1." }, { "code": null, "e": 26036, "s": 25997, "text": "Repeat the above steps till we reach N" }, { "code": null, "e": 26045, "s": 26036, "text": "Program:" }, { "code": null, "e": 26053, "s": 26045, "text": "Python3" }, { "code": "# code to print binary values of first 5 numbers # recursive functiondef Print_Binary_Values(num): # base condition if(num > 1): Print_Binary_Values(num // 2) print(num % 2, end=\"\") # driver codeif __name__ == \"__main__\": N = 5 # looping N times for i in range(1, N+1): Print_Binary_Values(i) print(end=\" \")", "e": 26406, "s": 26053, "text": null }, { "code": null, "e": 26413, "s": 26406, "text": "Output" }, { "code": null, "e": 26430, "s": 26413, "text": "1 10 11 100 101 " }, { "code": null, "e": 26439, "s": 26430, "text": "Approach" }, { "code": null, "e": 26454, "s": 26439, "text": "Check if k > 1" }, { "code": null, "e": 26531, "s": 26454, "text": "Right shift the number by 1 bit and perform a recursive call on the function" }, { "code": null, "e": 26556, "s": 26531, "text": "Print the bits of number" }, { "code": null, "e": 26589, "s": 26556, "text": "Repeat the steps till we reach N" }, { "code": null, "e": 26598, "s": 26589, "text": "Program:" }, { "code": null, "e": 26606, "s": 26598, "text": "Python3" }, { "code": "# code to print binary values of first 5 numbers # recursive function def Print_Binary_Values(num): # base condition if(num > 1): Print_Binary_Values(num >> 1) print(num & 1, end=\"\") # driver codeif __name__ == \"__main__\": N = 5 # looping N times for i in range(1, N+1): Print_Binary_Values(i) print(end=\" \")", "e": 26965, "s": 26606, "text": null }, { "code": null, "e": 26972, "s": 26965, "text": "Output" }, { "code": null, "e": 26989, "s": 26972, "text": "1 10 11 100 101 " }, { "code": null, "e": 27108, "s": 26989, "text": "bin() is an inbuilt python function that can convert any decimal number given to it as input to its equivalent binary." }, { "code": null, "e": 27116, "s": 27108, "text": "Syntax:" }, { "code": null, "e": 27130, "s": 27116, "text": "bin (number) " }, { "code": null, "e": 27195, "s": 27130, "text": "here number is the decimal number that gets converted to binary " }, { "code": null, "e": 27203, "s": 27195, "text": "Program" }, { "code": null, "e": 27211, "s": 27203, "text": "Python3" }, { "code": "# code to print first 5 binary number using builtIn library def Print_Binary_Number(num): for i in range(1, num+1): # using bin to print binary value print(int(bin(i).split('0b')[1]), end=\" \") # driver codeif __name__ == \"__main__\": num = 5 Print_Binary_Number(num)", "e": 27508, "s": 27211, "text": null }, { "code": null, "e": 27515, "s": 27508, "text": "Output" }, { "code": null, "e": 27532, "s": 27515, "text": "1 10 11 100 101 " }, { "code": null, "e": 27539, "s": 27532, "text": "Picked" }, { "code": null, "e": 27546, "s": 27539, "text": "Python" }, { "code": null, "e": 27562, "s": 27546, "text": "Python Programs" }, { "code": null, "e": 27660, "s": 27562, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27692, "s": 27660, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27734, "s": 27692, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27776, "s": 27734, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27832, "s": 27776, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27859, "s": 27832, "text": "Python Classes and Objects" }, { "code": null, "e": 27881, "s": 27859, "text": "Defaultdict in Python" }, { "code": null, "e": 27920, "s": 27881, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27966, "s": 27920, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28004, "s": 27966, "text": "Python | Convert a list to dictionary" } ]
Node.js Buffer.swap16() Method - GeeksforGeeks
13 Oct, 2021 The Buffer.swap16() method is an inbuilt application programming interface of class Buffer within Buffer module which is used to swap the buffer byte order in-place. The swapping is performed by interpreting buffer as an array of 16-bit numbers. Syntax: Buffer.swap16() Parameters: This method does not accept any parameters. Return value: It returns a reference to the swapped buffer. Error thrown: It throws ERR_INVALID_BUFFER_SIZE if length of buffer (buf.length) is not a multiple of 2. Below examples illustrate the use of Buffer.swap16() Method in Node.js: Example 1: // Node.js program to demonstrate the // Buffer.swap16() method // Creating a buffer const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); // Display the buffer value// before swap console.log(buf); // Using Buffer.swap16() methodbuf.swap16(); // Display the result // after swapconsole.log(buf); Output: <Buffer 01 02 03 04 05 06 07 08> <Buffer 02 01 04 03 06 05 08 07> Example 2: This example display the error thrown by this method. // Node.js program to demonstrate the // Buffer.swap16() method // Creating a buffer const buf = Buffer.from([0x7, 0x5, 0x2]); // Display the buffer value// before swap console.log(buf); try { // Using Buffer.swap16() method // It will throw error buf.swap16(); // Display the result // after swap console.log(buf); }catch(e) { console.log("Entering catch block"); // Display error console.log(e);} Output: <Buffer 07 05 02> Entering catch block RangeError [ERR_INVALID_BUFFER_SIZE]: Buffer size must be a multiple of 16-bits at Buffer.swap16 (buffer.js:1042:11) at /home/runner/index.js:14:9 ...... Note: The above program will compile and run by using the node index.js command. Reference: https://nodejs.org/dist/latest-v13.x/docs/api/buffer.html#buffer_buf_swap16 Node.js-Buffer-module Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.writeFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js How to use an ES6 import in Node.js? Express.js res.render() Function Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25831, "s": 25803, "text": "\n13 Oct, 2021" }, { "code": null, "e": 26077, "s": 25831, "text": "The Buffer.swap16() method is an inbuilt application programming interface of class Buffer within Buffer module which is used to swap the buffer byte order in-place. The swapping is performed by interpreting buffer as an array of 16-bit numbers." }, { "code": null, "e": 26085, "s": 26077, "text": "Syntax:" }, { "code": null, "e": 26101, "s": 26085, "text": "Buffer.swap16()" }, { "code": null, "e": 26157, "s": 26101, "text": "Parameters: This method does not accept any parameters." }, { "code": null, "e": 26217, "s": 26157, "text": "Return value: It returns a reference to the swapped buffer." }, { "code": null, "e": 26322, "s": 26217, "text": "Error thrown: It throws ERR_INVALID_BUFFER_SIZE if length of buffer (buf.length) is not a multiple of 2." }, { "code": null, "e": 26394, "s": 26322, "text": "Below examples illustrate the use of Buffer.swap16() Method in Node.js:" }, { "code": null, "e": 26405, "s": 26394, "text": "Example 1:" }, { "code": "// Node.js program to demonstrate the // Buffer.swap16() method // Creating a buffer const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); // Display the buffer value// before swap console.log(buf); // Using Buffer.swap16() methodbuf.swap16(); // Display the result // after swapconsole.log(buf); ", "e": 26738, "s": 26405, "text": null }, { "code": null, "e": 26746, "s": 26738, "text": "Output:" }, { "code": null, "e": 26813, "s": 26746, "text": "<Buffer 01 02 03 04 05 06 07 08>\n<Buffer 02 01 04 03 06 05 08 07>\n" }, { "code": null, "e": 26878, "s": 26813, "text": "Example 2: This example display the error thrown by this method." }, { "code": "// Node.js program to demonstrate the // Buffer.swap16() method // Creating a buffer const buf = Buffer.from([0x7, 0x5, 0x2]); // Display the buffer value// before swap console.log(buf); try { // Using Buffer.swap16() method // It will throw error buf.swap16(); // Display the result // after swap console.log(buf); }catch(e) { console.log(\"Entering catch block\"); // Display error console.log(e);}", "e": 27320, "s": 26878, "text": null }, { "code": null, "e": 27328, "s": 27320, "text": "Output:" }, { "code": null, "e": 27534, "s": 27328, "text": "<Buffer 07 05 02>\nEntering catch block\nRangeError [ERR_INVALID_BUFFER_SIZE]: Buffer size\nmust be a multiple of 16-bits\n at Buffer.swap16 (buffer.js:1042:11)\n at /home/runner/index.js:14:9\n ......\n" }, { "code": null, "e": 27615, "s": 27534, "text": "Note: The above program will compile and run by using the node index.js command." }, { "code": null, "e": 27702, "s": 27615, "text": "Reference: https://nodejs.org/dist/latest-v13.x/docs/api/buffer.html#buffer_buf_swap16" }, { "code": null, "e": 27724, "s": 27702, "text": "Node.js-Buffer-module" }, { "code": null, "e": 27731, "s": 27724, "text": "Picked" }, { "code": null, "e": 27739, "s": 27731, "text": "Node.js" }, { "code": null, "e": 27756, "s": 27739, "text": "Web Technologies" }, { "code": null, "e": 27854, "s": 27756, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27884, "s": 27854, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 27941, "s": 27884, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 27995, "s": 27941, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 28032, "s": 27995, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 28065, "s": 28032, "text": "Express.js res.render() Function" }, { "code": null, "e": 28105, "s": 28065, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28150, "s": 28105, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28193, "s": 28150, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28243, "s": 28193, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Find the maximum sum of digits of the product of two numbers - GeeksforGeeks
16 Mar, 2021 Given an array arr[] of size N( > 2). The task is to find the maximum sum of digits of the product of any two numbers of the given array.Examples: Input : arr[] = {8, 7} Output : 11 The product of 8 and 7 is 56. The sum of the digits of 56 is equal to 11.Input : arr[] = {4, 3, 5} Output : 6 Product of 4 & 3 = 12. Sum of the digits = 3. Product of 3 & 5 = 15. Sum of the digits = 6. Product of 4 & 5 = 20. Sum of the digits = 2. Approach: Run nested loops to select two numbers of the array and get the product. For every product check the digit sum and find the maximum digit sum.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program find the maximum sum of// digits of the product of two numbers#include <bits/stdc++.h>using namespace std; // Function to find the sum of the digitsint sumDigits(int n){ int digit_sum = 0; while (n) { digit_sum += n % 10; n /= 10; } return digit_sum;} // Function to find the maximum sum of digits of productint productOfNumbers(int arr[], int n){ int sum = INT_MIN; // Run nested loops for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { int product = arr[i] * arr[j]; // Find the maximum sum sum = max(sum, sumDigits(product)); } } // Return the required answer return sum;} // Driver codeint main(){ int arr[] = { 4, 3, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << productOfNumbers(arr, n); return 0;} // Java program find the maximum sum of// digits of the product of two numbersimport java.io.*; class GFG{ // Function to find the sum of the digitsstatic int sumDigits(int n){ int digit_sum = 0; while (n > 0) { digit_sum += n % 10; n /= 10; } return digit_sum;} // Function to find the maximum sum// of digits of productstatic int productOfNumbers(int []arr, int n){ int sum = Integer.MIN_VALUE; // Run nested loops for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { int product = arr[i] * arr[j]; // Find the maximum sum sum = Math.max(sum, sumDigits(product)); } } // Return the required answer return sum;} // Driver codepublic static void main (String[] args){ int []arr = { 4, 3, 5 }; int n = arr.length; System.out.print( productOfNumbers(arr, n));}} // This code is contributed by anuj_67.. # Python3 program find the maximum sum of# digits of the product of two numbersimport sys # Function to find the sum of the digitsdef sumDigits(n): digit_sum = 0; while (n > 0): digit_sum += n % 10; n /= 10; return digit_sum; # Function to find the maximum sum# of digits of productdef productOfNumbers(arr, n): sum = -sys.maxsize - 1; # Run nested loops for i in range(n - 1): for j in range(i + 1, n): product = arr[i] * arr[j]; # Find the maximum sum sum = max(sum, sumDigits(product)); # Return the required answer return sum; # Driver codeif __name__ == '__main__': arr =[ 4, 3, 5 ]; n = len(arr); print(int(productOfNumbers(arr, n))); # This code contributed by PrinciRaj1992 // C# program find the maximum sum of// digits of the product of two numbersusing System; class GFG{ // Function to find the sum of the digitsstatic int sumDigits(int n){ int digit_sum = 0; while (n > 0) { digit_sum += n % 10; n /= 10; } return digit_sum;} // Function to find the maximum sum// of digits of productstatic int productOfNumbers(int []arr, int n){ int sum = int.MinValue; // Run nested loops for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { int product = arr[i] * arr[j]; // Find the maximum sum sum = Math.Max(sum, sumDigits(product)); } } // Return the required answer return sum;} // Driver codepublic static void Main (String[] args){ int []arr = { 4, 3, 5 }; int n = arr.Length; Console.Write(productOfNumbers(arr, n));}} // This code is contributed by 29AjayKumar <script> // Javascript program find the maximum sum of // digits of the product of two numbers // Function to find the sum of the digits function sumDigits(n) { let digit_sum = 0; while (n > 0) { digit_sum += n % 10; n = parseInt(n / 10, 10); } return digit_sum; } // Function to find the maximum sum of digits of product function productOfNumbers(arr, n) { let sum = Number.MIN_VALUE; // Run nested loops for (let i = 0; i < n - 1; i++) { for (let j = i + 1; j < n; j++) { let product = arr[i] * arr[j]; // Find the maximum sum sum = Math.max(sum, sumDigits(product)); } } // Return the required answer return sum; } let arr = [ 4, 3, 5 ]; let n = arr.length; document.write(productOfNumbers(arr, n)); </script> Output: 6 vt_m 29AjayKumar princiraj1992 divyesh072019 number-digits Numbers Arrays Arrays Numbers 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 Linear Search Linked List vs Array Python | Using 2D arrays/lists the right way Search an element in a sorted and rotated array Queue | Set 1 (Introduction and Array Implementation)
[ { "code": null, "e": 26335, "s": 26307, "text": "\n16 Mar, 2021" }, { "code": null, "e": 26484, "s": 26335, "text": "Given an array arr[] of size N( > 2). The task is to find the maximum sum of digits of the product of any two numbers of the given array.Examples: " }, { "code": null, "e": 26768, "s": 26484, "text": "Input : arr[] = {8, 7} Output : 11 The product of 8 and 7 is 56. The sum of the digits of 56 is equal to 11.Input : arr[] = {4, 3, 5} Output : 6 Product of 4 & 3 = 12. Sum of the digits = 3. Product of 3 & 5 = 15. Sum of the digits = 6. Product of 4 & 5 = 20. Sum of the digits = 2. " }, { "code": null, "e": 26975, "s": 26770, "text": "Approach: Run nested loops to select two numbers of the array and get the product. For every product check the digit sum and find the maximum digit sum.Below is the implementation of the above approach: " }, { "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": 27006, "s": 26995, "text": "Javascript" }, { "code": "// C++ program find the maximum sum of// digits of the product of two numbers#include <bits/stdc++.h>using namespace std; // Function to find the sum of the digitsint sumDigits(int n){ int digit_sum = 0; while (n) { digit_sum += n % 10; n /= 10; } return digit_sum;} // Function to find the maximum sum of digits of productint productOfNumbers(int arr[], int n){ int sum = INT_MIN; // Run nested loops for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { int product = arr[i] * arr[j]; // Find the maximum sum sum = max(sum, sumDigits(product)); } } // Return the required answer return sum;} // Driver codeint main(){ int arr[] = { 4, 3, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << productOfNumbers(arr, n); return 0;}", "e": 27857, "s": 27006, "text": null }, { "code": "// Java program find the maximum sum of// digits of the product of two numbersimport java.io.*; class GFG{ // Function to find the sum of the digitsstatic int sumDigits(int n){ int digit_sum = 0; while (n > 0) { digit_sum += n % 10; n /= 10; } return digit_sum;} // Function to find the maximum sum// of digits of productstatic int productOfNumbers(int []arr, int n){ int sum = Integer.MIN_VALUE; // Run nested loops for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { int product = arr[i] * arr[j]; // Find the maximum sum sum = Math.max(sum, sumDigits(product)); } } // Return the required answer return sum;} // Driver codepublic static void main (String[] args){ int []arr = { 4, 3, 5 }; int n = arr.length; System.out.print( productOfNumbers(arr, n));}} // This code is contributed by anuj_67..", "e": 28799, "s": 27857, "text": null }, { "code": "# Python3 program find the maximum sum of# digits of the product of two numbersimport sys # Function to find the sum of the digitsdef sumDigits(n): digit_sum = 0; while (n > 0): digit_sum += n % 10; n /= 10; return digit_sum; # Function to find the maximum sum# of digits of productdef productOfNumbers(arr, n): sum = -sys.maxsize - 1; # Run nested loops for i in range(n - 1): for j in range(i + 1, n): product = arr[i] * arr[j]; # Find the maximum sum sum = max(sum, sumDigits(product)); # Return the required answer return sum; # Driver codeif __name__ == '__main__': arr =[ 4, 3, 5 ]; n = len(arr); print(int(productOfNumbers(arr, n))); # This code contributed by PrinciRaj1992", "e": 29581, "s": 28799, "text": null }, { "code": "// C# program find the maximum sum of// digits of the product of two numbersusing System; class GFG{ // Function to find the sum of the digitsstatic int sumDigits(int n){ int digit_sum = 0; while (n > 0) { digit_sum += n % 10; n /= 10; } return digit_sum;} // Function to find the maximum sum// of digits of productstatic int productOfNumbers(int []arr, int n){ int sum = int.MinValue; // Run nested loops for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { int product = arr[i] * arr[j]; // Find the maximum sum sum = Math.Max(sum, sumDigits(product)); } } // Return the required answer return sum;} // Driver codepublic static void Main (String[] args){ int []arr = { 4, 3, 5 }; int n = arr.Length; Console.Write(productOfNumbers(arr, n));}} // This code is contributed by 29AjayKumar", "e": 30510, "s": 29581, "text": null }, { "code": "<script> // Javascript program find the maximum sum of // digits of the product of two numbers // Function to find the sum of the digits function sumDigits(n) { let digit_sum = 0; while (n > 0) { digit_sum += n % 10; n = parseInt(n / 10, 10); } return digit_sum; } // Function to find the maximum sum of digits of product function productOfNumbers(arr, n) { let sum = Number.MIN_VALUE; // Run nested loops for (let i = 0; i < n - 1; i++) { for (let j = i + 1; j < n; j++) { let product = arr[i] * arr[j]; // Find the maximum sum sum = Math.max(sum, sumDigits(product)); } } // Return the required answer return sum; } let arr = [ 4, 3, 5 ]; let n = arr.length; document.write(productOfNumbers(arr, n)); </script>", "e": 31448, "s": 30510, "text": null }, { "code": null, "e": 31458, "s": 31448, "text": "Output: " }, { "code": null, "e": 31460, "s": 31458, "text": "6" }, { "code": null, "e": 31467, "s": 31462, "text": "vt_m" }, { "code": null, "e": 31479, "s": 31467, "text": "29AjayKumar" }, { "code": null, "e": 31493, "s": 31479, "text": "princiraj1992" }, { "code": null, "e": 31507, "s": 31493, "text": "divyesh072019" }, { "code": null, "e": 31521, "s": 31507, "text": "number-digits" }, { "code": null, "e": 31529, "s": 31521, "text": "Numbers" }, { "code": null, "e": 31536, "s": 31529, "text": "Arrays" }, { "code": null, "e": 31543, "s": 31536, "text": "Arrays" }, { "code": null, "e": 31551, "s": 31543, "text": "Numbers" }, { "code": null, "e": 31649, "s": 31551, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31717, "s": 31649, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 31761, "s": 31717, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 31809, "s": 31761, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 31832, "s": 31809, "text": "Introduction to Arrays" }, { "code": null, "e": 31864, "s": 31832, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 31878, "s": 31864, "text": "Linear Search" }, { "code": null, "e": 31899, "s": 31878, "text": "Linked List vs Array" }, { "code": null, "e": 31944, "s": 31899, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 31992, "s": 31944, "text": "Search an element in a sorted and rotated array" } ]
TypeScript | String substring() Method - GeeksforGeeks
18 Jun, 2020 The substring() is an inbuilt function in TypeScript which is used to return the subset of a String object. Syntax: string.substring(indexA, [indexB]) Parameter: This method accepts two parameter as mentioned above and described elow: indexA : This parameter is the integer between 0 and one less than the length of the string. indexB : This parameter is the integer between 0 and length of the string. Return Value: This method returns the subset of a String object. Below example illustrate the String substring() method in TypeScript. Example 1: <script> // Original strings var str = "Geeksforgeeks - Best Platform"; // use of String substring() Method var newstr = str.substring(0,5) console.log(newstr);</script> Output: Geeks Example 2: <script> // Original strings var str = "Geeksforgeeks - Best Platform"; // use of String substring() Method var newstr = str.substring(0,5) console.log(newstr); newstr = str.substring(-2,5) console.log(newstr); newstr = str.substring(12,22) console.log(newstr); newstr = str.substring(0,1) console.log(newstr);</script> Output: Geeks Geeks s - Best P G TypeScript JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25685, "s": 25657, "text": "\n18 Jun, 2020" }, { "code": null, "e": 25793, "s": 25685, "text": "The substring() is an inbuilt function in TypeScript which is used to return the subset of a String object." }, { "code": null, "e": 25803, "s": 25793, "text": " Syntax: " }, { "code": null, "e": 25839, "s": 25803, "text": "string.substring(indexA, [indexB]) " }, { "code": null, "e": 25924, "s": 25839, "text": "Parameter: This method accepts two parameter as mentioned above and described elow: " }, { "code": null, "e": 26017, "s": 25924, "text": "indexA : This parameter is the integer between 0 and one less than the length of the string." }, { "code": null, "e": 26092, "s": 26017, "text": "indexB : This parameter is the integer between 0 and length of the string." }, { "code": null, "e": 26227, "s": 26092, "text": "Return Value: This method returns the subset of a String object. Below example illustrate the String substring() method in TypeScript." }, { "code": null, "e": 26240, "s": 26227, "text": "Example 1: " }, { "code": "<script> // Original strings var str = \"Geeksforgeeks - Best Platform\"; // use of String substring() Method var newstr = str.substring(0,5) console.log(newstr);</script>", "e": 26433, "s": 26240, "text": null }, { "code": null, "e": 26442, "s": 26433, "text": "Output: " }, { "code": null, "e": 26449, "s": 26442, "text": "Geeks\n" }, { "code": null, "e": 26461, "s": 26449, "text": "Example 2: " }, { "code": "<script> // Original strings var str = \"Geeksforgeeks - Best Platform\"; // use of String substring() Method var newstr = str.substring(0,5) console.log(newstr); newstr = str.substring(-2,5) console.log(newstr); newstr = str.substring(12,22) console.log(newstr); newstr = str.substring(0,1) console.log(newstr);</script>", "e": 26831, "s": 26461, "text": null }, { "code": null, "e": 26840, "s": 26831, "text": "Output: " }, { "code": null, "e": 26866, "s": 26840, "text": "Geeks\nGeeks\ns - Best P\nG\n" }, { "code": null, "e": 26877, "s": 26866, "text": "TypeScript" }, { "code": null, "e": 26888, "s": 26877, "text": "JavaScript" }, { "code": null, "e": 26905, "s": 26888, "text": "Web Technologies" }, { "code": null, "e": 27003, "s": 26905, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27043, "s": 27003, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27088, "s": 27043, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27149, "s": 27088, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27221, "s": 27149, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27273, "s": 27221, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 27313, "s": 27273, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27346, "s": 27313, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27391, "s": 27346, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27434, "s": 27391, "text": "How to fetch data from an API in ReactJS ?" } ]
How to Implement View Binding Inside Dialog in Android? - GeeksforGeeks
06 Jan, 2022 In android, View binding is a feature that allows you to more easily write code that interacts with views. Once view binding is enabled in a module, it generates a binding class for each XML layout file present in that module. An instance of a binding class contains direct references to all views that have an ID in the corresponding layout. In this article, we will be implementing the concept of viewBinding inside a dialog box. Here is a sample video of the application which we are going to build. Note that we are going to implement this project in Java Language. Step 1: Create a new project Open a new project. We will be working on Empty Activity with language as Java. Leave all other options unchanged. You can change the name of the project at your convenience. There will be two default files named activity_main.xml and MainActivity.java. If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio? Step 2: Navigate to Build scripts -> build.gradle(module) file and add the following piece of code in it. buildFeatures { viewBinding true } Click on sync now to save changes. Step 3: Working with XML files Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><!--Relative layout as parent layout--><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- Button to show dialog--> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/bt_show" android:text="Show dialog" android:layout_centerInParent="true" /> </RelativeLayout> Follow the path app > res > layout > right click > new > layout resource file and create a new file named as dialog_main.xml. Use the below code in dialog_main.xml file- XML <?xml version="1.0" encoding="utf-8"?><!--Relative layout as parent layoout--><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto"> <!-- cardview to give view of a dialog--> <androidx.cardview.widget.CardView android:layout_width="350dp" android:layout_height="wrap_content" android:layout_centerInParent="true" app:cardCornerRadius="16dp" > <!-- Linear layout number 1--> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center" android:padding="20dp" > <!--textview to show number count--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/tv_count" android:textSize="64sp" android:textStyle="bold" android:text="0" /> <!--Linear layout number 2--> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginTop="16dp" > <!-- minus button--> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:id="@+id/bt_minus" android:text=" - " android:layout_marginEnd="4dp" android:layout_marginRight="4dp" /> <!-- plus button--> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:id="@+id/bt_plus" android:text="+" android:layout_marginStart="4dp" android:layout_marginLeft="4dp" /> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView> </RelativeLayout> After executing the above code design of the dialog_main.xml file looks like this. Step 4: Working with MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java package com.example.bindingdialog; import androidx.appcompat.app.AppCompatActivity; import android.app.Dialog;import android.graphics.Color;import android.graphics.drawable.ColorDrawable;import android.os.Bundle;import android.view.View; import com.example.bindingdialog.databinding.ActivityMainBinding;import com.example.bindingdialog.databinding.DialogMainBinding; public class MainActivity extends AppCompatActivity { // Initialize variables ActivityMainBinding binding; DialogMainBinding dialogMainBinding; Dialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Inflate activity main binding=ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); binding.btShow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Inflate dialog main dialogMainBinding=DialogMainBinding.inflate(getLayoutInflater()); // Initialize dialog dialog=new Dialog(MainActivity.this); // set background transparent dialog.getWindow().setBackgroundDrawable(new ColorDrawable( Color.TRANSPARENT )); // set view dialog.setContentView(dialogMainBinding.getRoot()); // set listener on plus button dialogMainBinding.btPlus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // get count from text view String sCount=dialogMainBinding.tvCount.getText().toString(); // convert into int int count=Integer.parseInt(sCount); // Increase count ++count; // set count on textview dialogMainBinding.tvCount.setText(String.valueOf(count)); } }); // set listener on minus button dialogMainBinding.btMinus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // get count from text view String sCount=dialogMainBinding.tvCount.getText().toString(); // convert into int int count=Integer.parseInt(sCount); // check condition if(count!=0) { // When count is not equal to 0 // Decrease count --count; // set count on text view dialogMainBinding.tvCount.setText(String.valueOf(count)); } } }); // display dialog dialog.show(); } }); }} Here is the final output of our application. Output: sweetyty Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Retrofit with Kotlin Coroutine in Android Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 26381, "s": 26353, "text": "\n06 Jan, 2022" }, { "code": null, "e": 26724, "s": 26381, "text": "In android, View binding is a feature that allows you to more easily write code that interacts with views. Once view binding is enabled in a module, it generates a binding class for each XML layout file present in that module. An instance of a binding class contains direct references to all views that have an ID in the corresponding layout." }, { "code": null, "e": 26951, "s": 26724, "text": "In this article, we will be implementing the concept of viewBinding inside a dialog box. Here is a sample video of the application which we are going to build. Note that we are going to implement this project in Java Language." }, { "code": null, "e": 26980, "s": 26951, "text": "Step 1: Create a new project" }, { "code": null, "e": 27000, "s": 26980, "text": "Open a new project." }, { "code": null, "e": 27095, "s": 27000, "text": "We will be working on Empty Activity with language as Java. Leave all other options unchanged." }, { "code": null, "e": 27155, "s": 27095, "text": "You can change the name of the project at your convenience." }, { "code": null, "e": 27234, "s": 27155, "text": "There will be two default files named activity_main.xml and MainActivity.java." }, { "code": null, "e": 27375, "s": 27234, "text": "If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio? " }, { "code": null, "e": 27481, "s": 27375, "text": "Step 2: Navigate to Build scripts -> build.gradle(module) file and add the following piece of code in it." }, { "code": null, "e": 27518, "s": 27481, "text": "buildFeatures\n{\n viewBinding true\n}" }, { "code": null, "e": 27553, "s": 27518, "text": "Click on sync now to save changes." }, { "code": null, "e": 27584, "s": 27553, "text": "Step 3: Working with XML files" }, { "code": null, "e": 27726, "s": 27584, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file." }, { "code": null, "e": 27730, "s": 27726, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><!--Relative layout as parent layout--><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!-- Button to show dialog--> <Button android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:id=\"@+id/bt_show\" android:text=\"Show dialog\" android:layout_centerInParent=\"true\" /> </RelativeLayout>", "e": 28380, "s": 27730, "text": null }, { "code": null, "e": 28551, "s": 28380, "text": " Follow the path app > res > layout > right click > new > layout resource file and create a new file named as dialog_main.xml. Use the below code in dialog_main.xml file-" }, { "code": null, "e": 28555, "s": 28551, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><!--Relative layout as parent layoout--><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" xmlns:app=\"http://schemas.android.com/apk/res-auto\"> <!-- cardview to give view of a dialog--> <androidx.cardview.widget.CardView android:layout_width=\"350dp\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" app:cardCornerRadius=\"16dp\" > <!-- Linear layout number 1--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" android:gravity=\"center\" android:padding=\"20dp\" > <!--textview to show number count--> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:id=\"@+id/tv_count\" android:textSize=\"64sp\" android:textStyle=\"bold\" android:text=\"0\" /> <!--Linear layout number 2--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\" android:layout_marginTop=\"16dp\" > <!-- minus button--> <Button android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:id=\"@+id/bt_minus\" android:text=\" - \" android:layout_marginEnd=\"4dp\" android:layout_marginRight=\"4dp\" /> <!-- plus button--> <Button android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:id=\"@+id/bt_plus\" android:text=\"+\" android:layout_marginStart=\"4dp\" android:layout_marginLeft=\"4dp\" /> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView> </RelativeLayout>", "e": 30821, "s": 28555, "text": null }, { "code": null, "e": 30904, "s": 30821, "text": "After executing the above code design of the dialog_main.xml file looks like this." }, { "code": null, "e": 30948, "s": 30904, "text": "Step 4: Working with MainActivity.java file" }, { "code": null, "e": 31138, "s": 30948, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 31143, "s": 31138, "text": "Java" }, { "code": "package com.example.bindingdialog; import androidx.appcompat.app.AppCompatActivity; import android.app.Dialog;import android.graphics.Color;import android.graphics.drawable.ColorDrawable;import android.os.Bundle;import android.view.View; import com.example.bindingdialog.databinding.ActivityMainBinding;import com.example.bindingdialog.databinding.DialogMainBinding; public class MainActivity extends AppCompatActivity { // Initialize variables ActivityMainBinding binding; DialogMainBinding dialogMainBinding; Dialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Inflate activity main binding=ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); binding.btShow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Inflate dialog main dialogMainBinding=DialogMainBinding.inflate(getLayoutInflater()); // Initialize dialog dialog=new Dialog(MainActivity.this); // set background transparent dialog.getWindow().setBackgroundDrawable(new ColorDrawable( Color.TRANSPARENT )); // set view dialog.setContentView(dialogMainBinding.getRoot()); // set listener on plus button dialogMainBinding.btPlus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // get count from text view String sCount=dialogMainBinding.tvCount.getText().toString(); // convert into int int count=Integer.parseInt(sCount); // Increase count ++count; // set count on textview dialogMainBinding.tvCount.setText(String.valueOf(count)); } }); // set listener on minus button dialogMainBinding.btMinus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // get count from text view String sCount=dialogMainBinding.tvCount.getText().toString(); // convert into int int count=Integer.parseInt(sCount); // check condition if(count!=0) { // When count is not equal to 0 // Decrease count --count; // set count on text view dialogMainBinding.tvCount.setText(String.valueOf(count)); } } }); // display dialog dialog.show(); } }); }}", "e": 34309, "s": 31143, "text": null }, { "code": null, "e": 34355, "s": 34309, "text": " Here is the final output of our application." }, { "code": null, "e": 34364, "s": 34355, "text": "Output: " }, { "code": null, "e": 34375, "s": 34366, "text": "sweetyty" }, { "code": null, "e": 34383, "s": 34375, "text": "Android" }, { "code": null, "e": 34388, "s": 34383, "text": "Java" }, { "code": null, "e": 34393, "s": 34388, "text": "Java" }, { "code": null, "e": 34401, "s": 34393, "text": "Android" }, { "code": null, "e": 34499, "s": 34401, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34537, "s": 34499, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 34576, "s": 34537, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 34626, "s": 34576, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 34677, "s": 34626, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 34719, "s": 34677, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 34734, "s": 34719, "text": "Arrays in Java" }, { "code": null, "e": 34778, "s": 34734, "text": "Split() String method in Java with examples" }, { "code": null, "e": 34800, "s": 34778, "text": "For-each loop in Java" }, { "code": null, "e": 34851, "s": 34800, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Find element in array that divides all array elements - GeeksforGeeks
01 Apr, 2021 Given an array of n non-negative integers. Find such element in the array, that all array elements are divisible by it.Examples : Input : arr[] = {2, 2, 4} Output : 2 Input : arr[] = {2, 1, 3, 1, 6} Output : 1 Input: arr[] = {2, 3, 5} Output : -1 The approach is to calculate GCD of the entire array and then check if there exist an element equal to the GCD of the array. For calculating the gcd of the entire array we will use Euclidean algorithm. C++ Java Python3 C# PHP Javascript // CPP program to find such number in the array// that all array elements are divisible by it#include <bits/stdc++.h>using namespace std; // Returns gcd of two numbers.int gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Function to return the// desired number if existsint findNumber(int arr[], int n){ // Find GCD of array int ans = arr[0]; for (int i = 0; i < n; i++) ans = gcd(ans, arr[i]); // Check if GCD is present in array for (int i = 0; i < n; i++) if (arr[i] == ans) return ans; return -1;} // Driver Functionint main(){ int arr[] = { 2, 2, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findNumber(arr, n) << endl; return 0;} // JAVA program to find such number in// the array that all array elements// are divisible by itimport java.io.*; class GFG { // Returns GCD of two numbers static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // Function to return the desired // number if exists static int findNumber(int arr[], int n) { // Find GCD of array int ans = arr[0]; for (int i = 0; i < n; i++) ans = gcd(ans, arr[i]); // Check if GCD is present in array for (int i = 0; i < n; i++) if (arr[i] == ans) return ans; return -1; } // Driver Code public static void main(String args[]) { int arr[] = { 2, 2, 4 }; int n = arr.length; System.out.println(findNumber(arr, n)); }} // This code is contributed by Nikita Tiwari # Python3 program to find such number# in the array that all array# elements are divisible by it # Returns GCD of two numbersdef gcd (a, b) : if (a == 0) : return b return gcd (b % a, a) # Function to return the desired# number if existsdef findNumber (arr, n) : # Find GCD of array ans = arr[0] for i in range(0, n) : ans = gcd (ans, arr[i]) # Check if GCD is present in array for i in range(0, n) : if (arr[i] == ans) : return ans return -1 # Driver Codearr = [2, 2, 4];n = len(arr)print(findNumber(arr, n)) # This code is contributed by Nikita Tiwari // C# program to find such number in// the array that all array elements// are divisible by itusing System; class GFG { // Returns GCD of two numbers static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // Function to return the desired // number if exists static int findNumber(int[] arr, int n) { // Find GCD of array int ans = arr[0]; for (int i = 0; i < n; i++) ans = gcd(ans, arr[i]); // Check if GCD is present in array for (int i = 0; i < n; i++) if (arr[i] == ans) return ans; return -1; } // Driver Code public static void Main() { int[] arr = { 2, 2, 4 }; int n = arr.Length; Console.WriteLine(findNumber(arr, n)); }} // This code is contributed by vt_m <?php// PHP program to find such// number in the array that// all array elements are// divisible by it // Returns gcd of two numbersfunction gcd ($a, $b){ if ($a == 0) return $b; return gcd ($b % $a, $a);} // Function to return the// desired number if existsfunction findNumber ($arr, $n){ // Find GCD of array $ans = $arr[0]; for ($i = 0; $i < $n; $i++) $ans = gcd ($ans, $arr[$i]); // Check if GCD is // present in array for ($i = 0; $i < $n; $i++) if ($arr[$i] == $ans) return $ans; return -1;} // Driver Code$arr =array (2, 2, 4);$n = sizeof($arr);echo findNumber($arr, $n), "\n"; // This code is contributed by ajit?> <script> // Javascript program to find such number in the array // that all array elements are divisible by it // Returns gcd of two numbers. function gcd(a, b) { if (a == 0) return b; return gcd(b % a, a); } // Function to return the // desired number if exists function findNumber(arr, n) { // Find GCD of array let ans = arr[0]; for (let i = 0; i < n; i++) ans = gcd(ans, arr[i]); // Check if GCD is present in array for (let i = 0; i < n; i++) if (arr[i] == ans) return ans; return -1; } let arr = [ 2, 2, 4 ]; let n = arr.length; document.write(findNumber(arr, n)); </script> Output : 2 vt_m jit_t divyesh072019 divisibility GCD-LCM Arrays Mathematical Arrays Mathematical 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 Introduction to Arrays Multidimensional Arrays in Java Linear Search Linked List vs Array Program for Fibonacci numbers Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) C++ Data Types Coin Change | DP-7
[ { "code": null, "e": 26101, "s": 26073, "text": "\n01 Apr, 2021" }, { "code": null, "e": 26233, "s": 26101, "text": "Given an array of n non-negative integers. Find such element in the array, that all array elements are divisible by it.Examples : " }, { "code": null, "e": 26352, "s": 26233, "text": "Input : arr[] = {2, 2, 4}\nOutput : 2\n\nInput : arr[] = {2, 1, 3, 1, 6}\nOutput : 1\n\nInput: arr[] = {2, 3, 5}\nOutput : -1" }, { "code": null, "e": 26558, "s": 26354, "text": "The approach is to calculate GCD of the entire array and then check if there exist an element equal to the GCD of the array. For calculating the gcd of the entire array we will use Euclidean algorithm. " }, { "code": null, "e": 26562, "s": 26558, "text": "C++" }, { "code": null, "e": 26567, "s": 26562, "text": "Java" }, { "code": null, "e": 26575, "s": 26567, "text": "Python3" }, { "code": null, "e": 26578, "s": 26575, "text": "C#" }, { "code": null, "e": 26582, "s": 26578, "text": "PHP" }, { "code": null, "e": 26593, "s": 26582, "text": "Javascript" }, { "code": "// CPP program to find such number in the array// that all array elements are divisible by it#include <bits/stdc++.h>using namespace std; // Returns gcd of two numbers.int gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Function to return the// desired number if existsint findNumber(int arr[], int n){ // Find GCD of array int ans = arr[0]; for (int i = 0; i < n; i++) ans = gcd(ans, arr[i]); // Check if GCD is present in array for (int i = 0; i < n; i++) if (arr[i] == ans) return ans; return -1;} // Driver Functionint main(){ int arr[] = { 2, 2, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findNumber(arr, n) << endl; return 0;}", "e": 27323, "s": 26593, "text": null }, { "code": "// JAVA program to find such number in// the array that all array elements// are divisible by itimport java.io.*; class GFG { // Returns GCD of two numbers static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // Function to return the desired // number if exists static int findNumber(int arr[], int n) { // Find GCD of array int ans = arr[0]; for (int i = 0; i < n; i++) ans = gcd(ans, arr[i]); // Check if GCD is present in array for (int i = 0; i < n; i++) if (arr[i] == ans) return ans; return -1; } // Driver Code public static void main(String args[]) { int arr[] = { 2, 2, 4 }; int n = arr.length; System.out.println(findNumber(arr, n)); }} // This code is contributed by Nikita Tiwari", "e": 28209, "s": 27323, "text": null }, { "code": "# Python3 program to find such number# in the array that all array# elements are divisible by it # Returns GCD of two numbersdef gcd (a, b) : if (a == 0) : return b return gcd (b % a, a) # Function to return the desired# number if existsdef findNumber (arr, n) : # Find GCD of array ans = arr[0] for i in range(0, n) : ans = gcd (ans, arr[i]) # Check if GCD is present in array for i in range(0, n) : if (arr[i] == ans) : return ans return -1 # Driver Codearr = [2, 2, 4];n = len(arr)print(findNumber(arr, n)) # This code is contributed by Nikita Tiwari", "e": 28847, "s": 28209, "text": null }, { "code": "// C# program to find such number in// the array that all array elements// are divisible by itusing System; class GFG { // Returns GCD of two numbers static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // Function to return the desired // number if exists static int findNumber(int[] arr, int n) { // Find GCD of array int ans = arr[0]; for (int i = 0; i < n; i++) ans = gcd(ans, arr[i]); // Check if GCD is present in array for (int i = 0; i < n; i++) if (arr[i] == ans) return ans; return -1; } // Driver Code public static void Main() { int[] arr = { 2, 2, 4 }; int n = arr.Length; Console.WriteLine(findNumber(arr, n)); }} // This code is contributed by vt_m", "e": 29704, "s": 28847, "text": null }, { "code": "<?php// PHP program to find such// number in the array that// all array elements are// divisible by it // Returns gcd of two numbersfunction gcd ($a, $b){ if ($a == 0) return $b; return gcd ($b % $a, $a);} // Function to return the// desired number if existsfunction findNumber ($arr, $n){ // Find GCD of array $ans = $arr[0]; for ($i = 0; $i < $n; $i++) $ans = gcd ($ans, $arr[$i]); // Check if GCD is // present in array for ($i = 0; $i < $n; $i++) if ($arr[$i] == $ans) return $ans; return -1;} // Driver Code$arr =array (2, 2, 4);$n = sizeof($arr);echo findNumber($arr, $n), \"\\n\"; // This code is contributed by ajit?>", "e": 30404, "s": 29704, "text": null }, { "code": "<script> // Javascript program to find such number in the array // that all array elements are divisible by it // Returns gcd of two numbers. function gcd(a, b) { if (a == 0) return b; return gcd(b % a, a); } // Function to return the // desired number if exists function findNumber(arr, n) { // Find GCD of array let ans = arr[0]; for (let i = 0; i < n; i++) ans = gcd(ans, arr[i]); // Check if GCD is present in array for (let i = 0; i < n; i++) if (arr[i] == ans) return ans; return -1; } let arr = [ 2, 2, 4 ]; let n = arr.length; document.write(findNumber(arr, n)); </script>", "e": 31145, "s": 30404, "text": null }, { "code": null, "e": 31155, "s": 31145, "text": "Output : " }, { "code": null, "e": 31157, "s": 31155, "text": "2" }, { "code": null, "e": 31164, "s": 31159, "text": "vt_m" }, { "code": null, "e": 31170, "s": 31164, "text": "jit_t" }, { "code": null, "e": 31184, "s": 31170, "text": "divyesh072019" }, { "code": null, "e": 31197, "s": 31184, "text": "divisibility" }, { "code": null, "e": 31205, "s": 31197, "text": "GCD-LCM" }, { "code": null, "e": 31212, "s": 31205, "text": "Arrays" }, { "code": null, "e": 31225, "s": 31212, "text": "Mathematical" }, { "code": null, "e": 31232, "s": 31225, "text": "Arrays" }, { "code": null, "e": 31245, "s": 31232, "text": "Mathematical" }, { "code": null, "e": 31343, "s": 31245, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31411, "s": 31343, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 31434, "s": 31411, "text": "Introduction to Arrays" }, { "code": null, "e": 31466, "s": 31434, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 31480, "s": 31466, "text": "Linear Search" }, { "code": null, "e": 31501, "s": 31480, "text": "Linked List vs Array" }, { "code": null, "e": 31531, "s": 31501, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 31591, "s": 31531, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 31634, "s": 31591, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 31649, "s": 31634, "text": "C++ Data Types" } ]
Dart - Null Aware Operators - GeeksforGeeks
28 Jan, 2022 Null-aware operators in dart allow you to make computations based on whether or not a value is null. It’s shorthand for longer expressions. A null-aware operator is a nice tool for making nullable types usable in Dart instead of throwing an error. These operators are used in fullback in combination that you will get value at the end but not null. Null-aware operators are used in almost every programming language to check whether the given variable value is Null. The keyword for Null in the programming language Dart is null. Null means a variable which has no values assign ever and the variable is initialized with nothing like. The most common use of the Null aware operator is when a developer wants to parse JSON data from the server and after parsing JSON, the user can check whether the JSON is empty or not using the IF-Else condition. Here are few Null-aware operators that are explained. We use ?? when you want to evaluate and return an expression if another expression resolves to null. It is also called the if-null operator and coalescing operator. The null-aware operator is ??, which returns the expression on its left unless that expression’s value is null. In which case it’s null it returns the expression on its right: Example 1: Dart void main(){ // In this we have defined the value of variable b. var b = "GeeksforGeeks"; String a = b ?? 'Hello'; print(a); // In this we have not defined the value of variable c. var c; String d = c ?? 'hello'; print(d);} Output: GeeksforGeeks hello Explanation: In the above example, we have two parts. In the first part value of variable b is not null. In the second part value of the variable c is null. In the first part, since the variable b is not null, the ?? operator will return the assigned value, i.e., GeeksforGeeks, and in the second part, the variable c is null, hence the second value will be returned from the ?? operator, i.e hello. Example 2 : Dart void main() { var code; code = code ?? "Java"; print(code); var companyName = "Microsoft"; companyName = companyName ?? "Google"; print(companyName);} Output: Java Microsoft Explanation: In the above example, we declared two variables and one of them is of null value and the other is not null and contains a string value. We are using the ?? operator when reassigning values to those variables. In the first variable, since the variable code is null, the ?? operator will return the second value, i.e., Java, and in the second case, the variable companyName is not null, hence the first value will be returned from the ?? operator, i.e Microsoft. This operator was introduced in Dart version 2.3. Placing ... before an expression, inserts a list into another only if it’s not null. It helps add multiple values to our collection like List, Map, and Set. It is also called a Null check operator. Example 1: Dart void main(){ List<int> lowerNumber = [1,2,3,4,5]; List<int> upperNumbers = [6,8,9,0]; lowerNumber = [...lowerNumber,...?upperNumbers]; print('numbers are ${lowerNumber}'); List<int> listNull; lowerNumber = [...lowerNumber, ...?listNull]; print('new list are ${lowerNumber}');} Output: Explanation: In the first line of output, we get the appended list. Now we see the value of listNull is not assigned i.e it’s null. In dart, if we don’t use (...?) operator we get an error because the value of listNull is null and we cannot print the desired output which you can see below – To remove this error we have used the (...?) operator so that we don’t get an error and get desired output. So in the second line, we got a new list without causing an error. Example 2: Dart void main(){ List<Friend> friendA = [ Friend(name: 'Sara', age: 12), Friend(name: 'Jenny', age: 17) ]; List<Friend> friendB; List<Friend> myFriends = [...friendA, ...?friendB, Friend(name: 'Julia', age: 15)]; myFriends.forEach((friend) => print(friend.name));}class Friend{ String name; int age; Friend({this.name, this.age});} Output: hiichbinlolol Blogathon-2021 Dart Function Blogathon Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create a Table With Multiple Foreign Keys in SQL? How to Import JSON Data into SQL Server? Stratified Sampling in Pandas How to Install Tkinter in Windows? Python program to convert XML to Dictionary Flutter - DropDownButton Widget Listview.builder in Flutter Flutter - Asset Image Splash Screen in Flutter Flutter - Custom Bottom Navigation Bar
[ { "code": null, "e": 26122, "s": 26094, "text": "\n28 Jan, 2022" }, { "code": null, "e": 26970, "s": 26122, "text": "Null-aware operators in dart allow you to make computations based on whether or not a value is null. It’s shorthand for longer expressions. A null-aware operator is a nice tool for making nullable types usable in Dart instead of throwing an error. These operators are used in fullback in combination that you will get value at the end but not null. Null-aware operators are used in almost every programming language to check whether the given variable value is Null. The keyword for Null in the programming language Dart is null. Null means a variable which has no values assign ever and the variable is initialized with nothing like. The most common use of the Null aware operator is when a developer wants to parse JSON data from the server and after parsing JSON, the user can check whether the JSON is empty or not using the IF-Else condition." }, { "code": null, "e": 27024, "s": 26970, "text": "Here are few Null-aware operators that are explained." }, { "code": null, "e": 27125, "s": 27024, "text": "We use ?? when you want to evaluate and return an expression if another expression resolves to null." }, { "code": null, "e": 27189, "s": 27125, "text": "It is also called the if-null operator and coalescing operator." }, { "code": null, "e": 27365, "s": 27189, "text": "The null-aware operator is ??, which returns the expression on its left unless that expression’s value is null. In which case it’s null it returns the expression on its right:" }, { "code": null, "e": 27376, "s": 27365, "text": "Example 1:" }, { "code": null, "e": 27381, "s": 27376, "text": "Dart" }, { "code": "void main(){ // In this we have defined the value of variable b. var b = \"GeeksforGeeks\"; String a = b ?? 'Hello'; print(a); // In this we have not defined the value of variable c. var c; String d = c ?? 'hello'; print(d);}", "e": 27618, "s": 27381, "text": null }, { "code": null, "e": 27627, "s": 27618, "text": "Output: " }, { "code": null, "e": 27647, "s": 27627, "text": "GeeksforGeeks\nhello" }, { "code": null, "e": 28048, "s": 27647, "text": "Explanation: In the above example, we have two parts. In the first part value of variable b is not null. In the second part value of the variable c is null. In the first part, since the variable b is not null, the ?? operator will return the assigned value, i.e., GeeksforGeeks, and in the second part, the variable c is null, hence the second value will be returned from the ?? operator, i.e hello." }, { "code": null, "e": 28060, "s": 28048, "text": "Example 2 :" }, { "code": null, "e": 28065, "s": 28060, "text": "Dart" }, { "code": "void main() { var code; code = code ?? \"Java\"; print(code); var companyName = \"Microsoft\"; companyName = companyName ?? \"Google\"; print(companyName);}", "e": 28229, "s": 28065, "text": null }, { "code": null, "e": 28238, "s": 28229, "text": "Output: " }, { "code": null, "e": 28253, "s": 28238, "text": "Java\nMicrosoft" }, { "code": null, "e": 28727, "s": 28253, "text": "Explanation: In the above example, we declared two variables and one of them is of null value and the other is not null and contains a string value. We are using the ?? operator when reassigning values to those variables. In the first variable, since the variable code is null, the ?? operator will return the second value, i.e., Java, and in the second case, the variable companyName is not null, hence the first value will be returned from the ?? operator, i.e Microsoft." }, { "code": null, "e": 28777, "s": 28727, "text": "This operator was introduced in Dart version 2.3." }, { "code": null, "e": 28862, "s": 28777, "text": "Placing ... before an expression, inserts a list into another only if it’s not null." }, { "code": null, "e": 28934, "s": 28862, "text": "It helps add multiple values to our collection like List, Map, and Set." }, { "code": null, "e": 28975, "s": 28934, "text": "It is also called a Null check operator." }, { "code": null, "e": 28986, "s": 28975, "text": "Example 1:" }, { "code": null, "e": 28991, "s": 28986, "text": "Dart" }, { "code": "void main(){ List<int> lowerNumber = [1,2,3,4,5]; List<int> upperNumbers = [6,8,9,0]; lowerNumber = [...lowerNumber,...?upperNumbers]; print('numbers are ${lowerNumber}'); List<int> listNull; lowerNumber = [...lowerNumber, ...?listNull]; print('new list are ${lowerNumber}');}", "e": 29278, "s": 28991, "text": null }, { "code": null, "e": 29287, "s": 29278, "text": "Output: " }, { "code": null, "e": 29300, "s": 29287, "text": "Explanation:" }, { "code": null, "e": 29355, "s": 29300, "text": "In the first line of output, we get the appended list." }, { "code": null, "e": 29419, "s": 29355, "text": "Now we see the value of listNull is not assigned i.e it’s null." }, { "code": null, "e": 29579, "s": 29419, "text": "In dart, if we don’t use (...?) operator we get an error because the value of listNull is null and we cannot print the desired output which you can see below –" }, { "code": null, "e": 29687, "s": 29579, "text": "To remove this error we have used the (...?) operator so that we don’t get an error and get desired output." }, { "code": null, "e": 29754, "s": 29687, "text": "So in the second line, we got a new list without causing an error." }, { "code": null, "e": 29765, "s": 29754, "text": "Example 2:" }, { "code": null, "e": 29770, "s": 29765, "text": "Dart" }, { "code": "void main(){ List<Friend> friendA = [ Friend(name: 'Sara', age: 12), Friend(name: 'Jenny', age: 17) ]; List<Friend> friendB; List<Friend> myFriends = [...friendA, ...?friendB, Friend(name: 'Julia', age: 15)]; myFriends.forEach((friend) => print(friend.name));}class Friend{ String name; int age; Friend({this.name, this.age});}", "e": 30109, "s": 29770, "text": null }, { "code": null, "e": 30120, "s": 30109, "text": " Output: " }, { "code": null, "e": 30136, "s": 30122, "text": "hiichbinlolol" }, { "code": null, "e": 30151, "s": 30136, "text": "Blogathon-2021" }, { "code": null, "e": 30165, "s": 30151, "text": "Dart Function" }, { "code": null, "e": 30175, "s": 30165, "text": "Blogathon" }, { "code": null, "e": 30180, "s": 30175, "text": "Dart" }, { "code": null, "e": 30278, "s": 30180, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30335, "s": 30278, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 30376, "s": 30335, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 30406, "s": 30376, "text": "Stratified Sampling in Pandas" }, { "code": null, "e": 30441, "s": 30406, "text": "How to Install Tkinter in Windows?" }, { "code": null, "e": 30485, "s": 30441, "text": "Python program to convert XML to Dictionary" }, { "code": null, "e": 30517, "s": 30485, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 30545, "s": 30517, "text": "Listview.builder in Flutter" }, { "code": null, "e": 30567, "s": 30545, "text": "Flutter - Asset Image" }, { "code": null, "e": 30592, "s": 30567, "text": "Splash Screen in Flutter" } ]
Database Management Systems | Set 6 - GeeksforGeeks
09 Nov, 2021 Following questions have been asked in GATE 2009 CS exam. 1) Consider two transactions T1 and T2, and four schedules S1, S2, S3, S4 of T1 and T2 as given below: T1 = R1[X] W1[X] W1[Y] T2 = R2[X] R2[Y] W2[Y] S1 = R1[X] R2[X] R2[Y] W1[X] W1[Y] W2[Y] S2 = R1[X] R2[X] R2[Y] W1[X] W2[Y] W1[Y] S3 = R1[X] W1[X] R2[X] W1[Y] R2[Y] W2[Y] S1 = R1[X] R2[Y]R2[X]W1[X] W1[Y] W2[Y] Which of the above schedules are conflict-serializable? (A) S1 and S2 (B) S2 and S3 (C) S3 only (D) S4 only Answer (B) There can be two possible serial schedules T1 T2 and T2 T1. The serial schedule T1 T2 has the following sequence of operations R1[X] W1[X] W1[Y] R2[X] R2[Y] W2[Y] And the schedule T2 T1 has the following sequence of operations. R2[X] R2[Y] W2[Y] R1[X] W1[X] W1[Y] The Schedule S2 is conflict-equivalent to T2 T1 and S3 is conflict-equivalent to T1 T2. 2) Let R and S be relational schemes such that R={a,b,c} and S={c}. Now consider the following queries on the database: IV) SELECT R.a, R.b FROM R,S WHERE R.c=S.c Which of the above queries are equivalent? (A) I and II (B) I and III (C) II and IV (D) III and IV Answer (A) I and II describe the division operator in Relational Algebra and Tuple Relational Calculus respectively. See Page 3 of this and slide numbers 9,10 of this for more details. 3) Consider the following relational schema: Suppliers(sid:integer, sname:string, city:string, street:string) Parts(pid:integer, pname:string, color:string) Catalog(sid:integer, pid:integer, cost:real) Consider the following relational query on the above database: SELECT S.sname FROM Suppliers S WHERE S.sid NOT IN (SELECT C.sid FROM Catalog C WHERE C.pid NOT IN (SELECT P.pid FROM Parts P WHERE P.color<> 'blue')) Assume that relations corresponding to the above schema are not empty. Which one of the following is the correct interpretation of the above query? (A) Find the names of all suppliers who have supplied a non-blue part. (B) Find the names of all suppliers who have not supplied a non-blue part. (C) Find the names of all suppliers who have supplied only blue parts. (D) Find the names of all suppliers who have not supplied only blue parts. Answer (A) The subquery “SELECT P.pid FROM Parts P WHERE P.color<> ‘blue’” gives pids of parts which are not blue. The bigger subquery “SELECT C.sid FROM Catalog C WHERE C.pid NOT IN (SELECT P.pid FROM Parts P WHERE P.color<> ‘blue’)” gives sids of all those suppliers who have supplied blue parts. The complete query gives the names of all suppliers who have supplied a non-blue part 4) Assume that, in the suppliers relation above, each supplier and each street within a city has a unique name, and (sname, city) forms a candidate key. No other functional dependencies are implied other than those implied by primary and candidate keys. Which one of the following is TRUE about the above schema? (A) The schema is in BCNF (B) The schema is in 3NF but not in BCNF (C) The schema is in 2NF but not in 3NF (D) The schema is not in 2NF Answer (A) A relation is in BCNF if for every one of its dependencies X ? Y, at least one of the following conditions hold: X ? Y is a trivial functional dependency (Y ? X) X is a superkey for schema R Since (sname, city) forms a candidate key, there is no non-trivial dependency X ? Y where X is not a superkey Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc. Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above. sumitgumber28 GATE-CS-2009 DBMS GATE CS MCQ DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL | WITH clause SQL | Join (Inner, Left, Right and Full Joins) SQL query to find second highest salary? SQL Interview Questions CTE in SQL Layers of OSI Model TCP/IP Model Types of Operating Systems Page Replacement Algorithms in Operating Systems Differences between TCP and UDP
[ { "code": null, "e": 30871, "s": 30843, "text": "\n09 Nov, 2021" }, { "code": null, "e": 30930, "s": 30871, "text": "Following questions have been asked in GATE 2009 CS exam. " }, { "code": null, "e": 31350, "s": 30930, "text": "1) Consider two transactions T1 and T2, and four schedules S1, S2, S3, S4 of T1 and T2 as given below: T1 = R1[X] W1[X] W1[Y] T2 = R2[X] R2[Y] W2[Y] S1 = R1[X] R2[X] R2[Y] W1[X] W1[Y] W2[Y] S2 = R1[X] R2[X] R2[Y] W1[X] W2[Y] W1[Y] S3 = R1[X] W1[X] R2[X] W1[Y] R2[Y] W2[Y] S1 = R1[X] R2[Y]R2[X]W1[X] W1[Y] W2[Y] Which of the above schedules are conflict-serializable? (A) S1 and S2 (B) S2 and S3 (C) S3 only (D) S4 only " }, { "code": null, "e": 31714, "s": 31350, "text": "Answer (B) There can be two possible serial schedules T1 T2 and T2 T1. The serial schedule T1 T2 has the following sequence of operations R1[X] W1[X] W1[Y] R2[X] R2[Y] W2[Y] And the schedule T2 T1 has the following sequence of operations. R2[X] R2[Y] W2[Y] R1[X] W1[X] W1[Y] The Schedule S2 is conflict-equivalent to T2 T1 and S3 is conflict-equivalent to T1 T2. " }, { "code": null, "e": 31836, "s": 31714, "text": "2) Let R and S be relational schemes such that R={a,b,c} and S={c}. Now consider the following queries on the database: " }, { "code": null, "e": 31900, "s": 31838, "text": "IV) SELECT R.a, R.b\n FROM R,S\n WHERE R.c=S.c" }, { "code": null, "e": 32000, "s": 31900, "text": "Which of the above queries are equivalent? (A) I and II (B) I and III (C) II and IV (D) III and IV " }, { "code": null, "e": 32186, "s": 32000, "text": "Answer (A) I and II describe the division operator in Relational Algebra and Tuple Relational Calculus respectively. See Page 3 of this and slide numbers 9,10 of this for more details. " }, { "code": null, "e": 32232, "s": 32186, "text": "3) Consider the following relational schema: " }, { "code": null, "e": 32389, "s": 32232, "text": "Suppliers(sid:integer, sname:string, city:string, street:string)\nParts(pid:integer, pname:string, color:string)\nCatalog(sid:integer, pid:integer, cost:real)" }, { "code": null, "e": 32454, "s": 32389, "text": "Consider the following relational query on the above database: " }, { "code": null, "e": 32871, "s": 32454, "text": "SELECT S.sname\n FROM Suppliers S\n WHERE S.sid NOT IN (SELECT C.sid\n FROM Catalog C\n WHERE C.pid NOT IN (SELECT P.pid \n FROM Parts P \n WHERE P.color<> 'blue'))" }, { "code": null, "e": 33020, "s": 32871, "text": "Assume that relations corresponding to the above schema are not empty. Which one of the following is the correct interpretation of the above query? " }, { "code": null, "e": 33313, "s": 33020, "text": "(A) Find the names of all suppliers who have supplied a non-blue part. (B) Find the names of all suppliers who have not supplied a non-blue part. (C) Find the names of all suppliers who have supplied only blue parts. (D) Find the names of all suppliers who have not supplied only blue parts. " }, { "code": null, "e": 33699, "s": 33313, "text": "Answer (A) The subquery “SELECT P.pid FROM Parts P WHERE P.color<> ‘blue’” gives pids of parts which are not blue. The bigger subquery “SELECT C.sid FROM Catalog C WHERE C.pid NOT IN (SELECT P.pid FROM Parts P WHERE P.color<> ‘blue’)” gives sids of all those suppliers who have supplied blue parts. The complete query gives the names of all suppliers who have supplied a non-blue part " }, { "code": null, "e": 34149, "s": 33699, "text": "4) Assume that, in the suppliers relation above, each supplier and each street within a city has a unique name, and (sname, city) forms a candidate key. No other functional dependencies are implied other than those implied by primary and candidate keys. Which one of the following is TRUE about the above schema? (A) The schema is in BCNF (B) The schema is in 3NF but not in BCNF (C) The schema is in 2NF but not in 3NF (D) The schema is not in 2NF " }, { "code": null, "e": 34274, "s": 34149, "text": "Answer (A) A relation is in BCNF if for every one of its dependencies X ? Y, at least one of the following conditions hold: " }, { "code": null, "e": 34361, "s": 34274, "text": " X ? Y is a trivial functional dependency (Y ? X)\n X is a superkey for schema R " }, { "code": null, "e": 34472, "s": 34361, "text": "Since (sname, city) forms a candidate key, there is no non-trivial dependency X ? Y where X is not a superkey " }, { "code": null, "e": 34587, "s": 34472, "text": "Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc. " }, { "code": null, "e": 34737, "s": 34587, "text": "Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above. " }, { "code": null, "e": 34751, "s": 34737, "text": "sumitgumber28" }, { "code": null, "e": 34764, "s": 34751, "text": "GATE-CS-2009" }, { "code": null, "e": 34769, "s": 34764, "text": "DBMS" }, { "code": null, "e": 34777, "s": 34769, "text": "GATE CS" }, { "code": null, "e": 34781, "s": 34777, "text": "MCQ" }, { "code": null, "e": 34786, "s": 34781, "text": "DBMS" }, { "code": null, "e": 34884, "s": 34786, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34902, "s": 34884, "text": "SQL | WITH clause" }, { "code": null, "e": 34949, "s": 34902, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 34990, "s": 34949, "text": "SQL query to find second highest salary?" }, { "code": null, "e": 35014, "s": 34990, "text": "SQL Interview Questions" }, { "code": null, "e": 35025, "s": 35014, "text": "CTE in SQL" }, { "code": null, "e": 35045, "s": 35025, "text": "Layers of OSI Model" }, { "code": null, "e": 35058, "s": 35045, "text": "TCP/IP Model" }, { "code": null, "e": 35085, "s": 35058, "text": "Types of Operating Systems" }, { "code": null, "e": 35134, "s": 35085, "text": "Page Replacement Algorithms in Operating Systems" } ]
Clearfix in Bootstrap - GeeksforGeeks
15 Jul, 2021 One of the major problems with the structure of HTML is that if you have a child div inside parent div, the child div automatically flows around the parent div. The solution to this problem is using clear property of CSS. Bootstrap allows us to use a class named clearfix which is used to clear the floated contents inside any container.Example 1: Without clearfix property. In the below program two buttons are floated to left and right. html <!DOCTYPE html><html><head> <title>Bootstrap Example</title> <!-- Bootstrap CSS and JS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script> <style> .left{ float:left; } .right{ float:right; } </style></head> <body> <div class="bg-info"> <button type="button" class="btn btn-secondary left"> floated left button </button> <button type="button" class="btn btn-secondary right"> floated right button </button> </div></body></html> Output: Clearfix property clear all the floated content of the element that it is applied to. It is also used to clear floated content within a container. Example 2: With clearfix property. Without using the clearfix class, the parent div may not wrap around the children button elements properly and can cause a broken layout. html <!DOCTYPE html><html><head> <title>Bootstrap Example</title> <!-- Bootstrap CSS and JS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script> <style> .left{ float:left; } .right{ float:right; } </style></head> <body> <div class="bg-info clearfix"> <button type="button" class="btn btn-secondary left"> floated left button </button> <button type="button" class="btn btn-secondary right"> floated right button </button> </div></body></html> Output: Supported Browser: Google Chrome Internet Explorer Firefox Opera Safari ysachin2314 Picked Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to change navigation bar color in Bootstrap ? Form validation using jQuery How to pass data into a bootstrap modal? How to align navbar items to the right in Bootstrap 4 ? How to Show Images on Click using HTML ? 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": 25321, "s": 25293, "text": "\n15 Jul, 2021" }, { "code": null, "e": 25762, "s": 25321, "text": "One of the major problems with the structure of HTML is that if you have a child div inside parent div, the child div automatically flows around the parent div. The solution to this problem is using clear property of CSS. Bootstrap allows us to use a class named clearfix which is used to clear the floated contents inside any container.Example 1: Without clearfix property. In the below program two buttons are floated to left and right. " }, { "code": null, "e": 25767, "s": 25762, "text": "html" }, { "code": "<!DOCTYPE html><html><head> <title>Bootstrap Example</title> <!-- Bootstrap CSS and JS --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js\"></script> <style> .left{ float:left; } .right{ float:right; } </style></head> <body> <div class=\"bg-info\"> <button type=\"button\" class=\"btn btn-secondary left\"> floated left button </button> <button type=\"button\" class=\"btn btn-secondary right\"> floated right button </button> </div></body></html>", "e": 26559, "s": 25767, "text": null }, { "code": null, "e": 26569, "s": 26559, "text": "Output: " }, { "code": null, "e": 26891, "s": 26569, "text": "Clearfix property clear all the floated content of the element that it is applied to. It is also used to clear floated content within a container. Example 2: With clearfix property. Without using the clearfix class, the parent div may not wrap around the children button elements properly and can cause a broken layout. " }, { "code": null, "e": 26896, "s": 26891, "text": "html" }, { "code": "<!DOCTYPE html><html><head> <title>Bootstrap Example</title> <!-- Bootstrap CSS and JS --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js\"></script> <style> .left{ float:left; } .right{ float:right; } </style></head> <body> <div class=\"bg-info clearfix\"> <button type=\"button\" class=\"btn btn-secondary left\"> floated left button </button> <button type=\"button\" class=\"btn btn-secondary right\"> floated right button </button> </div></body></html>", "e": 27697, "s": 26896, "text": null }, { "code": null, "e": 27706, "s": 27697, "text": "Output: " }, { "code": null, "e": 27725, "s": 27706, "text": "Supported Browser:" }, { "code": null, "e": 27739, "s": 27725, "text": "Google Chrome" }, { "code": null, "e": 27757, "s": 27739, "text": "Internet Explorer" }, { "code": null, "e": 27765, "s": 27757, "text": "Firefox" }, { "code": null, "e": 27771, "s": 27765, "text": "Opera" }, { "code": null, "e": 27778, "s": 27771, "text": "Safari" }, { "code": null, "e": 27790, "s": 27778, "text": "ysachin2314" }, { "code": null, "e": 27797, "s": 27790, "text": "Picked" }, { "code": null, "e": 27807, "s": 27797, "text": "Bootstrap" }, { "code": null, "e": 27824, "s": 27807, "text": "Web Technologies" }, { "code": null, "e": 27922, "s": 27824, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27972, "s": 27922, "text": "How to change navigation bar color in Bootstrap ?" }, { "code": null, "e": 28001, "s": 27972, "text": "Form validation using jQuery" }, { "code": null, "e": 28042, "s": 28001, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 28098, "s": 28042, "text": "How to align navbar items to the right in Bootstrap 4 ?" }, { "code": null, "e": 28139, "s": 28098, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 28179, "s": 28139, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28212, "s": 28179, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28257, "s": 28212, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28300, "s": 28257, "text": "How to fetch data from an API in ReactJS ?" } ]
How to add Mask to an EditText in Android - GeeksforGeeks
18 Feb, 2021 EditText is an android widget. It is a user interface element used for entering and modifying data. It returns data in String format. Masking refers to the process of putting something in place of something else. Therefore by Masking an EditText, the blank space is replaced with some default text, known as Mask. This mask gets removed as soon as the user enters any character as input, and reappears when the text has been removed from the EditText. In this article, the masking is done with the help of JitPack library, because it can be customized easily according to the need to implement various fields like phone number, date, etc. Approach: Add the support Library in your root build.gradle file (not your module build.gradle file). This library jitpack is a novel package repository. It is made for JVM so that any library which is present in github and bigbucket can be directly used in the application.allprojects { repositories { maven { url "https://jitpack.io" } }}Add the below dependency in the dependencies section. It is a simple Android edittext with custom mask support. Mask edittext is directly imported and is customized according to the use.dependencies { implementation 'ru.egslava:MaskedEditText:1.0.5'}Now add the following code in the activity_main.xml file. It will create three mask edittexts and one button in activity_main.xml.activity_main.xmlactivity_main.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto" android:orientation="vertical" tools:context=".MainActivity"> <br.com.sapereaude.maskedEditText.MaskedEditText android:hint="#### #### #### ####" android:layout_width="match_parent" android:inputType="number" <!-- Set the masked characters --> app:mask="#### #### #### ####" android:layout_height="wrap_content" android:layout_margin="20dp" android:id="@+id/card"/> <br.com.sapereaude.maskedEditText.MaskedEditText android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:id="@+id/phone" android:hint="9876543210" android:inputType="phone" app:keep_hint="true" <!-- Set the masked characters --> app:mask="+91 ### ### ####"/> <br.com.sapereaude.maskedEditText.MaskedEditText android:hint="##:##:####" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:id="@+id/Date" android:inputType="date" <!-- Set the masked characters --> app:mask="##:##:####"/> <Button android:id="@+id/showButton" android:layout_marginTop="40dp" android:layout_gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAllCaps="false" android:textSize="18sp" android:text="Show" /></LinearLayout>Now add the following code in the MainActivity.java file. All the three mask edittexts and a button are defined. An onClickListener() is added on the button which creates a toast and shows all the data entered in the mask edittexts.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgMaskEditText; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast;import br.com.sapereaude .maskedEditText .MaskedEditText; public class MainActivity extends AppCompatActivity { MaskedEditText creditCardText, phoneNumText, dateText; Button show; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); creditCardText = findViewById(R.id.card); phoneNumText = findViewById(R.id.phone); dateText = findViewById(R.id.Date); show = findViewById(R.id.showButton); show.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // Display the information // from the EditText // with help of Taosts Toast.makeText( MainActivity.this, "Credit Card Number " + creditCardText.getText() + "\n Phone Number " + phoneNumText.getText() + "\n Date " + dateText.getText(), Toast.LENGTH_LONG) .show(); } }); }} Add the support Library in your root build.gradle file (not your module build.gradle file). This library jitpack is a novel package repository. It is made for JVM so that any library which is present in github and bigbucket can be directly used in the application.allprojects { repositories { maven { url "https://jitpack.io" } }} allprojects { repositories { maven { url "https://jitpack.io" } }} Add the below dependency in the dependencies section. It is a simple Android edittext with custom mask support. Mask edittext is directly imported and is customized according to the use.dependencies { implementation 'ru.egslava:MaskedEditText:1.0.5'} dependencies { implementation 'ru.egslava:MaskedEditText:1.0.5'} Now add the following code in the activity_main.xml file. It will create three mask edittexts and one button in activity_main.xml.activity_main.xmlactivity_main.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto" android:orientation="vertical" tools:context=".MainActivity"> <br.com.sapereaude.maskedEditText.MaskedEditText android:hint="#### #### #### ####" android:layout_width="match_parent" android:inputType="number" <!-- Set the masked characters --> app:mask="#### #### #### ####" android:layout_height="wrap_content" android:layout_margin="20dp" android:id="@+id/card"/> <br.com.sapereaude.maskedEditText.MaskedEditText android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:id="@+id/phone" android:hint="9876543210" android:inputType="phone" app:keep_hint="true" <!-- Set the masked characters --> app:mask="+91 ### ### ####"/> <br.com.sapereaude.maskedEditText.MaskedEditText android:hint="##:##:####" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:id="@+id/Date" android:inputType="date" <!-- Set the masked characters --> app:mask="##:##:####"/> <Button android:id="@+id/showButton" android:layout_marginTop="40dp" android:layout_gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAllCaps="false" android:textSize="18sp" android:text="Show" /></LinearLayout> activity_main.xml <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto" android:orientation="vertical" tools:context=".MainActivity"> <br.com.sapereaude.maskedEditText.MaskedEditText android:hint="#### #### #### ####" android:layout_width="match_parent" android:inputType="number" <!-- Set the masked characters --> app:mask="#### #### #### ####" android:layout_height="wrap_content" android:layout_margin="20dp" android:id="@+id/card"/> <br.com.sapereaude.maskedEditText.MaskedEditText android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:id="@+id/phone" android:hint="9876543210" android:inputType="phone" app:keep_hint="true" <!-- Set the masked characters --> app:mask="+91 ### ### ####"/> <br.com.sapereaude.maskedEditText.MaskedEditText android:hint="##:##:####" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:id="@+id/Date" android:inputType="date" <!-- Set the masked characters --> app:mask="##:##:####"/> <Button android:id="@+id/showButton" android:layout_marginTop="40dp" android:layout_gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAllCaps="false" android:textSize="18sp" android:text="Show" /></LinearLayout> Now add the following code in the MainActivity.java file. All the three mask edittexts and a button are defined. An onClickListener() is added on the button which creates a toast and shows all the data entered in the mask edittexts.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgMaskEditText; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast;import br.com.sapereaude .maskedEditText .MaskedEditText; public class MainActivity extends AppCompatActivity { MaskedEditText creditCardText, phoneNumText, dateText; Button show; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); creditCardText = findViewById(R.id.card); phoneNumText = findViewById(R.id.phone); dateText = findViewById(R.id.Date); show = findViewById(R.id.showButton); show.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // Display the information // from the EditText // with help of Taosts Toast.makeText( MainActivity.this, "Credit Card Number " + creditCardText.getText() + "\n Phone Number " + phoneNumText.getText() + "\n Date " + dateText.getText(), Toast.LENGTH_LONG) .show(); } }); }} MainActivity.java package org.geeksforgeeks.gfgMaskEditText; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast;import br.com.sapereaude .maskedEditText .MaskedEditText; public class MainActivity extends AppCompatActivity { MaskedEditText creditCardText, phoneNumText, dateText; Button show; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); creditCardText = findViewById(R.id.card); phoneNumText = findViewById(R.id.phone); dateText = findViewById(R.id.Date); show = findViewById(R.id.showButton); show.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // Display the information // from the EditText // with help of Taosts Toast.makeText( MainActivity.this, "Credit Card Number " + creditCardText.getText() + "\n Phone Number " + phoneNumText.getText() + "\n Date " + dateText.getText(), Toast.LENGTH_LONG) .show(); } }); }} Output: android Android-View Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Retrofit with Kotlin Coroutine in Android Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 26405, "s": 26377, "text": "\n18 Feb, 2021" }, { "code": null, "e": 26539, "s": 26405, "text": "EditText is an android widget. It is a user interface element used for entering and modifying data. It returns data in String format." }, { "code": null, "e": 26857, "s": 26539, "text": "Masking refers to the process of putting something in place of something else. Therefore by Masking an EditText, the blank space is replaced with some default text, known as Mask. This mask gets removed as soon as the user enters any character as input, and reappears when the text has been removed from the EditText." }, { "code": null, "e": 27044, "s": 26857, "text": "In this article, the masking is done with the help of JitPack library, because it can be customized easily according to the need to implement various fields like phone number, date, etc." }, { "code": null, "e": 27054, "s": 27044, "text": "Approach:" }, { "code": null, "e": 31478, "s": 27054, "text": "Add the support Library in your root build.gradle file (not your module build.gradle file). This library jitpack is a novel package repository. It is made for JVM so that any library which is present in github and bigbucket can be directly used in the application.allprojects { repositories { maven { url \"https://jitpack.io\" } }}Add the below dependency in the dependencies section. It is a simple Android edittext with custom mask support. Mask edittext is directly imported and is customized according to the use.dependencies { implementation 'ru.egslava:MaskedEditText:1.0.5'}Now add the following code in the activity_main.xml file. It will create three mask edittexts and one button in activity_main.xml.activity_main.xmlactivity_main.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <br.com.sapereaude.maskedEditText.MaskedEditText android:hint=\"#### #### #### ####\" android:layout_width=\"match_parent\" android:inputType=\"number\" <!-- Set the masked characters --> app:mask=\"#### #### #### ####\" android:layout_height=\"wrap_content\" android:layout_margin=\"20dp\" android:id=\"@+id/card\"/> <br.com.sapereaude.maskedEditText.MaskedEditText android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"20dp\" android:id=\"@+id/phone\" android:hint=\"9876543210\" android:inputType=\"phone\" app:keep_hint=\"true\" <!-- Set the masked characters --> app:mask=\"+91 ### ### ####\"/> <br.com.sapereaude.maskedEditText.MaskedEditText android:hint=\"##:##:####\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"20dp\" android:id=\"@+id/Date\" android:inputType=\"date\" <!-- Set the masked characters --> app:mask=\"##:##:####\"/> <Button android:id=\"@+id/showButton\" android:layout_marginTop=\"40dp\" android:layout_gravity=\"center\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:textAllCaps=\"false\" android:textSize=\"18sp\" android:text=\"Show\" /></LinearLayout>Now add the following code in the MainActivity.java file. All the three mask edittexts and a button are defined. An onClickListener() is added on the button which creates a toast and shows all the data entered in the mask edittexts.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgMaskEditText; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast;import br.com.sapereaude .maskedEditText .MaskedEditText; public class MainActivity extends AppCompatActivity { MaskedEditText creditCardText, phoneNumText, dateText; Button show; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); creditCardText = findViewById(R.id.card); phoneNumText = findViewById(R.id.phone); dateText = findViewById(R.id.Date); show = findViewById(R.id.showButton); show.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // Display the information // from the EditText // with help of Taosts Toast.makeText( MainActivity.this, \"Credit Card Number \" + creditCardText.getText() + \"\\n Phone Number \" + phoneNumText.getText() + \"\\n Date \" + dateText.getText(), Toast.LENGTH_LONG) .show(); } }); }}" }, { "code": null, "e": 31840, "s": 31478, "text": "Add the support Library in your root build.gradle file (not your module build.gradle file). This library jitpack is a novel package repository. It is made for JVM so that any library which is present in github and bigbucket can be directly used in the application.allprojects { repositories { maven { url \"https://jitpack.io\" } }}" }, { "code": "allprojects { repositories { maven { url \"https://jitpack.io\" } }}", "e": 31938, "s": 31840, "text": null }, { "code": null, "e": 32192, "s": 31938, "text": "Add the below dependency in the dependencies section. It is a simple Android edittext with custom mask support. Mask edittext is directly imported and is customized according to the use.dependencies { implementation 'ru.egslava:MaskedEditText:1.0.5'}" }, { "code": "dependencies { implementation 'ru.egslava:MaskedEditText:1.0.5'}", "e": 32260, "s": 32192, "text": null }, { "code": null, "e": 34227, "s": 32260, "text": "Now add the following code in the activity_main.xml file. It will create three mask edittexts and one button in activity_main.xml.activity_main.xmlactivity_main.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <br.com.sapereaude.maskedEditText.MaskedEditText android:hint=\"#### #### #### ####\" android:layout_width=\"match_parent\" android:inputType=\"number\" <!-- Set the masked characters --> app:mask=\"#### #### #### ####\" android:layout_height=\"wrap_content\" android:layout_margin=\"20dp\" android:id=\"@+id/card\"/> <br.com.sapereaude.maskedEditText.MaskedEditText android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"20dp\" android:id=\"@+id/phone\" android:hint=\"9876543210\" android:inputType=\"phone\" app:keep_hint=\"true\" <!-- Set the masked characters --> app:mask=\"+91 ### ### ####\"/> <br.com.sapereaude.maskedEditText.MaskedEditText android:hint=\"##:##:####\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"20dp\" android:id=\"@+id/Date\" android:inputType=\"date\" <!-- Set the masked characters --> app:mask=\"##:##:####\"/> <Button android:id=\"@+id/showButton\" android:layout_marginTop=\"40dp\" android:layout_gravity=\"center\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:textAllCaps=\"false\" android:textSize=\"18sp\" android:text=\"Show\" /></LinearLayout>" }, { "code": null, "e": 34245, "s": 34227, "text": "activity_main.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <br.com.sapereaude.maskedEditText.MaskedEditText android:hint=\"#### #### #### ####\" android:layout_width=\"match_parent\" android:inputType=\"number\" <!-- Set the masked characters --> app:mask=\"#### #### #### ####\" android:layout_height=\"wrap_content\" android:layout_margin=\"20dp\" android:id=\"@+id/card\"/> <br.com.sapereaude.maskedEditText.MaskedEditText android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"20dp\" android:id=\"@+id/phone\" android:hint=\"9876543210\" android:inputType=\"phone\" app:keep_hint=\"true\" <!-- Set the masked characters --> app:mask=\"+91 ### ### ####\"/> <br.com.sapereaude.maskedEditText.MaskedEditText android:hint=\"##:##:####\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"20dp\" android:id=\"@+id/Date\" android:inputType=\"date\" <!-- Set the masked characters --> app:mask=\"##:##:####\"/> <Button android:id=\"@+id/showButton\" android:layout_marginTop=\"40dp\" android:layout_gravity=\"center\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:textAllCaps=\"false\" android:textSize=\"18sp\" android:text=\"Show\" /></LinearLayout>", "e": 36048, "s": 34245, "text": null }, { "code": null, "e": 37892, "s": 36048, "text": "Now add the following code in the MainActivity.java file. All the three mask edittexts and a button are defined. An onClickListener() is added on the button which creates a toast and shows all the data entered in the mask edittexts.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgMaskEditText; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast;import br.com.sapereaude .maskedEditText .MaskedEditText; public class MainActivity extends AppCompatActivity { MaskedEditText creditCardText, phoneNumText, dateText; Button show; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); creditCardText = findViewById(R.id.card); phoneNumText = findViewById(R.id.phone); dateText = findViewById(R.id.Date); show = findViewById(R.id.showButton); show.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // Display the information // from the EditText // with help of Taosts Toast.makeText( MainActivity.this, \"Credit Card Number \" + creditCardText.getText() + \"\\n Phone Number \" + phoneNumText.getText() + \"\\n Date \" + dateText.getText(), Toast.LENGTH_LONG) .show(); } }); }}" }, { "code": null, "e": 37910, "s": 37892, "text": "MainActivity.java" }, { "code": "package org.geeksforgeeks.gfgMaskEditText; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast;import br.com.sapereaude .maskedEditText .MaskedEditText; public class MainActivity extends AppCompatActivity { MaskedEditText creditCardText, phoneNumText, dateText; Button show; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); creditCardText = findViewById(R.id.card); phoneNumText = findViewById(R.id.phone); dateText = findViewById(R.id.Date); show = findViewById(R.id.showButton); show.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // Display the information // from the EditText // with help of Taosts Toast.makeText( MainActivity.this, \"Credit Card Number \" + creditCardText.getText() + \"\\n Phone Number \" + phoneNumText.getText() + \"\\n Date \" + dateText.getText(), Toast.LENGTH_LONG) .show(); } }); }}", "e": 39488, "s": 37910, "text": null }, { "code": null, "e": 39496, "s": 39488, "text": "Output:" }, { "code": null, "e": 39504, "s": 39496, "text": "android" }, { "code": null, "e": 39517, "s": 39504, "text": "Android-View" }, { "code": null, "e": 39525, "s": 39517, "text": "Android" }, { "code": null, "e": 39530, "s": 39525, "text": "Java" }, { "code": null, "e": 39535, "s": 39530, "text": "Java" }, { "code": null, "e": 39543, "s": 39535, "text": "Android" }, { "code": null, "e": 39641, "s": 39543, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39679, "s": 39641, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 39718, "s": 39679, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 39768, "s": 39718, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 39819, "s": 39768, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 39861, "s": 39819, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 39876, "s": 39861, "text": "Arrays in Java" }, { "code": null, "e": 39920, "s": 39876, "text": "Split() String method in Java with examples" }, { "code": null, "e": 39942, "s": 39920, "text": "For-each loop in Java" }, { "code": null, "e": 39993, "s": 39942, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Modulus of two float or double numbers - GeeksforGeeks
26 May, 2021 Given two floating-point numbers, find the remainder. Examples: Input: a = 36.5, b = 5.0 Output: 1.5 Input: a = 9.7, b = 2.3 Output: 0.5 A simple solution is to do repeated subtraction. C++ Java Python3 C# PHP Javascript // C++ program to find modulo of floating// point numbers.#include <bits/stdc++.h>using namespace std; double findMod(double a, double b){ double mod; // Handling negative values if (a < 0) mod = -a; else mod = a; if (b < 0) b = -b; // Finding mod by repeated subtraction while (mod >= b) mod = mod - b; // Sign of result typically depends // on sign of a. if (a < 0) return -mod; return mod;} // Driver Functionint main(){ double a = 9.7, b = 2.3; cout << findMod(a, b); return 0;} // Java program to find modulo of floating// point numbers class GFG{ static double findMod(double a, double b) { // Handling negative values if (a < 0) a = -a; if (b < 0) b = -b; // Finding mod by repeated subtraction double mod = a; while (mod >= b) mod = mod - b; // Sign of result typically depends // on sign of a. if (a < 0) return -mod; return mod; } // Driver code public static void main (String[] args) { double a = 9.7, b = 2.3; System.out.print(findMod(a, b)); }} // This code is contributed by Anant Agarwal. # Python3 program to find modulo# of floating point numbers. def findMod(a, b): # Handling negative values if (a < 0): a = -a if (b < 0): b = -b # Finding mod by repeated subtraction mod = a while (mod >= b): mod = mod - b # Sign of result typically # depends on sign of a. if (a < 0): return -mod return mod # Driver codea = 9.7; b = 2.3print(findMod(a, b)) # This code is contributed by Anant Agarwal. // C# program to find modulo of floating// point numbersusing System; class GFG { static double findMod(double a, double b) { // Handling negative values if (a < 0) a = -a; if (b < 0) b = -b; // Finding mod by repeated subtraction double mod = a; while (mod >= b) mod = mod - b; // Sign of result typically depends // on sign of a. if (a < 0) return -mod; return mod; } // Driver code public static void Main () { double a = 9.7, b = 2.3; Console.WriteLine(findMod(a, b)); }} // This code is contributed by vt_m. <?php// PHP program to find modulo // of floatingpoint numbers. function findMod($a, $b){ // Handling negative values if ($a < 0) $a = -$a; if ($b < 0) $b = -$b; // Finding mod by repeated // subtraction $mod = $a; while ($mod >= $b) $mod = $mod - $b; // Sign of result typically // depends on sign of a. if ($a < 0) return -$mod; return $mod;} // Driver Code $a = 9.7; $b = 2.3; echo findMod($a, $b); // This code is contributed by anuj_65.?> <script> // Javascript program to find// modulo of floating point numbers. function findMod(a, b){ let mod; // Handling negative values if (a < 0) mod = -a; else mod = a; if (b < 0) b = -b; // Finding mod by // repeated subtraction while (mod >= b) mod = mod - b; // Sign of result typically // depends on sign of a. if (a < 0) return -mod; return mod;} // Driver Function let a = 9.7, b = 2.3; document.write(findMod(a, b)); //This code is contributed by Mayank Tyagi</script> Output : 0.5 We can use the inbuilt fmod function to find the modulus of two floating-point numbers. C++ Java Python3 C# PHP Javascript // CPP program to find modulo of floating// point numbers using library function.#include <bits/stdc++.h>using namespace std; // Driver Functionint main(){ double a = 9.7, b = 2.3; cout << fmod(a, b); return 0;} // JAVA program to find modulo of floating// point numbers using library function.import java.util.*; class GFG{ // Driver Functionpublic static void main(String[] args){ double a = 9.7, b = 2.3; System.out.print((a % b));}} // This code contributed by umadevi9616 # Python3 program to find modulo of floating# point numbers using library function.from math import fmod # Driver codeif __name__ == '__main__': a = 9.7 b = 2.3 print(fmod(a, b)) # This code is contributed by mohit kumar 29 // C# program to find modulo of floating// point numbers using library function.using System; class GFG{ static void Main(){ double a = 9.7; double b = 2.3; Console.WriteLine(a % b);}} // This code is contributed by mukesh07 <?php// PHP program to find modulo of// floating point numbers using// library function. // Driver Code$a = 9.7; $b = 2.3;echo fmod($a, $b); // This code is contributed// by inder_verma?> <script> // Javascript program to find modulo of// floating point numbers using// library function. // Driver Codelet a = 9.7;let b = 2.3;document.write(a%b); // This code is contributed by mohan pavan </script> Output: 0.5 vt_m inderDuMCA rameshmarisa mohit kumar 29 mayanktyagi1709 pulamolusaimohan umadevi9616 mukesh07 CPP-Library Modular Arithmetic C Language C++ Technical Scripter Modular Arithmetic CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Multidimensional Arrays in C / C++ Converting Strings to Numbers in C/C++ Left Shift and Right Shift Operators in C/C++ Function Pointer in C Vector in C++ STL Initialize a vector in C++ (6 different ways) Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects
[ { "code": null, "e": 25858, "s": 25830, "text": "\n26 May, 2021" }, { "code": null, "e": 25912, "s": 25858, "text": "Given two floating-point numbers, find the remainder." }, { "code": null, "e": 25923, "s": 25912, "text": "Examples: " }, { "code": null, "e": 25960, "s": 25923, "text": "Input: a = 36.5, b = 5.0 Output: 1.5" }, { "code": null, "e": 25997, "s": 25960, "text": "Input: a = 9.7, b = 2.3 Output: 0.5 " }, { "code": null, "e": 26047, "s": 25997, "text": "A simple solution is to do repeated subtraction. " }, { "code": null, "e": 26051, "s": 26047, "text": "C++" }, { "code": null, "e": 26056, "s": 26051, "text": "Java" }, { "code": null, "e": 26064, "s": 26056, "text": "Python3" }, { "code": null, "e": 26067, "s": 26064, "text": "C#" }, { "code": null, "e": 26071, "s": 26067, "text": "PHP" }, { "code": null, "e": 26082, "s": 26071, "text": "Javascript" }, { "code": "// C++ program to find modulo of floating// point numbers.#include <bits/stdc++.h>using namespace std; double findMod(double a, double b){ double mod; // Handling negative values if (a < 0) mod = -a; else mod = a; if (b < 0) b = -b; // Finding mod by repeated subtraction while (mod >= b) mod = mod - b; // Sign of result typically depends // on sign of a. if (a < 0) return -mod; return mod;} // Driver Functionint main(){ double a = 9.7, b = 2.3; cout << findMod(a, b); return 0;}", "e": 26651, "s": 26082, "text": null }, { "code": "// Java program to find modulo of floating// point numbers class GFG{ static double findMod(double a, double b) { // Handling negative values if (a < 0) a = -a; if (b < 0) b = -b; // Finding mod by repeated subtraction double mod = a; while (mod >= b) mod = mod - b; // Sign of result typically depends // on sign of a. if (a < 0) return -mod; return mod; } // Driver code public static void main (String[] args) { double a = 9.7, b = 2.3; System.out.print(findMod(a, b)); }} // This code is contributed by Anant Agarwal.", "e": 27342, "s": 26651, "text": null }, { "code": "# Python3 program to find modulo# of floating point numbers. def findMod(a, b): # Handling negative values if (a < 0): a = -a if (b < 0): b = -b # Finding mod by repeated subtraction mod = a while (mod >= b): mod = mod - b # Sign of result typically # depends on sign of a. if (a < 0): return -mod return mod # Driver codea = 9.7; b = 2.3print(findMod(a, b)) # This code is contributed by Anant Agarwal.", "e": 27808, "s": 27342, "text": null }, { "code": "// C# program to find modulo of floating// point numbersusing System; class GFG { static double findMod(double a, double b) { // Handling negative values if (a < 0) a = -a; if (b < 0) b = -b; // Finding mod by repeated subtraction double mod = a; while (mod >= b) mod = mod - b; // Sign of result typically depends // on sign of a. if (a < 0) return -mod; return mod; } // Driver code public static void Main () { double a = 9.7, b = 2.3; Console.WriteLine(findMod(a, b)); }} // This code is contributed by vt_m.", "e": 28522, "s": 27808, "text": null }, { "code": "<?php// PHP program to find modulo // of floatingpoint numbers. function findMod($a, $b){ // Handling negative values if ($a < 0) $a = -$a; if ($b < 0) $b = -$b; // Finding mod by repeated // subtraction $mod = $a; while ($mod >= $b) $mod = $mod - $b; // Sign of result typically // depends on sign of a. if ($a < 0) return -$mod; return $mod;} // Driver Code $a = 9.7; $b = 2.3; echo findMod($a, $b); // This code is contributed by anuj_65.?>", "e": 29049, "s": 28522, "text": null }, { "code": "<script> // Javascript program to find// modulo of floating point numbers. function findMod(a, b){ let mod; // Handling negative values if (a < 0) mod = -a; else mod = a; if (b < 0) b = -b; // Finding mod by // repeated subtraction while (mod >= b) mod = mod - b; // Sign of result typically // depends on sign of a. if (a < 0) return -mod; return mod;} // Driver Function let a = 9.7, b = 2.3; document.write(findMod(a, b)); //This code is contributed by Mayank Tyagi</script>", "e": 29614, "s": 29049, "text": null }, { "code": null, "e": 29624, "s": 29614, "text": "Output : " }, { "code": null, "e": 29628, "s": 29624, "text": "0.5" }, { "code": null, "e": 29717, "s": 29628, "text": "We can use the inbuilt fmod function to find the modulus of two floating-point numbers. " }, { "code": null, "e": 29721, "s": 29717, "text": "C++" }, { "code": null, "e": 29726, "s": 29721, "text": "Java" }, { "code": null, "e": 29734, "s": 29726, "text": "Python3" }, { "code": null, "e": 29737, "s": 29734, "text": "C#" }, { "code": null, "e": 29741, "s": 29737, "text": "PHP" }, { "code": null, "e": 29752, "s": 29741, "text": "Javascript" }, { "code": "// CPP program to find modulo of floating// point numbers using library function.#include <bits/stdc++.h>using namespace std; // Driver Functionint main(){ double a = 9.7, b = 2.3; cout << fmod(a, b); return 0;}", "e": 29973, "s": 29752, "text": null }, { "code": "// JAVA program to find modulo of floating// point numbers using library function.import java.util.*; class GFG{ // Driver Functionpublic static void main(String[] args){ double a = 9.7, b = 2.3; System.out.print((a % b));}} // This code contributed by umadevi9616", "e": 30244, "s": 29973, "text": null }, { "code": "# Python3 program to find modulo of floating# point numbers using library function.from math import fmod # Driver codeif __name__ == '__main__': a = 9.7 b = 2.3 print(fmod(a, b)) # This code is contributed by mohit kumar 29", "e": 30487, "s": 30244, "text": null }, { "code": "// C# program to find modulo of floating// point numbers using library function.using System; class GFG{ static void Main(){ double a = 9.7; double b = 2.3; Console.WriteLine(a % b);}} // This code is contributed by mukesh07", "e": 30723, "s": 30487, "text": null }, { "code": "<?php// PHP program to find modulo of// floating point numbers using// library function. // Driver Code$a = 9.7; $b = 2.3;echo fmod($a, $b); // This code is contributed// by inder_verma?>", "e": 30911, "s": 30723, "text": null }, { "code": "<script> // Javascript program to find modulo of// floating point numbers using// library function. // Driver Codelet a = 9.7;let b = 2.3;document.write(a%b); // This code is contributed by mohan pavan </script>", "e": 31123, "s": 30911, "text": null }, { "code": null, "e": 31132, "s": 31123, "text": "Output: " }, { "code": null, "e": 31136, "s": 31132, "text": "0.5" }, { "code": null, "e": 31143, "s": 31138, "text": "vt_m" }, { "code": null, "e": 31154, "s": 31143, "text": "inderDuMCA" }, { "code": null, "e": 31167, "s": 31154, "text": "rameshmarisa" }, { "code": null, "e": 31182, "s": 31167, "text": "mohit kumar 29" }, { "code": null, "e": 31198, "s": 31182, "text": "mayanktyagi1709" }, { "code": null, "e": 31215, "s": 31198, "text": "pulamolusaimohan" }, { "code": null, "e": 31227, "s": 31215, "text": "umadevi9616" }, { "code": null, "e": 31236, "s": 31227, "text": "mukesh07" }, { "code": null, "e": 31248, "s": 31236, "text": "CPP-Library" }, { "code": null, "e": 31267, "s": 31248, "text": "Modular Arithmetic" }, { "code": null, "e": 31278, "s": 31267, "text": "C Language" }, { "code": null, "e": 31282, "s": 31278, "text": "C++" }, { "code": null, "e": 31301, "s": 31282, "text": "Technical Scripter" }, { "code": null, "e": 31320, "s": 31301, "text": "Modular Arithmetic" }, { "code": null, "e": 31324, "s": 31320, "text": "CPP" }, { "code": null, "e": 31422, "s": 31324, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31439, "s": 31422, "text": "Substring in C++" }, { "code": null, "e": 31474, "s": 31439, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 31513, "s": 31474, "text": "Converting Strings to Numbers in C/C++" }, { "code": null, "e": 31559, "s": 31513, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 31581, "s": 31559, "text": "Function Pointer in C" }, { "code": null, "e": 31599, "s": 31581, "text": "Vector in C++ STL" }, { "code": null, "e": 31645, "s": 31599, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 31664, "s": 31645, "text": "Inheritance in C++" }, { "code": null, "e": 31707, "s": 31664, "text": "Map in C++ Standard Template Library (STL)" } ]
Working with Excel Files in Julia - GeeksforGeeks
25 Aug, 2020 Julia is a high-level open-source programming language meaning that its source is freely available. It is a language that is used to perform operations in scientific computing. Julia is used for statistical computations and data analysis. Julia provides its users with some pre-defined functions and built-in packages with the help of which Julia makes it possible to work with Excel Files, that too with quite an easiness. With the help of Packages, Julia makes is easier to Read an Excel File. First, the package that is needed to be added to get its functionality for reading the Excel file is XLSX.jl package All the packages can be added with passing it as an argument in the add(” “) function which is present in the Pkg object Pkg.add("") To read one row at a time from an Excel File, Julia provides a function eachrow() to iterate over each row of the file and store the same in a variable. Approach: First, add the package XLSX Open the file using openxlsx() function with arguments passed in strings as the name of the file, accessing the cached memory. Now we will traverse the sheet in which our data is stored with the help of a loop and a variable to store(sheet) while passing. Now to access each row of the table we need to iterate row by row with help of function named eachrow() passing sheet as an argument in it. The variable to iterate used by for loop is known as ‘SheetRow‘ values are read using column references. row_number(iterating_variable) function is used to access the row number and the iterating variable is passed in it which will help in traversing. Now to read the referenced column the variable passed should have its argument having the same type as the values contained in the particular header and stored in another variable. r[“B”] for string,r[1] for int values etc. Now just print the variable in which these data are stored and ending both the loops Julia using PkgPkg.add("XLSX")XLSX.openxlsx("sample1.xlsx", enable_cache=false) do f sheet = f["Sheet1"] for r in XLSX.eachrow(sheet) # r is a `SheetRow`, values are read # using column references rn = XLSX.row_number(r) # `SheetRow` row number v1 = r[1] # will read value at column 1 v2 = r[2]# will read value at column 2 v3 = r["B"] v4 = r[3] println("v1=$v1, v2=$v2, v3=$v3, v4=$v4") endend Julia provides a function readxlsx() to read all the contents of a file in a single attempt. Approach: First, add the package Pkg Then add the XLSX package using add function and passing the package name as the argument The file can be read with the output of its all information by a function readxlsx() which reads the xlsx files Now this function returns the dimension of all the sheets inside the xlsx file. These dimension of all the sheets can be stored in a separate variable and then it can be accessed by passing a string. Now the separate variable’s all data in this sheet passed can be viewed with double colon which gives access to read all the data inside this particular sheet. Julia using PkgPkg.add("XLSX")import XLSXxf = XLSX.readxlsx("sample3.xlsx") Julia sh = xf["Sheet1"]sh[:] Modification of contents of an Excel File can be done by opening the file in the ‘rw’ i.e. Read-write mode and then further updating the values with the help of iterator. Approach: First, add the package Pkg Now add the package XLSX using add function Now open the file in the ‘rw‘ mode to make changes in the existing file. Now traverse with sheet variable with help of a loop Now pass the row number into the sheet variable to access the row Replace it with the new number or string END the loop using ‘end’. Julia # Modifying contents of a fileusing PkgPkg.add("XLSX")XLSX.openxlsx("sample3.xlsx", mode="rw") do xf sheet = xf[1] sheet["B2"] = "March" #row number = B2end The addition of columns in an Excel File is done by opening the file in ‘rw’ mode and then using the collect() function. Approach: First, add the packages Pkg, XLSX, and DataFrames. Now open the file in the ‘rw‘ mode means editing an existing file Now traverse the sheet using variable Pass the arguments as the column number in which you want to add the column and the dimension And pass the function collect passing arguments in it telling the range Then end the loop Julia # Only 10 columns are presentdf2 = DataFrame(XLSX.readtable("sample2.xlsx", "Sheet1")...) # add a new column to an existing file # and makes it 11 columnsXLSX.openxlsx("sample2.xlsx", mode="rw") do xf sheet = xf[1] # add a column from "K1" to "K3" sheet["K1", dim=1] = collect(1:3)end The deletion of contents from an Excel File can be done by using the setdiff() function. This function compares all the rows and removes the row that is passed as an argument. Approach: First tell the row that is needed to be deleted. Now in the same DataFrames ‘df’ pass the arguments using setdiff() function in which it reads all the rows from starting and deletes the row passed. Julia # deleting from an existing columnrow = 2df = df[setdiff(1:end, row), :] Original File: Updated File: Julia provides a function append() to perform the append operation to files. This function takes both the dataframes as an argument and returns the appended dataframe. Approach: To append the file use the append() function passing the DataFrames (df2,df3) as arguments The append() function works as adding the df2 dataframe at the back of df3 dataframe But remember the columns should be the same in both the dataframes (df2,df3) Julia # Only 10 columns are presentdf2 = DataFrame(XLSX.readtable("sample2.xlsx", "Sheet1")...) # Add a new column to an existing file # and makes it 11 columnsXLSX.openxlsx("sample2.xlsx", mode="rw") do xf sheet = xf[1] # will add a column from "K1" to "K3" sheet["K1", dim=1] = collect(1:3)end # Updated columns and stored in new dataframe df3df3 = DataFrame(XLSX.readtable("sample2.xlsx", "Sheet1")...) # Appended df2 rows to the end of df3 # with same column namesdf3 = append!(df2,df3) To write contents to a new Excel file, open the file in the ‘w’ i.e. write mode and then use the collect() function to add columns to the files and further assign the values to be added to the variables. Approach: First, open the file in the writing mode ‘w’ and start the loop Now to add a row to the new file give the row number as an argument in the sheet variable and pass the collect function giving range till which we want a row and pass them as arguments Now to add the column to the file pass the row number and dimension as 1 for column Pass the collect() function into the sheet variable and pass range in the collect() function till which we want our column, on the particular row number Now pass a matrix of numbers in the sheet variable separated by semicolon(;) in square brackets and pass the row numbers range in the sheet variable till which we want our matrix. Julia # Writing a new xlsx file and # the mode is w means(write)# and created a new one.XLSX.openxlsx("sample5.xlsx", mode="w") do xf sheet = xf[1] # add a row from "A5" to "E5" # equivalent to `sheet["A5", dim=2] = collect(1:4)` sheet["A5"] = collect(1:5) # will add a column from "B1" to "B4" sheet["B1", dim=1] = collect(1:3) # will add a matrix from "A7" to "C9" sheet["A7:C9"] = [ 1 2 3 ; 4 5 6 ; 7 8 9 ]end julia-FileHandling Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Vectors in Julia String to Number Conversion in Julia String concatenation in Julia Getting rounded value of a number in Julia - round() Method Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder) Storing Output on a File in Julia Formatting of Strings in Julia Manipulating matrices in Julia Creating array with repeated elements in Julia - repeat() Method while loop in Julia
[ { "code": null, "e": 25659, "s": 25631, "text": "\n25 Aug, 2020" }, { "code": null, "e": 26083, "s": 25659, "text": "Julia is a high-level open-source programming language meaning that its source is freely available. It is a language that is used to perform operations in scientific computing. Julia is used for statistical computations and data analysis. Julia provides its users with some pre-defined functions and built-in packages with the help of which Julia makes it possible to work with Excel Files, that too with quite an easiness." }, { "code": null, "e": 26256, "s": 26083, "text": "With the help of Packages, Julia makes is easier to Read an Excel File. First, the package that is needed to be added to get its functionality for reading the Excel file is" }, { "code": null, "e": 26273, "s": 26256, "text": "XLSX.jl package\n" }, { "code": null, "e": 26394, "s": 26273, "text": "All the packages can be added with passing it as an argument in the add(” “) function which is present in the Pkg object" }, { "code": null, "e": 26407, "s": 26394, "text": "Pkg.add(\"\")\n" }, { "code": null, "e": 26560, "s": 26407, "text": "To read one row at a time from an Excel File, Julia provides a function eachrow() to iterate over each row of the file and store the same in a variable." }, { "code": null, "e": 26570, "s": 26560, "text": "Approach:" }, { "code": null, "e": 26598, "s": 26570, "text": "First, add the package XLSX" }, { "code": null, "e": 26725, "s": 26598, "text": "Open the file using openxlsx() function with arguments passed in strings as the name of the file, accessing the cached memory." }, { "code": null, "e": 26854, "s": 26725, "text": "Now we will traverse the sheet in which our data is stored with the help of a loop and a variable to store(sheet) while passing." }, { "code": null, "e": 26994, "s": 26854, "text": "Now to access each row of the table we need to iterate row by row with help of function named eachrow() passing sheet as an argument in it." }, { "code": null, "e": 27099, "s": 26994, "text": "The variable to iterate used by for loop is known as ‘SheetRow‘ values are read using column references." }, { "code": null, "e": 27246, "s": 27099, "text": "row_number(iterating_variable) function is used to access the row number and the iterating variable is passed in it which will help in traversing." }, { "code": null, "e": 27470, "s": 27246, "text": "Now to read the referenced column the variable passed should have its argument having the same type as the values contained in the particular header and stored in another variable. r[“B”] for string,r[1] for int values etc." }, { "code": null, "e": 27555, "s": 27470, "text": "Now just print the variable in which these data are stored and ending both the loops" }, { "code": null, "e": 27561, "s": 27555, "text": "Julia" }, { "code": "using PkgPkg.add(\"XLSX\")XLSX.openxlsx(\"sample1.xlsx\", enable_cache=false) do f sheet = f[\"Sheet1\"] for r in XLSX.eachrow(sheet) # r is a `SheetRow`, values are read # using column references rn = XLSX.row_number(r) # `SheetRow` row number v1 = r[1] # will read value at column 1 v2 = r[2]# will read value at column 2 v3 = r[\"B\"] v4 = r[3] println(\"v1=$v1, v2=$v2, v3=$v3, v4=$v4\") endend", "e": 27983, "s": 27561, "text": null }, { "code": null, "e": 28132, "s": 28039, "text": "Julia provides a function readxlsx() to read all the contents of a file in a single attempt." }, { "code": null, "e": 28143, "s": 28132, "text": "Approach: " }, { "code": null, "e": 28170, "s": 28143, "text": "First, add the package Pkg" }, { "code": null, "e": 28260, "s": 28170, "text": "Then add the XLSX package using add function and passing the package name as the argument" }, { "code": null, "e": 28373, "s": 28260, "text": "The file can be read with the output of its all information by a function readxlsx() which reads the xlsx files" }, { "code": null, "e": 28453, "s": 28373, "text": "Now this function returns the dimension of all the sheets inside the xlsx file." }, { "code": null, "e": 28573, "s": 28453, "text": "These dimension of all the sheets can be stored in a separate variable and then it can be accessed by passing a string." }, { "code": null, "e": 28733, "s": 28573, "text": "Now the separate variable’s all data in this sheet passed can be viewed with double colon which gives access to read all the data inside this particular sheet." }, { "code": null, "e": 28739, "s": 28733, "text": "Julia" }, { "code": "using PkgPkg.add(\"XLSX\")import XLSXxf = XLSX.readxlsx(\"sample3.xlsx\")", "e": 28809, "s": 28739, "text": null }, { "code": null, "e": 28815, "s": 28809, "text": "Julia" }, { "code": "sh = xf[\"Sheet1\"]sh[:]", "e": 28838, "s": 28815, "text": null }, { "code": null, "e": 29009, "s": 28838, "text": "Modification of contents of an Excel File can be done by opening the file in the ‘rw’ i.e. Read-write mode and then further updating the values with the help of iterator." }, { "code": null, "e": 29019, "s": 29009, "text": "Approach:" }, { "code": null, "e": 29046, "s": 29019, "text": "First, add the package Pkg" }, { "code": null, "e": 29090, "s": 29046, "text": "Now add the package XLSX using add function" }, { "code": null, "e": 29163, "s": 29090, "text": "Now open the file in the ‘rw‘ mode to make changes in the existing file." }, { "code": null, "e": 29216, "s": 29163, "text": "Now traverse with sheet variable with help of a loop" }, { "code": null, "e": 29282, "s": 29216, "text": "Now pass the row number into the sheet variable to access the row" }, { "code": null, "e": 29323, "s": 29282, "text": "Replace it with the new number or string" }, { "code": null, "e": 29349, "s": 29323, "text": "END the loop using ‘end’." }, { "code": null, "e": 29355, "s": 29349, "text": "Julia" }, { "code": "# Modifying contents of a fileusing PkgPkg.add(\"XLSX\")XLSX.openxlsx(\"sample3.xlsx\", mode=\"rw\") do xf sheet = xf[1] sheet[\"B2\"] = \"March\" #row number = B2end", "e": 29518, "s": 29355, "text": null }, { "code": null, "e": 29639, "s": 29518, "text": "The addition of columns in an Excel File is done by opening the file in ‘rw’ mode and then using the collect() function." }, { "code": null, "e": 29649, "s": 29639, "text": "Approach:" }, { "code": null, "e": 29700, "s": 29649, "text": "First, add the packages Pkg, XLSX, and DataFrames." }, { "code": null, "e": 29766, "s": 29700, "text": "Now open the file in the ‘rw‘ mode means editing an existing file" }, { "code": null, "e": 29804, "s": 29766, "text": "Now traverse the sheet using variable" }, { "code": null, "e": 29898, "s": 29804, "text": "Pass the arguments as the column number in which you want to add the column and the dimension" }, { "code": null, "e": 29970, "s": 29898, "text": "And pass the function collect passing arguments in it telling the range" }, { "code": null, "e": 29988, "s": 29970, "text": "Then end the loop" }, { "code": null, "e": 29994, "s": 29988, "text": "Julia" }, { "code": "# Only 10 columns are presentdf2 = DataFrame(XLSX.readtable(\"sample2.xlsx\", \"Sheet1\")...) # add a new column to an existing file # and makes it 11 columnsXLSX.openxlsx(\"sample2.xlsx\", mode=\"rw\") do xf sheet = xf[1] # add a column from \"K1\" to \"K3\" sheet[\"K1\", dim=1] = collect(1:3)end", "e": 30295, "s": 29994, "text": null }, { "code": null, "e": 30471, "s": 30295, "text": "The deletion of contents from an Excel File can be done by using the setdiff() function. This function compares all the rows and removes the row that is passed as an argument." }, { "code": null, "e": 30481, "s": 30471, "text": "Approach:" }, { "code": null, "e": 30530, "s": 30481, "text": "First tell the row that is needed to be deleted." }, { "code": null, "e": 30679, "s": 30530, "text": "Now in the same DataFrames ‘df’ pass the arguments using setdiff() function in which it reads all the rows from starting and deletes the row passed." }, { "code": null, "e": 30685, "s": 30679, "text": "Julia" }, { "code": "# deleting from an existing columnrow = 2df = df[setdiff(1:end, row), :]", "e": 30758, "s": 30685, "text": null }, { "code": null, "e": 30773, "s": 30758, "text": "Original File:" }, { "code": null, "e": 30787, "s": 30773, "text": "Updated File:" }, { "code": null, "e": 30955, "s": 30787, "text": "Julia provides a function append() to perform the append operation to files. This function takes both the dataframes as an argument and returns the appended dataframe." }, { "code": null, "e": 30965, "s": 30955, "text": "Approach:" }, { "code": null, "e": 31056, "s": 30965, "text": "To append the file use the append() function passing the DataFrames (df2,df3) as arguments" }, { "code": null, "e": 31141, "s": 31056, "text": "The append() function works as adding the df2 dataframe at the back of df3 dataframe" }, { "code": null, "e": 31218, "s": 31141, "text": "But remember the columns should be the same in both the dataframes (df2,df3)" }, { "code": null, "e": 31224, "s": 31218, "text": "Julia" }, { "code": "# Only 10 columns are presentdf2 = DataFrame(XLSX.readtable(\"sample2.xlsx\", \"Sheet1\")...) # Add a new column to an existing file # and makes it 11 columnsXLSX.openxlsx(\"sample2.xlsx\", mode=\"rw\") do xf sheet = xf[1] # will add a column from \"K1\" to \"K3\" sheet[\"K1\", dim=1] = collect(1:3)end # Updated columns and stored in new dataframe df3df3 = DataFrame(XLSX.readtable(\"sample2.xlsx\", \"Sheet1\")...) # Appended df2 rows to the end of df3 # with same column namesdf3 = append!(df2,df3)", "e": 31727, "s": 31224, "text": null }, { "code": null, "e": 31983, "s": 31779, "text": "To write contents to a new Excel file, open the file in the ‘w’ i.e. write mode and then use the collect() function to add columns to the files and further assign the values to be added to the variables." }, { "code": null, "e": 31993, "s": 31983, "text": "Approach:" }, { "code": null, "e": 32057, "s": 31993, "text": "First, open the file in the writing mode ‘w’ and start the loop" }, { "code": null, "e": 32242, "s": 32057, "text": "Now to add a row to the new file give the row number as an argument in the sheet variable and pass the collect function giving range till which we want a row and pass them as arguments" }, { "code": null, "e": 32326, "s": 32242, "text": "Now to add the column to the file pass the row number and dimension as 1 for column" }, { "code": null, "e": 32479, "s": 32326, "text": "Pass the collect() function into the sheet variable and pass range in the collect() function till which we want our column, on the particular row number" }, { "code": null, "e": 32660, "s": 32479, "text": "Now pass a matrix of numbers in the sheet variable separated by semicolon(;) in square brackets and pass the row numbers range in the sheet variable till which we want our matrix." }, { "code": null, "e": 32666, "s": 32660, "text": "Julia" }, { "code": "# Writing a new xlsx file and # the mode is w means(write)# and created a new one.XLSX.openxlsx(\"sample5.xlsx\", mode=\"w\") do xf sheet = xf[1] # add a row from \"A5\" to \"E5\" # equivalent to `sheet[\"A5\", dim=2] = collect(1:4)` sheet[\"A5\"] = collect(1:5) # will add a column from \"B1\" to \"B4\" sheet[\"B1\", dim=1] = collect(1:3) # will add a matrix from \"A7\" to \"C9\" sheet[\"A7:C9\"] = [ 1 2 3 ; 4 5 6 ; 7 8 9 ]end", "e": 33107, "s": 32666, "text": null }, { "code": null, "e": 33126, "s": 33107, "text": "julia-FileHandling" }, { "code": null, "e": 33132, "s": 33126, "text": "Julia" }, { "code": null, "e": 33230, "s": 33132, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33247, "s": 33230, "text": "Vectors in Julia" }, { "code": null, "e": 33284, "s": 33247, "text": "String to Number Conversion in Julia" }, { "code": null, "e": 33314, "s": 33284, "text": "String concatenation in Julia" }, { "code": null, "e": 33374, "s": 33314, "text": "Getting rounded value of a number in Julia - round() Method" }, { "code": null, "e": 33447, "s": 33374, "text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)" }, { "code": null, "e": 33481, "s": 33447, "text": "Storing Output on a File in Julia" }, { "code": null, "e": 33512, "s": 33481, "text": "Formatting of Strings in Julia" }, { "code": null, "e": 33543, "s": 33512, "text": "Manipulating matrices in Julia" }, { "code": null, "e": 33608, "s": 33543, "text": "Creating array with repeated elements in Julia - repeat() Method" } ]
XML-RPC - Response Format
Responses are much like requests, with a few extra twists. If the response is successful - the procedure was found, executed correctly, and returned results - then the XML-RPC response will look much like a request, except that the methodCall element is replaced by a methodResponse element and there is no methodName element: <?xml version="1.0"?> <methodResponse> <params> <param> <value><double>18.24668429131</double></value> </param> </params> </methodResponse> An XML-RPC response can only contain one parameter. An XML-RPC response can only contain one parameter. That parameter may be an array or a struct, so it is possible to return multiple values. That parameter may be an array or a struct, so it is possible to return multiple values. It is always required to return a value in response. A "success value" - perhaps a Boolean set to true (1). It is always required to return a value in response. A "success value" - perhaps a Boolean set to true (1). Like requests, responses are packaged in HTTP and have HTTP headers. All XML-RPC responses use the 200 OK response code, even if a fault is contained in the message. Headers use a common structure similar to that of requests, and a typical set of headers might look like: HTTP/1.1 200 OK Date: Sat, 06 Oct 2001 23:20:04 GMT Server: Apache.1.3.12 (Unix) Connection: close Content-Type: text/xml Content-Length: 124 XML-RPC only requires HTTP 1.0 support, but HTTP 1.1 is compatible. XML-RPC only requires HTTP 1.0 support, but HTTP 1.1 is compatible. The Content-Type must be set to text/xml. The Content-Type must be set to text/xml. The Content-Length header specifies the length of the response in bytes. The Content-Length header specifies the length of the response in bytes. A complete response, with both headers and a response payload, would look like: HTTP/1.1 200 OK Date: Sat, 06 Oct 2001 23:20:04 GMT Server: Apache.1.3.12 (Unix) Connection: close Content-Type: text/xml Content-Length: 124 <?xml version="1.0"?> <methodResponse> <params> <param> <value><double>18.24668429131</double></value> </param> </params> </methodResponse> After the response is delivered from the XML-RPC server to the XML-RPC client, the connection is closed. Follow-up requests need to be sent as separate XML-RPC connections. Print Add Notes Bookmark this page
[ { "code": null, "e": 2011, "s": 1684, "text": "Responses are much like requests, with a few extra twists. If the response is successful - the procedure was found, executed correctly, and returned results - then the XML-RPC response will look much like a request, except that the methodCall element is replaced by a methodResponse element and there is no methodName element:" }, { "code": null, "e": 2178, "s": 2011, "text": "<?xml version=\"1.0\"?>\n<methodResponse>\n <params>\n <param>\n <value><double>18.24668429131</double></value>\n </param>\n </params>\n</methodResponse>" }, { "code": null, "e": 2230, "s": 2178, "text": "An XML-RPC response can only contain one parameter." }, { "code": null, "e": 2282, "s": 2230, "text": "An XML-RPC response can only contain one parameter." }, { "code": null, "e": 2371, "s": 2282, "text": "That parameter may be an array or a struct, so it is possible to return multiple values." }, { "code": null, "e": 2460, "s": 2371, "text": "That parameter may be an array or a struct, so it is possible to return multiple values." }, { "code": null, "e": 2568, "s": 2460, "text": "It is always required to return a value in response. A \"success value\" - perhaps a Boolean set to true (1)." }, { "code": null, "e": 2676, "s": 2568, "text": "It is always required to return a value in response. A \"success value\" - perhaps a Boolean set to true (1)." }, { "code": null, "e": 2948, "s": 2676, "text": "Like requests, responses are packaged in HTTP and have HTTP headers. All XML-RPC\nresponses use the 200 OK response code, even if a fault is contained in the message.\nHeaders use a common structure similar to that of requests, and a typical set of headers\nmight look like:" }, { "code": null, "e": 3091, "s": 2948, "text": "HTTP/1.1 200 OK\nDate: Sat, 06 Oct 2001 23:20:04 GMT\nServer: Apache.1.3.12 (Unix)\nConnection: close\nContent-Type: text/xml\nContent-Length: 124\n" }, { "code": null, "e": 3159, "s": 3091, "text": "XML-RPC only requires HTTP 1.0 support, but HTTP 1.1 is compatible." }, { "code": null, "e": 3227, "s": 3159, "text": "XML-RPC only requires HTTP 1.0 support, but HTTP 1.1 is compatible." }, { "code": null, "e": 3269, "s": 3227, "text": "The Content-Type must be set to text/xml." }, { "code": null, "e": 3311, "s": 3269, "text": "The Content-Type must be set to text/xml." }, { "code": null, "e": 3384, "s": 3311, "text": "The Content-Length header specifies the length of the response in bytes." }, { "code": null, "e": 3457, "s": 3384, "text": "The Content-Length header specifies the length of the response in bytes." }, { "code": null, "e": 3537, "s": 3457, "text": "A complete response, with both headers and a response payload, would look like:" }, { "code": null, "e": 3847, "s": 3537, "text": "HTTP/1.1 200 OK\nDate: Sat, 06 Oct 2001 23:20:04 GMT\nServer: Apache.1.3.12 (Unix)\nConnection: close\nContent-Type: text/xml\nContent-Length: 124\n\n<?xml version=\"1.0\"?>\n<methodResponse>\n <params>\n <param>\n <value><double>18.24668429131</double></value>\n </param>\n </params>\n</methodResponse>" }, { "code": null, "e": 4020, "s": 3847, "text": "After the response is delivered from the XML-RPC server to the XML-RPC client, the connection is closed. Follow-up requests need to be sent as separate XML-RPC connections." }, { "code": null, "e": 4027, "s": 4020, "text": " Print" }, { "code": null, "e": 4038, "s": 4027, "text": " Add Notes" } ]
How to get element with max id in MongoDB?
To get the element with a max id, you can use the find() method. To understand the above concept, let us create a collection with the document. The query is as follows − > db.getElementWithMaxIdDemo.insertOne({"Name":"John","Age":21}); { "acknowledged" : true, "insertedId" : ObjectId("5c8bbce480f10143d8431e1c") } > db.getElementWithMaxIdDemo.insertOne({"Name":"Larry","Age":24}); { "acknowledged" : true, "insertedId" : ObjectId("5c8bbcec80f10143d8431e1d") } > db.getElementWithMaxIdDemo.insertOne({"Name":"David","Age":23}); { "acknowledged" : true, "insertedId" : ObjectId("5c8bbcf580f10143d8431e1e") } > db.getElementWithMaxIdDemo.insertOne({"Name":"Chris","Age":20}); { "acknowledged" : true, "insertedId" : ObjectId("5c8bbcfe80f10143d8431e1f") } > db.getElementWithMaxIdDemo.insertOne({"Name":"Robert","Age":25}); { "acknowledged" : true, "insertedId" : ObjectId("5c8bbd0880f10143d8431e20") } Display all documents from a collection with the help of find() method. The query is as follows − > db.getElementWithMaxIdDemo.find().pretty(); The following is the output − { "_id" : ObjectId("5c8bbce480f10143d8431e1c"), "Name" : "John", "Age" : 21 } { "_id" : ObjectId("5c8bbcec80f10143d8431e1d"), "Name" : "Larry", "Age" : 24 } { "_id" : ObjectId("5c8bbcf580f10143d8431e1e"), "Name" : "David", "Age" : 23 } { "_id" : ObjectId("5c8bbcfe80f10143d8431e1f"), "Name" : "Chris", "Age" : 20 } { "_id" : ObjectId("5c8bbd0880f10143d8431e20"), "Name" : "Robert", "Age" : 25 } Here is the query to get the element with max id − > db.getElementWithMaxIdDemo.find().sort({_id:-1}).limit(1).pretty() The following is the output with a record with maximum id − { "_id" : ObjectId("5c8bbd0880f10143d8431e20"), "Name" : "Robert", "Age" : 25 }
[ { "code": null, "e": 1232, "s": 1062, "text": "To get the element with a max id, you can use the find() method. To understand the above concept, let us create a collection with the document. The query is as follows −" }, { "code": null, "e": 1992, "s": 1232, "text": "> db.getElementWithMaxIdDemo.insertOne({\"Name\":\"John\",\"Age\":21});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8bbce480f10143d8431e1c\")\n}\n> db.getElementWithMaxIdDemo.insertOne({\"Name\":\"Larry\",\"Age\":24});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8bbcec80f10143d8431e1d\")\n}\n> db.getElementWithMaxIdDemo.insertOne({\"Name\":\"David\",\"Age\":23});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8bbcf580f10143d8431e1e\")\n}\n> db.getElementWithMaxIdDemo.insertOne({\"Name\":\"Chris\",\"Age\":20});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8bbcfe80f10143d8431e1f\")\n}\n> db.getElementWithMaxIdDemo.insertOne({\"Name\":\"Robert\",\"Age\":25});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8bbd0880f10143d8431e20\")\n}" }, { "code": null, "e": 2090, "s": 1992, "text": "Display all documents from a collection with the help of find() method. The query is as follows −" }, { "code": null, "e": 2136, "s": 2090, "text": "> db.getElementWithMaxIdDemo.find().pretty();" }, { "code": null, "e": 2166, "s": 2136, "text": "The following is the output −" }, { "code": null, "e": 2606, "s": 2166, "text": "{\n \"_id\" : ObjectId(\"5c8bbce480f10143d8431e1c\"),\n \"Name\" : \"John\",\n \"Age\" : 21\n}\n{\n \"_id\" : ObjectId(\"5c8bbcec80f10143d8431e1d\"),\n \"Name\" : \"Larry\",\n \"Age\" : 24\n}\n{\n \"_id\" : ObjectId(\"5c8bbcf580f10143d8431e1e\"),\n \"Name\" : \"David\",\n \"Age\" : 23\n}\n{\n \"_id\" : ObjectId(\"5c8bbcfe80f10143d8431e1f\"),\n \"Name\" : \"Chris\",\n \"Age\" : 20\n}\n{\n \"_id\" : ObjectId(\"5c8bbd0880f10143d8431e20\"),\n \"Name\" : \"Robert\",\n \"Age\" : 25\n}" }, { "code": null, "e": 2657, "s": 2606, "text": "Here is the query to get the element with max id −" }, { "code": null, "e": 2726, "s": 2657, "text": "> db.getElementWithMaxIdDemo.find().sort({_id:-1}).limit(1).pretty()" }, { "code": null, "e": 2786, "s": 2726, "text": "The following is the output with a record with maximum id −" }, { "code": null, "e": 2875, "s": 2786, "text": "{\n \"_id\" : ObjectId(\"5c8bbd0880f10143d8431e20\"),\n \"Name\" : \"Robert\",\n \"Age\" : 25\n}" } ]
How to change axes background color in Matplotlib?
To change the axes background color, we can use set_facecolor() method. Set the figure size and adjust the padding between and around the subplots. Set the figure size and adjust the padding between and around the subplots. Get the current axes using gca() method. Get the current axes using gca() method. Set the facecolor of the axes. Set the facecolor of the axes. Create x and y data points using numpy. Create x and y data points using numpy. Plot x and y data points using plot() method. Plot x and y data points using plot() method. To display the figure, use show() method. To display the figure, use show() method. import numpy as np import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True ax = plt.gca() ax.set_facecolor("orange") x = np.linspace(-2, 2, 10) y = np.exp(-x) plt.plot(x, y, color='red') plt.show()
[ { "code": null, "e": 1134, "s": 1062, "text": "To change the axes background color, we can use set_facecolor() method." }, { "code": null, "e": 1210, "s": 1134, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1286, "s": 1210, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1327, "s": 1286, "text": "Get the current axes using gca() method." }, { "code": null, "e": 1368, "s": 1327, "text": "Get the current axes using gca() method." }, { "code": null, "e": 1399, "s": 1368, "text": "Set the facecolor of the axes." }, { "code": null, "e": 1430, "s": 1399, "text": "Set the facecolor of the axes." }, { "code": null, "e": 1470, "s": 1430, "text": "Create x and y data points using numpy." }, { "code": null, "e": 1510, "s": 1470, "text": "Create x and y data points using numpy." }, { "code": null, "e": 1556, "s": 1510, "text": "Plot x and y data points using plot() method." }, { "code": null, "e": 1602, "s": 1556, "text": "Plot x and y data points using plot() method." }, { "code": null, "e": 1644, "s": 1602, "text": "To display the figure, use show() method." }, { "code": null, "e": 1686, "s": 1644, "text": "To display the figure, use show() method." }, { "code": null, "e": 1952, "s": 1686, "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nax = plt.gca()\nax.set_facecolor(\"orange\")\n\nx = np.linspace(-2, 2, 10)\ny = np.exp(-x)\n\nplt.plot(x, y, color='red')\n\nplt.show()" } ]
GATE | GATE CS Mock 2018 | Question 50 - GeeksforGeeks
19 Nov, 2018 Consider an array A[999] & each element occupies 4 word. A 32 word cache is used and divided into 16 word blocks. What is the miss ratio for the following statement. Assume one block is read into cache in case of miss: for(i=0; i < 1000; i++) A[i] = A[i] + 99 (A) 0.50(B) 0.75(C) 0.875(D) 0.125Answer: (D)Explanation: Since there is 16 word block, 4 element can stay in one block. Now notice that each element is referred twice, one read and one write operation.So when in a block when 1st element is referred for read, it will be miss, and hence that block will be copied to cache.Now 2nd, 3rd, and 4th references to that 1st element will be hit for read and write. So out of 8 reference, 1 miss and 7 hit for one block. Gets repeated for each and every block.Therefore, hit 7/8 and miss 1/8 Option (D) is correct.Quiz of this Question GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2014-(Set-1) | Question 30 GATE | GATE-CS-2001 | Question 23 GATE | GATE-CS-2015 (Set 1) | Question 65 GATE | GATE CS 2010 | Question 45 GATE | GATE-CS-2014-(Set-1) | Question 65 GATE | GATE-CS-2004 | Question 3 GATE | GATE-CS-2015 (Set 3) | Question 65 C++ Program to count Vowels in a string using Pointer GATE | GATE CS 2012 | Question 40
[ { "code": null, "e": 24087, "s": 24059, "text": "\n19 Nov, 2018" }, { "code": null, "e": 24306, "s": 24087, "text": "Consider an array A[999] & each element occupies 4 word. A 32 word cache is used and divided into 16 word blocks. What is the miss ratio for the following statement. Assume one block is read into cache in case of miss:" }, { "code": null, "e": 24350, "s": 24306, "text": "for(i=0; i < 1000; i++)\n A[i] = A[i] + 99\n" }, { "code": null, "e": 24883, "s": 24350, "text": "(A) 0.50(B) 0.75(C) 0.875(D) 0.125Answer: (D)Explanation: Since there is 16 word block, 4 element can stay in one block. Now notice that each element is referred twice, one read and one write operation.So when in a block when 1st element is referred for read, it will be miss, and hence that block will be copied to cache.Now 2nd, 3rd, and 4th references to that 1st element will be hit for read and write. So out of 8 reference, 1 miss and 7 hit for one block. Gets repeated for each and every block.Therefore, hit 7/8 and miss 1/8" }, { "code": null, "e": 24927, "s": 24883, "text": "Option (D) is correct.Quiz of this Question" }, { "code": null, "e": 24932, "s": 24927, "text": "GATE" }, { "code": null, "e": 25030, "s": 24932, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25039, "s": 25030, "text": "Comments" }, { "code": null, "e": 25052, "s": 25039, "text": "Old Comments" }, { "code": null, "e": 25094, "s": 25052, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 25136, "s": 25094, "text": "GATE | GATE-CS-2014-(Set-1) | Question 30" }, { "code": null, "e": 25170, "s": 25136, "text": "GATE | GATE-CS-2001 | Question 23" }, { "code": null, "e": 25212, "s": 25170, "text": "GATE | GATE-CS-2015 (Set 1) | Question 65" }, { "code": null, "e": 25246, "s": 25212, "text": "GATE | GATE CS 2010 | Question 45" }, { "code": null, "e": 25288, "s": 25246, "text": "GATE | GATE-CS-2014-(Set-1) | Question 65" }, { "code": null, "e": 25321, "s": 25288, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 25363, "s": 25321, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 25417, "s": 25363, "text": "C++ Program to count Vowels in a string using Pointer" } ]
Abstract Methods in Java with Examples - GeeksforGeeks
26 Dec, 2020 Sometimes, we require just method declaration in super-classes. This can be achieve by specifying the abstract type modifier. These methods are sometimes referred to as subclasser responsibility because they have no implementation specified in the super-class. Thus, a subclass must override them to provide method definition. To declare an abstract method, use this general form: abstract type method-name(parameter-list); As you can see, no method body is present. Any concrete class(i.e. class without abstract keyword) that extends an abstract class must override all the abstract methods of the class.Important rules for abstract methods: Any class that contains one or more abstract methods must also be declared abstract The following are various illegal combinations of other modifiers for methods with respect to abstract modifier: finalabstract nativeabstract synchronizedabstract staticabstract privateabstract strictfp finalabstract nativeabstract synchronizedabstract staticabstract privateabstract strictfp final abstract native abstract synchronized abstract static abstract private abstract strictfp Consider the following Java program, that illustrate the use of abstract keyword with classes and methods. Java // A java program to demonstrate// use of abstract keyword. // abstract classabstract class A { // abstract method // it has no body abstract void m1(); // concrete methods are still // allowed in abstract classes void m2() { System.out.println("This is " + "a concrete method."); }} // concrete class Bclass B extends A { // class B must override m1() method // otherwise, compile-time // exception will be thrown void m1() { System.out.println("B's " + "implementation of m1."); }} // Driver classpublic class AbstractDemo { public static void main(String args[]) { B b = new B(); b.m1(); b.m2(); }} Output: B's implementation of m1. This is a concrete method. Note: Although abstract classes cannot be used to instantiate objects, they can be used to create object references, because Java’s approach to run-time polymorphism is implemented through the use of super-class references. Thus, it must be possible to create a reference to an abstract class so that it can be used to point to a subclass object. mukundpandey2000 slheymann1 Picked Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Hashtable in Java Constructors in Java Different ways of Reading a text file in Java Comparator Interface in Java with Examples Java Math random() method with Examples HashMap containsKey() Method in Java How to Create Array of Objects in Java? Convert Double to Integer in Java Iterating over ArrayLists in Java Generating random numbers in Java
[ { "code": null, "e": 23582, "s": 23554, "text": "\n26 Dec, 2020" }, { "code": null, "e": 23964, "s": 23582, "text": "Sometimes, we require just method declaration in super-classes. This can be achieve by specifying the abstract type modifier. These methods are sometimes referred to as subclasser responsibility because they have no implementation specified in the super-class. Thus, a subclass must override them to provide method definition. To declare an abstract method, use this general form: " }, { "code": null, "e": 24007, "s": 23964, "text": "abstract type method-name(parameter-list);" }, { "code": null, "e": 24229, "s": 24007, "text": "As you can see, no method body is present. Any concrete class(i.e. class without abstract keyword) that extends an abstract class must override all the abstract methods of the class.Important rules for abstract methods: " }, { "code": null, "e": 24313, "s": 24229, "text": "Any class that contains one or more abstract methods must also be declared abstract" }, { "code": null, "e": 24516, "s": 24313, "text": "The following are various illegal combinations of other modifiers for methods with respect to abstract modifier: finalabstract nativeabstract synchronizedabstract staticabstract privateabstract strictfp" }, { "code": null, "e": 24606, "s": 24516, "text": "finalabstract nativeabstract synchronizedabstract staticabstract privateabstract strictfp" }, { "code": null, "e": 24612, "s": 24606, "text": "final" }, { "code": null, "e": 24628, "s": 24612, "text": "abstract native" }, { "code": null, "e": 24650, "s": 24628, "text": "abstract synchronized" }, { "code": null, "e": 24666, "s": 24650, "text": "abstract static" }, { "code": null, "e": 24683, "s": 24666, "text": "abstract private" }, { "code": null, "e": 24701, "s": 24683, "text": "abstract strictfp" }, { "code": null, "e": 24810, "s": 24701, "text": "Consider the following Java program, that illustrate the use of abstract keyword with classes and methods. " }, { "code": null, "e": 24815, "s": 24810, "text": "Java" }, { "code": "// A java program to demonstrate// use of abstract keyword. // abstract classabstract class A { // abstract method // it has no body abstract void m1(); // concrete methods are still // allowed in abstract classes void m2() { System.out.println(\"This is \" + \"a concrete method.\"); }} // concrete class Bclass B extends A { // class B must override m1() method // otherwise, compile-time // exception will be thrown void m1() { System.out.println(\"B's \" + \"implementation of m1.\"); }} // Driver classpublic class AbstractDemo { public static void main(String args[]) { B b = new B(); b.m1(); b.m2(); }}", "e": 25556, "s": 24815, "text": null }, { "code": null, "e": 25565, "s": 25556, "text": "Output: " }, { "code": null, "e": 25618, "s": 25565, "text": "B's implementation of m1.\nThis is a concrete method." }, { "code": null, "e": 25966, "s": 25618, "text": "Note: Although abstract classes cannot be used to instantiate objects, they can be used to create object references, because Java’s approach to run-time polymorphism is implemented through the use of super-class references. Thus, it must be possible to create a reference to an abstract class so that it can be used to point to a subclass object. " }, { "code": null, "e": 25983, "s": 25966, "text": "mukundpandey2000" }, { "code": null, "e": 25994, "s": 25983, "text": "slheymann1" }, { "code": null, "e": 26001, "s": 25994, "text": "Picked" }, { "code": null, "e": 26006, "s": 26001, "text": "Java" }, { "code": null, "e": 26025, "s": 26006, "text": "Technical Scripter" }, { "code": null, "e": 26030, "s": 26025, "text": "Java" }, { "code": null, "e": 26128, "s": 26030, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26137, "s": 26128, "text": "Comments" }, { "code": null, "e": 26150, "s": 26137, "text": "Old Comments" }, { "code": null, "e": 26168, "s": 26150, "text": "Hashtable in Java" }, { "code": null, "e": 26189, "s": 26168, "text": "Constructors in Java" }, { "code": null, "e": 26235, "s": 26189, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26278, "s": 26235, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 26318, "s": 26278, "text": "Java Math random() method with Examples" }, { "code": null, "e": 26355, "s": 26318, "text": "HashMap containsKey() Method in Java" }, { "code": null, "e": 26395, "s": 26355, "text": "How to Create Array of Objects in Java?" }, { "code": null, "e": 26429, "s": 26395, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 26463, "s": 26429, "text": "Iterating over ArrayLists in Java" } ]
Enum in Python
Enum is a class in python for creating enumerations, which are a set of symbolic names (members) bound to unique, constant values. The members of an enumeration can be compared by these symbolic anmes, and the enumeration itself can be iterated over. An enum has the following characteristics. The enums are evaluatable string representation of an object also called repr(). The enums are evaluatable string representation of an object also called repr(). The name of the enum is displayed using ‘name’ keyword. The name of the enum is displayed using ‘name’ keyword. Using type() we can check the enum types. Using type() we can check the enum types. import enum # Using enum class create enumerations class Days(enum.Enum): Sun = 1 Mon = 2 Tue = 3 # print the enum member as a string print ("The enum member as a string is : ",end="") print (Days.Mon) # print the enum member as a repr print ("he enum member as a repr is : ",end="") print (repr(Days.Sun)) # Check type of enum member print ("The type of enum member is : ",end ="") print (type(Days.Mon)) # print name of enum member print ("The name of enum member is : ",end ="") print (Days.Tue.name) Running the above code gives us the following result − The enum member as a string is : Days.Mon he enum member as a repr is : The type of enum member is : The name of enum member is : Tue We can print the enum as an iterable list. In the below code we use a for loop to print all enum members. import enum # Using enum class create enumerations class Days(enum.Enum): Sun = 1 Mon = 2 Tue = 3 # printing all enum members using loop print ("The enum members are : ") for weekday in (Days): print(weekday) Running the above code gives us the following result − The enum members are : Days.Sun Days.Mon Days.Tue The members in an Enumeration are hashable, hence they can be used in dictionaries and sets. in the below example we see the hashing in action and check if the hashing is successful. import enum # Using enum class create enumerations class Days(enum.Enum): Sun = 1 Mon = 2 # Hashing to create a dictionary Daytype = {} Daytype[Days.Sun] = 'Sun God' Daytype[Days.Mon] = 'Moon God' # Checkign if the hashing is successful print(Daytype =={Days.Sun:'Sun God',Days.Mon:'Moon God'}) Running the above code gives us the following result − True We can access the enum members by using the name or value of the member items. In the below example we first access the value by name where we use the name of the enu as an index. import enum # Using enum class create enumerations class Days(enum.Enum): Sun = 1 Mon = 2 print('enum member accessed by name: ') print (Days['Mon']) print('enum member accessed by Value: ') print (Days(1)) Running the above code gives us the following result − enum member accessed by name: Days.Mon enum member accessed by Value: Days.Sun Comparing the enums is a sraight forward process, we use the comparison operator. import enum # Using enum class create enumerations class Days(enum.Enum): Sun = 1 Mon = 2 Tue = 1 if Days.Sun == Days.Tue: print('Match') if Days.Mon != Days.Tue: print('No Match') Running the above code gives us the following result − Match No Match
[ { "code": null, "e": 1356, "s": 1062, "text": "Enum is a class in python for creating enumerations, which are a set of symbolic names (members) bound to unique, constant values. The members of an enumeration can be compared by these symbolic anmes, and the enumeration itself can be iterated over. An enum has the following characteristics." }, { "code": null, "e": 1437, "s": 1356, "text": "The enums are evaluatable string representation of an object also called repr()." }, { "code": null, "e": 1518, "s": 1437, "text": "The enums are evaluatable string representation of an object also called repr()." }, { "code": null, "e": 1574, "s": 1518, "text": "The name of the enum is displayed using ‘name’ keyword." }, { "code": null, "e": 1630, "s": 1574, "text": "The name of the enum is displayed using ‘name’ keyword." }, { "code": null, "e": 1672, "s": 1630, "text": "Using type() we can check the enum types." }, { "code": null, "e": 1714, "s": 1672, "text": "Using type() we can check the enum types." }, { "code": null, "e": 2230, "s": 1714, "text": "import enum\n# Using enum class create enumerations\nclass Days(enum.Enum):\n Sun = 1\n Mon = 2\n Tue = 3\n# print the enum member as a string\nprint (\"The enum member as a string is : \",end=\"\")\nprint (Days.Mon)\n\n# print the enum member as a repr\nprint (\"he enum member as a repr is : \",end=\"\")\nprint (repr(Days.Sun))\n\n# Check type of enum member\nprint (\"The type of enum member is : \",end =\"\")\nprint (type(Days.Mon))\n\n# print name of enum member\nprint (\"The name of enum member is : \",end =\"\")\nprint (Days.Tue.name)" }, { "code": null, "e": 2285, "s": 2230, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2419, "s": 2285, "text": "The enum member as a string is : Days.Mon\nhe enum member as a repr is :\nThe type of enum member is :\nThe name of enum member is : Tue" }, { "code": null, "e": 2525, "s": 2419, "text": "We can print the enum as an iterable list. In the below code we use a for loop to print all enum members." }, { "code": null, "e": 2746, "s": 2525, "text": "import enum\n# Using enum class create enumerations\nclass Days(enum.Enum):\n Sun = 1\n Mon = 2\n Tue = 3\n# printing all enum members using loop\nprint (\"The enum members are : \")\nfor weekday in (Days):\n print(weekday)" }, { "code": null, "e": 2801, "s": 2746, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2851, "s": 2801, "text": "The enum members are :\nDays.Sun\nDays.Mon\nDays.Tue" }, { "code": null, "e": 3034, "s": 2851, "text": "The members in an Enumeration are hashable, hence they can be used in dictionaries and sets. in the below example we see the hashing in action and check if the hashing is successful." }, { "code": null, "e": 3336, "s": 3034, "text": "import enum\n# Using enum class create enumerations\nclass Days(enum.Enum):\n Sun = 1\n Mon = 2\n# Hashing to create a dictionary\nDaytype = {}\nDaytype[Days.Sun] = 'Sun God'\nDaytype[Days.Mon] = 'Moon God'\n\n# Checkign if the hashing is successful\nprint(Daytype =={Days.Sun:'Sun God',Days.Mon:'Moon God'})" }, { "code": null, "e": 3391, "s": 3336, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 3396, "s": 3391, "text": "True" }, { "code": null, "e": 3576, "s": 3396, "text": "We can access the enum members by using the name or value of the member items. In the below example we first access the value by name where we use the name of the enu as an index." }, { "code": null, "e": 3789, "s": 3576, "text": "import enum\n# Using enum class create enumerations\nclass Days(enum.Enum):\n Sun = 1\n Mon = 2\nprint('enum member accessed by name: ')\nprint (Days['Mon'])\nprint('enum member accessed by Value: ')\nprint (Days(1))" }, { "code": null, "e": 3844, "s": 3789, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 3923, "s": 3844, "text": "enum member accessed by name:\nDays.Mon\nenum member accessed by Value:\nDays.Sun" }, { "code": null, "e": 4005, "s": 3923, "text": "Comparing the enums is a sraight forward process, we use the comparison operator." }, { "code": null, "e": 4201, "s": 4005, "text": "import enum\n# Using enum class create enumerations\nclass Days(enum.Enum):\n Sun = 1\n Mon = 2\n Tue = 1\nif Days.Sun == Days.Tue:\n print('Match')\nif Days.Mon != Days.Tue:\n print('No Match')" }, { "code": null, "e": 4256, "s": 4201, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 4271, "s": 4256, "text": "Match\nNo Match" } ]
Sum of Array Elements | Practice | GeeksforGeeks
Given an integer array arr of size n, you need to sum the elements of arr. Example 1: Input: n = 3 arr[] = {3 2 1} Output: 6 Example 2: Input: n = 4 arr[] = {1 2 3 4} Output: 10 Your Task: You need to complete the function sumElement() that takes arr and n and returns the sum. The printing is done by the driver code. Expected Time Complexity: O(n). Expected Auxiliary Space: O(1). Constraints: 1 <= n <= 103 1 <= arri <= 104 0 adityadixit70541 day ago Take a variable sum=0 then iterate the array and add to sum then return sum def sumElement(arr,n): sum=0 for i in range(n): sum=sum+arr[i] return sum 0 mehtay0376 days ago Python Solution: def sumElement(arr,n): #code here return sum(arr) 0 atif836146 days ago JAVA SOLUTION if(n==0){ return 0; } int sum=0; for(int i=0;i<n;i++){ sum=sum+arr[i]; } return sum; 0 rishabhchemistry31 week ago int res=0; for(int i=0;i<n;i++){ res=res+arr[i]; } return res; 0 zubairbinmasood786abcd1 week ago C++ Recursion if(n<0) return 0; return arr[n - 1] + sumElement(arr,n - 1); 0 zubairbinmasood786abcd1 week ago C++ One Liner : ) return accumulate(arr,arr + n,0); 0 diagovenk2 weeks ago Hello guys. Four lines easy java solution public static int sumElement(int arr[], int n) { // Your code here int sum = 0; for(int i=0; i<n; i++){ sum += arr[i]; } return sum; } 0 shaikhusama7453 weeks ago C++ Code using Recursionint sumElement(int arr[],int n){ //Base Case if( n == 0 ){ return 0; } if( n == 1 ){ return arr[0]; } //Recursive Call int remainingPart = sumElement(arr+1,n-1); int sum = arr[0] + remainingPart; return sum;} 0 rapuriteja1 month ago def sumElement(arr,n): su = sum(arr) return su 0 ravi119033851 month ago //JAVA int sum=0; for(int i: arr) { sum+=i; } return sum; 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": 301, "s": 226, "text": "Given an integer array arr of size n, you need to sum the elements of arr." }, { "code": null, "e": 312, "s": 301, "text": "Example 1:" }, { "code": null, "e": 351, "s": 312, "text": "Input:\nn = 3\narr[] = {3 2 1}\nOutput: 6" }, { "code": null, "e": 362, "s": 351, "text": "Example 2:" }, { "code": null, "e": 405, "s": 362, "text": "Input:\nn = 4\narr[] = {1 2 3 4}\nOutput: 10\n" }, { "code": null, "e": 546, "s": 405, "text": "Your Task:\nYou need to complete the function sumElement() that takes arr and n and returns the sum. The printing is done by the driver code." }, { "code": null, "e": 610, "s": 546, "text": "Expected Time Complexity: O(n).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 654, "s": 610, "text": "Constraints:\n1 <= n <= 103\n1 <= arri <= 104" }, { "code": null, "e": 656, "s": 654, "text": "0" }, { "code": null, "e": 681, "s": 656, "text": "adityadixit70541 day ago" }, { "code": null, "e": 703, "s": 681, "text": "Take a variable sum=0" }, { "code": null, "e": 741, "s": 703, "text": "then iterate the array and add to sum" }, { "code": null, "e": 757, "s": 741, "text": "then return sum" }, { "code": null, "e": 843, "s": 757, "text": "def sumElement(arr,n): sum=0 for i in range(n): sum=sum+arr[i] return sum" }, { "code": null, "e": 845, "s": 843, "text": "0" }, { "code": null, "e": 865, "s": 845, "text": "mehtay0376 days ago" }, { "code": null, "e": 882, "s": 865, "text": "Python Solution:" }, { "code": null, "e": 937, "s": 882, "text": "def sumElement(arr,n): #code here return sum(arr) " }, { "code": null, "e": 939, "s": 937, "text": "0" }, { "code": null, "e": 959, "s": 939, "text": "atif836146 days ago" }, { "code": null, "e": 973, "s": 959, "text": "JAVA SOLUTION" }, { "code": null, "e": 1116, "s": 973, "text": " if(n==0){\n return 0;\n }\n int sum=0;\n for(int i=0;i<n;i++){\n sum=sum+arr[i];\n }\n return sum;" }, { "code": null, "e": 1118, "s": 1116, "text": "0" }, { "code": null, "e": 1146, "s": 1118, "text": "rishabhchemistry31 week ago" }, { "code": null, "e": 1222, "s": 1146, "text": " int res=0; for(int i=0;i<n;i++){ res=res+arr[i]; } return res;" }, { "code": null, "e": 1224, "s": 1222, "text": "0" }, { "code": null, "e": 1257, "s": 1224, "text": "zubairbinmasood786abcd1 week ago" }, { "code": null, "e": 1271, "s": 1257, "text": "C++ Recursion" }, { "code": null, "e": 1340, "s": 1271, "text": "if(n<0)\n return 0;\nreturn arr[n - 1] + sumElement(arr,n - 1);" }, { "code": null, "e": 1342, "s": 1340, "text": "0" }, { "code": null, "e": 1375, "s": 1342, "text": "zubairbinmasood786abcd1 week ago" }, { "code": null, "e": 1393, "s": 1375, "text": "C++ One Liner : )" }, { "code": null, "e": 1427, "s": 1393, "text": "return accumulate(arr,arr + n,0);" }, { "code": null, "e": 1429, "s": 1427, "text": "0" }, { "code": null, "e": 1450, "s": 1429, "text": "diagovenk2 weeks ago" }, { "code": null, "e": 1492, "s": 1450, "text": "Hello guys. Four lines easy java solution" }, { "code": null, "e": 1671, "s": 1492, "text": "public static int sumElement(int arr[], int n) { // Your code here int sum = 0; for(int i=0; i<n; i++){ sum += arr[i]; } return sum; }" }, { "code": null, "e": 1673, "s": 1671, "text": "0" }, { "code": null, "e": 1699, "s": 1673, "text": "shaikhusama7453 weeks ago" }, { "code": null, "e": 1847, "s": 1699, "text": "C++ Code using Recursionint sumElement(int arr[],int n){ //Base Case if( n == 0 ){ return 0; } if( n == 1 ){ return arr[0]; }" }, { "code": null, "e": 1867, "s": 1847, "text": " //Recursive Call" }, { "code": null, "e": 1971, "s": 1867, "text": " int remainingPart = sumElement(arr+1,n-1); int sum = arr[0] + remainingPart; return sum;} " }, { "code": null, "e": 1973, "s": 1971, "text": "0" }, { "code": null, "e": 1995, "s": 1973, "text": "rapuriteja1 month ago" }, { "code": null, "e": 2046, "s": 1995, "text": "def sumElement(arr,n): su = sum(arr) return su" }, { "code": null, "e": 2048, "s": 2046, "text": "0" }, { "code": null, "e": 2072, "s": 2048, "text": "ravi119033851 month ago" }, { "code": null, "e": 2079, "s": 2072, "text": "//JAVA" }, { "code": null, "e": 2164, "s": 2079, "text": "int sum=0; for(int i: arr) { sum+=i; } return sum;" }, { "code": null, "e": 2310, "s": 2164, "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": 2346, "s": 2310, "text": " Login to access your submissions. " }, { "code": null, "e": 2356, "s": 2346, "text": "\nProblem\n" }, { "code": null, "e": 2366, "s": 2356, "text": "\nContest\n" }, { "code": null, "e": 2429, "s": 2366, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 2577, "s": 2429, "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": 2785, "s": 2577, "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": 2891, "s": 2785, "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 subset an R data frame with condition based on only one value from categorical column?
To subset an R data frame with condition based on only one value from categorical column, we can follow the below steps − First of all, create a data frame. Then, subset the data frame with condition using filter function of dplyr package. Let's create a data frame as shown below − Live Demo Class<-sample(c("First","Second","Third","Fourth"),25,replace=TRUE) x<-sample(1:10,25,replace=TRUE) y<-sample(1:10,25,replace=TRUE) z<-sample(1:10,25,replace=TRUE) df<-data.frame(Class,x,y,z) df On executing, the above script generates the below output(this output will vary on your system due to randomization) − Class x y z 1 Fourth 10 6 7 2 First 10 1 5 3 Third 3 5 9 4 First 2 8 5 5 Third 4 9 9 6 First 2 5 3 7 Second 2 7 7 8 Third 6 4 4 9 First 2 9 3 10 First 10 7 4 11 Fourth 1 9 3 12 First 8 7 8 13 First 7 5 3 14 First 10 4 2 15 First 8 9 2 16 First 9 9 10 17 Third 1 1 10 18 Third 5 9 6 19 First 3 2 9 20 Third 8 5 4 21 Third 9 2 7 22 Second 5 9 3 23 Third 10 3 6 24 First 10 6 9 25 Third 1 10 4 Using filter function to subset df when x is greater than 5 and Class is First − Class<-sample(c("First","Second","Third","Fourth"),25,replace=TRUE) x<-sample(1:10,25,replace=TRUE) y<-sample(1:10,25,replace=TRUE) z<-sample(1:10,25,replace=TRUE) df<-data.frame(Class,x,y,z) library(dplyr) df %>% group_by(Class) %>% filter(x>5 & Class=="First") # A tibble: 8 x 4 # Groups: Class [1] Class x y z <chr> <int> <int> <int> 1 First 10 1 5 2 First 10 7 4 3 First 8 7 8 4 First 7 5 3 5 First 10 4 2 6 First 8 9 2 7 First 9 9 10 8 First 10 6 9 Using filter function to subset df when y is greater than 5 and Class is First − Class<-sample(c("First","Second","Third","Fourth"),25,replace=TRUE) x<-sample(1:10,25,replace=TRUE) y<-sample(1:10,25,replace=TRUE) z<-sample(1:10,25,replace=TRUE) df<-data.frame(Class,x,y,z) library(dplyr) df %>% group_by(Class) %>% filter(y>5 & Class=="First") # A tibble: 7 x 4 # Groups: Class [1] Class x y z <chr> <int> <int> <int> 1 First 2 8 5 2 First 2 9 3 3 First 10 7 4 4 First 8 7 8 5 First 8 9 2 6 First 9 9 10 7 First 10 6 9 Using filter function to subset df when z is greater than 5 and Class is First − Class<-sample(c("First","Second","Third","Fourth"),25,replace=TRUE) x<-sample(1:10,25,replace=TRUE) y<-sample(1:10,25,replace=TRUE) z<-sample(1:10,25,replace=TRUE) df<-data.frame(Class,x,y,z) library(dplyr) df %>% group_by(Class) %>% filter(z>5 & Class=="First") # A tibble: 4 x 4 # Groups: Class [1] Class x y z <chr> <int> <int> <int> 1 First 8 7 8 2 First 9 9 10 3 First 3 2 9 4 First 10 6 9
[ { "code": null, "e": 1184, "s": 1062, "text": "To subset an R data frame with condition based on only one value from categorical\ncolumn, we can follow the below steps −" }, { "code": null, "e": 1219, "s": 1184, "text": "First of all, create a data frame." }, { "code": null, "e": 1302, "s": 1219, "text": "Then, subset the data frame with condition using filter function of dplyr package." }, { "code": null, "e": 1345, "s": 1302, "text": "Let's create a data frame as shown below −" }, { "code": null, "e": 1356, "s": 1345, "text": " Live Demo" }, { "code": null, "e": 1551, "s": 1356, "text": "Class<-sample(c(\"First\",\"Second\",\"Third\",\"Fourth\"),25,replace=TRUE)\nx<-sample(1:10,25,replace=TRUE)\ny<-sample(1:10,25,replace=TRUE)\nz<-sample(1:10,25,replace=TRUE)\ndf<-data.frame(Class,x,y,z)\ndf" }, { "code": null, "e": 1670, "s": 1551, "text": "On executing, the above script generates the below output(this output will vary on your system due to randomization) −" }, { "code": null, "e": 2061, "s": 1670, "text": "Class x y z\n1 Fourth 10 6 7\n2 First 10 1 5\n3 Third 3 5 9\n4 First 2 8 5\n5 Third 4 9 9\n6 First 2 5 3\n7 Second 2 7 7\n8 Third 6 4 4\n9 First 2 9 3\n10 First 10 7 4\n11 Fourth 1 9 3\n12 First 8 7 8\n13 First 7 5 3\n14 First 10 4 2\n15 First 8 9 2\n16 First 9 9 10\n17 Third 1 1 10\n18 Third 5 9 6\n19 First 3 2 9\n20 Third 8 5 4\n21 Third 9 2 7\n22 Second 5 9 3\n23 Third 10 3 6\n24 First 10 6 9\n25 Third 1 10 4" }, { "code": null, "e": 2142, "s": 2061, "text": "Using filter function to subset df when x is greater than 5 and Class is First −" }, { "code": null, "e": 2405, "s": 2142, "text": "Class<-sample(c(\"First\",\"Second\",\"Third\",\"Fourth\"),25,replace=TRUE)\nx<-sample(1:10,25,replace=TRUE)\ny<-sample(1:10,25,replace=TRUE)\nz<-sample(1:10,25,replace=TRUE)\ndf<-data.frame(Class,x,y,z)\nlibrary(dplyr)\ndf %>% group_by(Class) %>% filter(x>5 & Class==\"First\")" }, { "code": null, "e": 2660, "s": 2405, "text": "# A tibble: 8 x 4\n# Groups: Class [1]\nClass x y z\n <chr> <int> <int> <int>\n1 First 10 1 5\n2 First 10 7 4\n3 First 8 7 8\n4 First 7 5 3\n5 First 10 4 2\n6 First 8 9 2\n7 First 9 9 10\n8 First 10 6 9" }, { "code": null, "e": 2741, "s": 2660, "text": "Using filter function to subset df when y is greater than 5 and Class is First −" }, { "code": null, "e": 3004, "s": 2741, "text": "Class<-sample(c(\"First\",\"Second\",\"Third\",\"Fourth\"),25,replace=TRUE)\nx<-sample(1:10,25,replace=TRUE)\ny<-sample(1:10,25,replace=TRUE)\nz<-sample(1:10,25,replace=TRUE)\ndf<-data.frame(Class,x,y,z)\nlibrary(dplyr)\ndf %>% group_by(Class) %>% filter(y>5 & Class==\"First\")" }, { "code": null, "e": 3239, "s": 3004, "text": "# A tibble: 7 x 4\n# Groups: Class [1]\nClass x y z\n <chr> <int> <int> <int>\n1 First 2 8 5\n2 First 2 9 3\n3 First 10 7 4\n4 First 8 7 8 \n5 First 8 9 2\n6 First 9 9 10\n7 First 10 6 9" }, { "code": null, "e": 3320, "s": 3239, "text": "Using filter function to subset df when z is greater than 5 and Class is First −" }, { "code": null, "e": 3583, "s": 3320, "text": "Class<-sample(c(\"First\",\"Second\",\"Third\",\"Fourth\"),25,replace=TRUE)\nx<-sample(1:10,25,replace=TRUE)\ny<-sample(1:10,25,replace=TRUE)\nz<-sample(1:10,25,replace=TRUE)\ndf<-data.frame(Class,x,y,z)\nlibrary(dplyr)\ndf %>% group_by(Class) %>% filter(z>5 & Class==\"First\")" }, { "code": null, "e": 3747, "s": 3583, "text": "# A tibble: 4 x 4\n# Groups: Class [1]\nClass x y z\n<chr> <int> <int> <int>\n1 First 8 7 8\n2 First 9 9 10\n3 First 3 2 9\n4 First 10 6 9" } ]
Class isAssignableFrom() method in Java with Examples - GeeksforGeeks
27 Nov, 2019 The isAssignableFrom() method of java.lang.Class class is used to check if the specified class’s object is compatible to be assigned to the instance of this Class. It will be compatible if both the classes are the same, or the specified class is a superclass or superinterface. The method returns true if the specified class’s object can be cast to the instance of this Class. It returns false otherwise. Syntax: public boolean isAssignableFrom(Class<T> class) Parameter: This method accepts class as parameter which is the specified class whose object to checked for compatibility to this Class instance. Return Value: This method returns true if the specified class’s object can be cast to the instance of this Class. It returns false otherwise. Below programs demonstrate the isAssignableFrom() method. Example 1: // Java program to demonstrate isAssignableFrom() method public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("Test"); System.out.println("Class represented by myClass: " + myClass.toString()); // get the Class instance using forName() method Class c = Class.forName("java.lang.String"); System.out.println("Class represented by c: " + c.toString()); // Check if object c is compatible // using isAssignableFrom() method System.out.println("Is c compatible: " + myClass.isAssignableFrom(c)); }} Output: Class represented by myClass: class Test Class represented by c: class java.lang.String Is c compatible: false Example 2: // Java program to demonstrate isAssignableFrom() method public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("Test"); System.out.println("Class represented by myClass: " + myClass.toString()); // get the Class instance using forName() method Class c = Class.forName("Test"); System.out.println("Class represented by c: " + c.toString()); // Check if object c is compatible // using isAssignableFrom() method System.out.println("Is c compatible: " + myClass.isAssignableFrom(c)); }} Output: Class represented by myClass: class Test Class represented by c: class Test Is c compatible: true Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#isAssignableFrom-java.lang.Class- Java-Functions Java-lang package Java.lang.Class Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Different ways of Reading a text file in Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Comparator Interface in Java with Examples HashMap get() Method in Java Introduction to Java Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23973, "s": 23945, "text": "\n27 Nov, 2019" }, { "code": null, "e": 24378, "s": 23973, "text": "The isAssignableFrom() method of java.lang.Class class is used to check if the specified class’s object is compatible to be assigned to the instance of this Class. It will be compatible if both the classes are the same, or the specified class is a superclass or superinterface. The method returns true if the specified class’s object can be cast to the instance of this Class. It returns false otherwise." }, { "code": null, "e": 24386, "s": 24378, "text": "Syntax:" }, { "code": null, "e": 24435, "s": 24386, "text": "public boolean isAssignableFrom(Class<T> class)\n" }, { "code": null, "e": 24580, "s": 24435, "text": "Parameter: This method accepts class as parameter which is the specified class whose object to checked for compatibility to this Class instance." }, { "code": null, "e": 24722, "s": 24580, "text": "Return Value: This method returns true if the specified class’s object can be cast to the instance of this Class. It returns false otherwise." }, { "code": null, "e": 24780, "s": 24722, "text": "Below programs demonstrate the isAssignableFrom() method." }, { "code": null, "e": 24791, "s": 24780, "text": "Example 1:" }, { "code": "// Java program to demonstrate isAssignableFrom() method public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); // get the Class instance using forName() method Class c = Class.forName(\"java.lang.String\"); System.out.println(\"Class represented by c: \" + c.toString()); // Check if object c is compatible // using isAssignableFrom() method System.out.println(\"Is c compatible: \" + myClass.isAssignableFrom(c)); }}", "e": 25565, "s": 24791, "text": null }, { "code": null, "e": 25573, "s": 25565, "text": "Output:" }, { "code": null, "e": 25685, "s": 25573, "text": "Class represented by myClass: class Test\nClass represented by c: class java.lang.String\nIs c compatible: false\n" }, { "code": null, "e": 25696, "s": 25685, "text": "Example 2:" }, { "code": "// Java program to demonstrate isAssignableFrom() method public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); // get the Class instance using forName() method Class c = Class.forName(\"Test\"); System.out.println(\"Class represented by c: \" + c.toString()); // Check if object c is compatible // using isAssignableFrom() method System.out.println(\"Is c compatible: \" + myClass.isAssignableFrom(c)); }}", "e": 26458, "s": 25696, "text": null }, { "code": null, "e": 26466, "s": 26458, "text": "Output:" }, { "code": null, "e": 26565, "s": 26466, "text": "Class represented by myClass: class Test\nClass represented by c: class Test\nIs c compatible: true\n" }, { "code": null, "e": 26673, "s": 26565, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#isAssignableFrom-java.lang.Class-" }, { "code": null, "e": 26688, "s": 26673, "text": "Java-Functions" }, { "code": null, "e": 26706, "s": 26688, "text": "Java-lang package" }, { "code": null, "e": 26722, "s": 26706, "text": "Java.lang.Class" }, { "code": null, "e": 26727, "s": 26722, "text": "Java" }, { "code": null, "e": 26732, "s": 26727, "text": "Java" }, { "code": null, "e": 26830, "s": 26732, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26845, "s": 26830, "text": "Stream In Java" }, { "code": null, "e": 26891, "s": 26845, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26912, "s": 26891, "text": "Constructors in Java" }, { "code": null, "e": 26931, "s": 26912, "text": "Exceptions in Java" }, { "code": null, "e": 26948, "s": 26931, "text": "Generics in Java" }, { "code": null, "e": 26978, "s": 26948, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27021, "s": 26978, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 27050, "s": 27021, "text": "HashMap get() Method in Java" }, { "code": null, "e": 27071, "s": 27050, "text": "Introduction to Java" } ]