title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
“Hello World” In 30 Different Languages
14 Aug, 2021 In this article, we are going to see how to print “Hello World” in 30 different languages. It includes languages like C, C++, Cobol, Scala, Matlab, C#, CoffeeScript, Delphi, Dart, Haskell, Pascal, Ruby, Python, Assembly, R, Swift, Kotlin, PHP, Java, Go, F#, Lisp, JavaScript, Algol, Perl, Tcl, TypeScript, Fortran, Bash (Unix Shell) and HTML. Now, let’s get started, C is a procedural programming language. It was initially developed by Dennis Ritchie as a system programming language to write an operating system. Features: Include low-level access to memory, a simple set of keywords, and a clean style, these features make C language suitable for system programmings like operating system or compiler development. Fast and Efficient. Hello World Program in C Language: C #include <stdio.h> int main() { printf("Hello World"); return 0;} C++, high-level computer programming language. Developed by Bjarne Stroustrup of Bell Laboratories in the early 1980s, it is based on the traditional C language but with added object-oriented programming and other capabilities. Features: Machine Independent or Portable. Mid-level programming language. Hello World Program in C++: C++ #include <iostream> int main() { std::cout << "Hello World"; return 0;} COBOL was designed in 1959 by CODASYL and was partly based on the programming language FLOW-MATIC designed by Grace Hopper. It was created as part of a US Department of Defense effort to create a portable programming language for data processing. Features: COBOL is an easy-to-learn, standard language that can be compiled and executed on a variety of computers. It supports a wide syntax vocabulary and features an uncluttered coding style. The logical control structures available in COBOL make it easy to read, modify and debug. COBOL is also scalable, reliable and portable across platforms. Hello World Program in Cobol: IDENTIFICATION DIVISION. PROGRAM-ID. Hello-world. PROCEDURE DIVISION. DISPLAY "Hello World". . Scala is a modern programming language designed and created by Martin Odersky. The design of the language started in 2001 and was released to the public in early 2004. Martin Odersky had a huge hand in the implementation of javac (the primary Java compiler) and also designed Generic Java, a facility of generic programming that was added to the Java programming language in 2004. This is why it doesn’t come as a surprise that Scala is similar to Java in many aspects, it’s actually written to run in JVM (Java Virtual Machine). Features: Case classes and Pattern matching. Singleton object. Hello World Program in Scala: Scala object HelloWorld extends App { printIn("Hello World")} MATLAB is a programming language developed by MathWorks. It started out as a matrix programming language where linear algebra programming was simple. It can be run both under interactive sessions and as a batch job. This tutorial gives you aggressively a gentle introduction of MATLAB programming language. Features: MATLAB can natively support the sensor, video, image, telemetry, binary, and various real-time data from JDBC/ODBC databases. Reading data from different databases, CSV, audio, images, and video is super simple from an integrated environment. It offers a huge library of mathematical functions needed for computing statistics, linear algebra, numerical integration, filtering, Fourier analysis, optimization and solving regular differential equations. Hello World Program in Matlab: disp('Hello World'); C# is pronounced as “C-Sharp”. It is an object-oriented programming language provided by Microsoft that runs on .Net Framework. Anders Hejlsberg is known as the founder of C# language. It is based on C++ and Java, but it has many additional extensions used to perform component-oriented programming approach. C# has evolved much since their first release in the year 2002. It was introduced with .NET Framework 1.0 and the current version of C# is 5.0. Features: Type-Safe. Component Oriented. Hello World in C#: C# namespace HelloWorld{ class Hello { static void Main(string[] args) { System.Console.WriteLine("Hello World"); } }} CoffeeScript is a lightweight language based on Ruby and Python which transcompiles (compiles from one source language to another) into JavaScript. It provides better syntax avoiding the quirky parts of JavaScript, still retaining the flexibility and beauty of the language. Features: Class-Based Inheritance. Extensive Library Support. Hello World in CoffeeScript: console.lof 'Hello World' Delphi was built to be run with Windows, macOS, iOS, Android, and Linux applications. This is about every major platform in existence. Primarily though, it was developed to be run with Windows-based applications. Since its arrival, Delphi has emphasized backward compatibility. This means that new programs can be run with their successors seamlessly. Features: Backward Compatibility. Incorporation Capability. Hello World Program in Delphi: program HelloWorld; begin WriteLn('Hello World'); end. Dart is an open-source general-purpose programming language. It is originally developed by Google and later approved as a standard by ECMA. Dart is a new programming language meant for the server as well as the browser. Introduced by Google, the Dart SDK ships with its compiler – the Dart VM. The SDK also includes a utility -dart2js, a transpiler that generates JavaScript equivalent of a Dart Script. Features: Flexible Imports and Exports. Null-Safe Operators. Hello World in Dart: Dart main(){ print('Hello World');} Haskell is a widely used purely functional language. Functional programming is based on mathematical functions. Besides Haskell, some other popular languages that follow Functional Programming paradigm include: Lisp, Python, Erlang, Racket, F#, Clojure, etc. Haskell is more intelligent than other popular programming languages such as Java, C, C++, PHP, etc Features: Lazy Evaluation. Pattern Matching. Hello World in Haskell: module Main where main :: IO () main = putStrLn "Hello World" Pascal, a computer programming language developed about 1970 by Niklaus Wirth of Switzerland to teach structured programming, which emphasizes the orderly use of conditional and loop control structures without GOTO statements. Features: Pascal is a Strongly Typed Language. It Supports Structured Programming Through Functions and Procedures. Hello World in Pascal: program Hello; begin writeln ('Hello, world.'); end. Ruby is a pure object-oriented programming language. It was created in 1993 by Yukihiro Matsumoto of Japan. Ruby is open-source and is freely available on the Web, but it is subject to a license. Features: Ruby can be used to write Common Gateway Interface (CGI) scripts. Ruby can be embedded into Hypertext Markup Language (HTML). Hello World in Ruby: Ruby puts 'Hello World' Python is a widely-used, interpreted, object-oriented, and high-level programming language with dynamic semantics, used for general-purpose programming. It was created by Guido van Rossum, and first released on February 20, 1991. Features: GUI Programming Support. Dynamically Typed Language. Hello World in Python: Python3 print("Hello World") Stan Poley wrote the Symbolic Optimal Assembly Program or SOAP assembly language for the IBM 650 computer in 1955. Assembly languages started being used widely as they relieved the programmers from tedious tasks such as remembering numeric codes. Features: 64-bit Address Space. Assembly languages have a syntax that is similar to the English language. Hello World in Assembly Language: global _main extern _printf section .text _main: push message call _printf add esp, 4 message: db 'Hello World', 10, 0 R is a language and environment for statistical computing and graphics. It is a GNU project which is similar to the S language and environment which was developed at Bell Laboratories (formerly AT&T, now Lucent Technologies) by John Chambers and colleagues. Features: Can Perform Complex Statistical Calculations. R is an interpreted language which means that it does not need a compiler to make a program from the code. Hello World Program in R: R cat('Hello World') Swift is a general-purpose, multi-paradigm, object-oriented, functional, imperative, and block structured language. It is the result of the latest research on programming languages and is built using a modern approach to safety, software design patterns by Apple Inc.. It is the brand new programming language for the iOS application, macOS applications, watchOS applications, tvOS applications. Features: Closures unified with function pointers. Fast and concise iteration over a range or collection. Hello World in Swift: println('Hello World'); Kotlin is a statically typed, general-purpose programming language developed by JetBrains, that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011 and a new language for the JVM. Kotlin is an object-oriented language, and a “better language” than Java, but still be fully interoperable with Java code. Features: Functions and functional programming. Top-level objects and the Singleton pattern. Hello World in Kotlin: Kotlin fun main(args: Array<String>){ println("Hello World")} PHP started out as a small open source project that evolved as more and more people found out how useful it was. Rasmus Lerdorf unleashed the first version of PHP way back in 1994. PHP is a recursive acronym for “PHP: Hypertext Preprocessor”. PHP is a server-side scripting language that is embedded in HTML. It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites. Features: Loosely Typed Language. Error Reporting. PHP echo "Hello World"; Java was created at Sun Microsystems, Inc., where James Gosling led a team of researchers in an effort to create a new language that would allow consumer electronic devices to communicate with each other. Work on the language began in 1991, and before long the team’s focus changed to a new niche, the World Wide Web. Java was first released in 1995, and Java’s ability to provide interactivity and multimedia showed that it was particularly well suited for the Web. Features: Multi-Threaded. High Performance. Hello World in Java: Java /*package whatever //do not write package name here */ import java.io.*; class GFG { public static void main (String[] args) { System.out.println("Hello World"); }} Go language is a programming language initially developed at Google in the year 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. It is a statically-typed language having syntax similar to that of C. It provides garbage collection, type safety, dynamic-typing capability, many advanced built-in types such as variable length arrays and key-value maps. Features: Powerful Standard Library and Tool Set. Testing Capabilities. Hello World in Go: println('Hello World"); F#, pronounced as F sharp, is a strongly typed programming language. The language allows for more than one programming styles which makes it a multi-paradigm language. F# encompasses functional, imperative, and object-oriented programming techniques. The F# language belongs to the Microsoft .NET language family. Features: It provides type inference. It allows writing higher order functions. Hello World in F#: printfn "Hello World" LISP, in full list processing, a computer programming language developed about 1960 by John McCarthy at the Massachusetts Institute of Technology (MIT). LISP was founded on the mathematical theory of recursive functions (in which a function appears in its own definition). Features: It provides advanced object-oriented programming. It provides a convenient macro system. Hello World in Lisp: (print "Hello World") JavaScript is a lightweight, interpreted programming language. It is designed for creating network-centric applications. It is complimentary to and integrated with Java. JavaScript is very easy to implement because it is integrated with HTML. It is open and cross-platform. Features: Handling Dates and Time. Detecting the User’s browser and OS. Hello World in JavaScript: Javascript console.log("Hello World"); ALGOL, a computer programming language designed by an international committee of the Association of Computing Machinery (ACM), led by Alan J. Perlis of Carnegie Mellon University, during 1958–60 for publishing algorithms, as well as for doing computations. Features: Short For Algorithmic. Family of Many Programming Languages For Scientific Computations. Hello World in Algol: BEGIN DISPLAY("Hello World") END. Perl is a general purpose, high-level interpreted and dynamic programming language. Perl supports both procedural and Object-Oriented programming. Perl is a lot similar to C syntactically and is easy for the users who have knowledge of C, C++. Since Perl is a lot similar to other widely used languages syntactically, it is easier to code and learn in Perl. Programs can be written in Perl in any of the widely used text editors like Notepad++, gedit, etc. Features: Perl Provides supports for cross-platform, and it is compatible with mark-up languages like HTML, XML etc. It is free and an Open Source software that is licensed under Artistic and GNU General Public License (GPL). Hello World in Perl: Perl #!/usr/bin/perlprint "Hello World"; The Tcl programming language was created in the spring of 1988 by John Ousterhout while working at the University of California, Berkeley. Tcl is the acronym for “Tool Command Language” (it is pronounced “tickle”). Tcl is actually divided into two things: a language and a library. Tcl is a simple textual programming language, intended for issuing commands to interactive programs such as text editors, debuggers and shells. Features: Reduced development time. Quite easy to get started for experienced programmers; since, the language is so simple that they can learn Tcl in a few hours or days. Hello World in TCL: puts "Hello World" TypeScript is a programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript and adds optional static typing to the language. TypeScript is designed for the development of large applications and transcompiles to JavaScript. Features: TypeScript is portable across browsers, devices, and operating systems. It can run on any environment that JavaScript runs on. Unlike its counterparts, TypeScript doesn’t need a dedicated VM or a specific runtime environment to execute. Compiled TypeScript can be consumed from any JavaScript code. TypeScript-generated JavaScript can reuse all of the existing JavaScript frameworks, tools, and libraries. Hello World in TypeScript: console.log 'Hello World' FORTRAN was the world’s first high-level programming language. It was developed at IBM by a small team led by John Backus. The earliest version of FORTRAN was released in 1957 as a programming tool for the IBM 704. FORTRAN allows the subroutines to be written to execute the functions and provide the return values. FORTRAN supported the procedural programming language that allows the code to be written in an algorithmic way. Hello World in Fortran: program helloworld print *, "Hello World" end program helloworld Bash is a Unix shell and command language written by Brian Fox for the GNU Project as a free software replacement for the Bourne shell. The name is an acronym for the ‘ Bourne-Again Shell ‘, a pun on Stephen Bourne, the author of the direct ancestor of the current Unix shell sh , which appeared in the Seventh Edition Bell Labs Research version of Unix. Features : Supports Brace Expansion. Good Debugging. Hello World in Bash: echo "Hello World" HTML stands for Hyper Text Markup Language, which is the most widely used language on Web to develop web pages. HTML was created by Berners-Lee in late 1991 but “HTML 2.0” was the first standard HTML specification which was published in 1995. HTML 4.01 was a major version of HTML, and it was published in late 1999. Features: It is platform-independent. Images, videos, and audio can be added to a web page. Hello World in HTML: HTML <!DOCTYPE html><html> <head> </head> <body> <h1>Hello World<h1> </body></html> Hello World So this is how we can print “Hello World” in 30 different languages. sagar0719kumar Programming Basics Programming Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n14 Aug, 2021" }, { "code": null, "e": 396, "s": 53, "text": "In this article, we are going to see how to print “Hello World” in 30 different languages. It includes languages like C, C++, Cobol, Scala, Matlab, C#, CoffeeScript, Delphi, ...
Java.util.Arrays.equals() in Java with Examples
19 Apr, 2022 Today we are going to discuss the simplest way to check whether two arrays are equal or not. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order. Also, two array references are considered equal if both are null. Arrays class in java provide the method Arrays.equals() to check whether two arrays are equal or not. Syntax : public static boolean equals(int[] a, int[] a2) Parameters : a - one array to be tested for equality a2 - the other array to be tested for equality Returns : true if the two arrays are equal Other Variants: public static boolean equals(byte[] a, byte[] a2) public static boolean equals(short[] a, short[] a2) public static boolean equals(long[] a, long[] a2) public static boolean equals(float[] a, float[] a2) public static boolean equals(double[] a, double[] a2) public static boolean equals(char[] a, char[] a2) public static boolean equals(boolean[] a, boolean[] a2) public static boolean equals(Object[] a, Object[] a2) Java // Java program to demonstrate working of Arrays.equals() import java.util.Arrays; public class ArrayEqualDemo{ public static void main(String[] args) { // Let us create different integers arrays int[] arr1 = new int [] {1, 2, 3, 4}; int[] arr2 = new int [] {1, 2, 3, 4}; int[] arr3 = new int [] {1, 2, 4, 3}; System.out.println("is arr1 equals to arr2 : " + Arrays.equals(arr1, arr2)); System.out.println("is arr1 equals to arr3 : " + Arrays.equals(arr1, arr3)); }} Output: is arr1 equals to arr2 : true is arr1 equals to arr3 : false We can also use Arrays.equals() for checking equality of array of objects of user defined class.Have a look at last variant of the Arrays.equals() method Note :- In case of arrays of Objects, you must override equals method to provide your own definition of equality, otherwise you will get output depends on what equals() method of Object class returns. In the program below, we are checking equality of rollno, name, and address for a student. Java // Java program to demonstrate working of Arrays.equals()// for user defined objects. import java.util.Arrays; public class ArrayEqualDemo{ public static void main (String[] args) { Student [] arr1 = {new Student(111, "bbbb", "london"), new Student(131, "aaaa", "nyc"), new Student(121, "cccc", "jaipur")}; Student [] arr2 = {new Student(111, "bbbb", "london"), new Student(131, "aaaa", "nyc"), new Student(121, "cccc", "jaipur")}; Student [] arr3 = {new Student(111, "bbbb", "london"), new Student(121, "dddd", "jaipur"), new Student(131, "aaaa", "nyc"), }; System.out.println("is arr1 equals to arr2 : " + Arrays.equals(arr1, arr2)); System.out.println("is arr1 equals to arr3 : " + Arrays.equals(arr1, arr3)); } } // A class to represent a student.class Student{ int rollno; String name, address; // Constructor public Student(int rollno, String name, String address) { this.rollno = rollno; this.name = name; this.address = address; } @Override public boolean equals(Object obj) { // typecast obj to Student so that we can compare students Student s = (Student) obj; return this.rollno == s.rollno && this.name.equals(s.name) && this.address.equals(s.address); }} Output: is arr1 equals to arr2 : true is arr1 equals to arr3 : false Note: String.equals() can be only performed to 1-D arrays and hence it doesn’t work for multidimensional arrays. Use Arrays.deepEquals(Object[], Object[]) instead , it returns true if the two specified arrays are deeply equal to each other. Java import java.util.Arrays; public class ArrayEqualDemo_2 { public static void main(String[] args) { // Let us create array of arrays int[][] arr1 = { { 0, 1 }, { 1, 0 } }; int[][] arr2 = { { 0, 1 }, { 1, 0 } }; System.out.println("is arr1 equals to arr2 : " + Arrays.equals(arr1, arr2)); System.out.println("is arr1 deepequals to arr2 : " + Arrays.deepEquals(arr1, arr2)); }} Output: is arr1 equals to arr2 : false is arr1 deepequals to arr2 : true This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. debankanmitra sagartomar9927 Java - util 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 Multidimensional Arrays in Java Set in Java Initializing a List in Java Collections in Java Stream In Java
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Apr, 2022" }, { "code": null, "e": 556, "s": 52, "text": "Today we are going to discuss the simplest way to check whether two arrays are equal or not. Two arrays are considered equal if both arrays contain the same number of element...
Convert Directed Graph into a Tree
23 Jun, 2021 Given an array arr[] of size N. There is an edge from i to arr[i]. The task is to convert this directed graph into tree by changing some of the edges. If for some i, arr[i] = i then i represents the root of the tree. In case of multiple answers print any of them.Examples: Input: arr[] = {6, 6, 0, 1, 4, 3, 3, 4, 0} Output: {6, 6, 0, 1, 4, 3, 4, 4, 0} Input: arr[] = {1, 2, 0}; Output: {0, 2, 0}. Approach: Consider the 2nd example image above which shows an example of a functional graph. It consists of two cycles 1, 6, 3 and 4. Our goal is to make the graph consisting of exactly one cycle of exactly one vertex looped to itself.Operation of change is equivalent to removing some outgoing edge and adding a new one, going to somewhat else vertex. Let’s firstly make our graph containing only one cycle. To do so, one can choose any of initially presented cycles and say that it will be the only one. Then one should consider every other cycle, remove any of its in-cycle edges and replace it with an edge going to any of the chosen cycle’s vertices. Thus the cycle will be broken and its vertices (along with tree ones) will be connected to the only chosen cycle. One will need to do exactly cycleCount – 1 such operations. Note that the removing of any non-cycle edge does not make sense, because it does not break any cycle.The next thing is to make the cycle length be equal to 1. That might be already satisfied, if one will choose a cycle of minimal length and this length equals 1. Thus, if the initial graph contains any cycle of length 1, we are done with cycleCount – 1 operations. Otherwise, the cycle contains more than one vertex. It can be fixed with exactly one operation – one just needs to break any of in-cycle edges, say from u to arr[u], and add an edge from u to u. The graph will remain consisting of one cycle, but consisting of one self-looped vertex. In that case, we are done with cycleCount operations.To do all the operations above, one can use DSU structure, or just a series of DFS. Note that there is no need in realisation of edge removing and creating, one just needs to analyze initial graph.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // CPP program to convert directed graph into tree#include <bits/stdc++.h>using namespace std; // Function to find root of the vertexint find(int x, int a[], int vis[], int root[]){ if (vis[x]) return root[x]; vis[x] = 1; root[x] = x; root[x] = find(a[x], a, vis, root); return root[x];} // Function to convert directed graph into treevoid Graph_to_tree(int a[], int n){ // Vis array to check if an index is visited or not // root[] array is to store parent of each vertex int vis[n] = { 0 }, root[n] = { 0 }; // Find parent of each parent for (int i = 0; i < n; i++) find(a[i], a, vis, root); // par stores the root of the resulting tree int par = -1; for (int i = 0; i < n; i++) if (i == a[i]) par = i; // If no self loop exists if (par == -1) { for (int i = 0; i < n; i++) { // Make vertex in a cycle as root of the tree if (i == find(a[i], a, vis, root)) { par = i; a[i] = i; break; } } } // Remove all cycles for (int i = 0; i < n; i++) { if (i == find(a[i], a, vis, root)) { a[i] = par; } } // Print the resulting array for (int i = 0; i < n; i++) cout << a[i] << " ";} // Driver code to test above functionsint main(){ int a[] = { 6, 6, 0, 1, 4, 3, 3, 4, 0 }; int n = sizeof(a) / sizeof(a[0]); // Function call Graph_to_tree(a, n);} // Java program to convert// directed graph into treeimport java.util.*; class GFG{ // Function to find root of the vertexstatic int find(int x, int a[], int vis[], int root[]){ if (vis[x] == 1) return root[x]; vis[x] = 1; root[x] = x; root[x] = find(a[x], a, vis, root); return root[x];} // Function to convert directed graph into treestatic void Graph_to_tree(int a[], int n){ // Vis array to check if an index is // visited or not root[] array is to // store parent of each vertex int []vis = new int[n]; int []root = new int[n]; // Find parent of each parent for (int i = 0; i < n; i++) find(a[i], a, vis, root); // par stores the root of the resulting tree int par = -1; for (int i = 0; i < n; i++) if (i == a[i]) par = i; // If no self loop exists if (par == -1) { for (int i = 0; i < n; i++) { // Make vertex in a cycle as root of the tree if (i == find(a[i], a, vis, root)) { par = i; a[i] = i; break; } } } // Remove all cycles for (int i = 0; i < n; i++) { if (i == find(a[i], a, vis, root)) { a[i] = par; } } // Print the resulting array for (int i = 0; i < n; i++) System.out.print(a[i] + " ");} // Driver Codestatic public void main ( String []arr){ int a[] = { 6, 6, 0, 1, 4, 3, 3, 4, 0 }; int n = a.length; // Function call Graph_to_tree(a, n);}} // This code is contributed by 29AjayKumar # A Python3 program to convert# directed graph into tree # Function to find root of the vertexdef find(x, a, vis, root): if vis[x]: return root[x] vis[x] = 1 root[x] = x root[x] = find(a[x], a, vis, root) return root[x] # Function to convert directed graph into treedef Graph_To_Tree(a, n): # Vis array to check if an index is visited or not # root[] array is to store parent of each vertex vis = [0] * n root = [0] * n # Find parent of each parent for i in range(n): find(a[i], a, vis, root) # par stores the root of the resulting tree par = -1 for i in range(n): if i == a[i]: par = i # If no self loop exists if par == -1: for i in range(n): # Make vertex in a cycle as root of the tree if i == find(a[i], a, vis, root): par = i a[i] = i break # Remove all cycles for i in range(n): if i == find(a[i], a, vis, root): a[i] = par # Print the resulting array for i in range(n): print(a[i], end = " ") # Driver Codeif __name__ == "__main__": a = [6, 6, 0, 1, 4, 3, 3, 4, 0] n = len(a) # Function call Graph_To_Tree(a, n) # This code is contributed by# sanjeev2552 // C# program to convert// directed graph into treeusing System;using System.Collections.Generic; class GFG{ // Function to find root of the vertexstatic int find(int x, int []a, int []vis, int []root){ if (vis[x] == 1) return root[x]; vis[x] = 1; root[x] = x; root[x] = find(a[x], a, vis, root); return root[x];} // Function to convert directed graph into treestatic void Graph_to_tree(int []a, int n){ // Vis array to check if an index is // visited or not root[] array is to // store parent of each vertex int []vis = new int[n]; int []root = new int[n]; // Find parent of each parent for (int i = 0; i < n; i++) find(a[i], a, vis, root); // par stores the root of the resulting tree int par = -1; for (int i = 0; i < n; i++) if (i == a[i]) par = i; // If no self loop exists if (par == -1) { for (int i = 0; i < n; i++) { // Make vertex in a cycle as root of the tree if (i == find(a[i], a, vis, root)) { par = i; a[i] = i; break; } } } // Remove all cycles for (int i = 0; i < n; i++) { if (i == find(a[i], a, vis, root)) { a[i] = par; } } // Print the resulting array for (int i = 0; i < n; i++) Console.Write(a[i] + " ");} // Driver Codestatic public void Main ( String []arr){ int []a = { 6, 6, 0, 1, 4, 3, 3, 4, 0 }; int n = a.Length; // Function call Graph_to_tree(a, n);}} // This code is contributed by Princi Singh <script> // Javascript program to convert// directed graph into tree // Function to find root of the vertexfunction find(x, a, vis, root){ if (vis[x] == 1) return root[x]; vis[x] = 1; root[x] = x; root[x] = find(a[x], a, vis, root); return root[x];} // Function to convert directed graph into treefunction Graph_to_tree(a, n){ // Vis array to check if an index is // visited or not root[] array is to // store parent of each vertex var vis = Array(n).fill(0); var root = Array(n).fill(0); // Find parent of each parent for (var i = 0; i < n; i++) find(a[i], a, vis, root); // par stores the root of the resulting tree var par = -1; for (var i = 0; i < n; i++) if (i == a[i]) par = i; // If no self loop exists if (par == -1) { for (var i = 0; i < n; i++) { // Make vertex in a cycle as root of the tree if (i == find(a[i], a, vis, root)) { par = i; a[i] = i; break; } } } // Remove all cycles for (var i = 0; i < n; i++) { if (i == find(a[i], a, vis, root)) { a[i] = par; } } // Print the resulting array for (var i = 0; i < n; i++) document.write(a[i] + " ");} // Driver Codevar a = [6, 6, 0, 1, 4, 3, 3, 4, 0];var n = a.length; // Function callGraph_to_tree(a, n); // This code is contributed by rrrtnx.</script> 6 6 0 1 4 3 4 4 0 29AjayKumar princi singh nidhi_biet sanjeev2552 rrrtnx Graph Tree Graph Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jun, 2021" }, { "code": null, "e": 303, "s": 28, "text": "Given an array arr[] of size N. There is an edge from i to arr[i]. The task is to convert this directed graph into tree by changing some of the edges. If for some i, arr[i] = ...
errors.New() Function in Golang with Examples
03 May, 2020 Errors package in Golang is used to implement the functions to manipulate the errors. errors.New()function returns an error that formats like given text. Each call to New returns distinct error value indeed in the event that the content is indistinguishable. Syntax: func New(text string) error It returns an error. Example 1: // Golang program to illustrate// the errors.new() function package main import ( "errors" "fmt")// Main functionfunc main() { err := errors.New("Sample Error") if err != nil { fmt.Print(err) }} Output: Sample Error Example 2: // Golang program to illustrate// the errors.new() functionpackage main import ( "errors" "fmt") // Main functionfunc main() { err := errors.New("It Says Error!") if err != nil { fmt.Print(err) }} Output: It Says Error! Golang-errors 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": "\n03 May, 2020" }, { "code": null, "e": 287, "s": 28, "text": "Errors package in Golang is used to implement the functions to manipulate the errors. errors.New()function returns an error that formats like given text. Each call to New retu...
Matplotlib.axes.Axes.invert_xaxis() in Python
19 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. The Axes.invert_xaxis() function in axes module of matplotlib library is used to invert the x-axis. Syntax: Axes.invert_xaxis(self) Parameters: This method does not accepts any parameters. Returns:This method does not returns any value. Below examples illustrate the matplotlib.axes.Axes.invert_xaxis() function in matplotlib.axes: Example 1: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np X = np.arange(-20, 20, 0.5)Y = np.arange(-20, 20, 0.5)U, V = np.meshgrid(X, Y) fig, ax = plt.subplots()ax.quiver(X, Y, U, V)w = ax.invert_xaxis()ax.set_title('matplotlib.axes.Axes.invert_xaxis() \Example', fontsize = 14, fontweight ='bold')plt.show() Output: Example 2: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np x = np.linspace(0, 200, 10)yy = np.transpose([2 * np.sin(x + phi) for phi in x]) fig, ax = plt.subplots()ax.plot(yy)w = ax.invert_xaxis()ax.set_title('matplotlib.axes.Axes.invert_xaxis() \Example', fontsize = 14, fontweight ='bold')plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Apr, 2020" }, { "code": null, "e": 328, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text...
Data Structures and Algorithms | Set 1
12 Dec, 2021 Following questions have been asked in GATE CS exam 1. Let LASTPOST, LASTIN and LASTPRE denote the last vertex visited in a postorder, inorder and preorder traversal. Respectively, of a complete binary tree. Which of the following is always true? (GATE CS 2000) (a) LASTIN = LASTPOST (b) LASTIN = LASTPRE (c) LASTPRE = LASTPOST (d) None of the above Answer (d) It is given that the given tree is complete binary tree. For a complete binary tree, the last visited node will always be same for inorder and preorder traversal. None of the above is true even for a complete binary tree. The option (a) is incorrect because the last node visited in Inorder traversal is right child and last node visited in Postorder traversal is root. The option (c) is incorrect because the last node visited in Preorder traversal is right child and last node visited in Postorder traversal is root. For option (b), see the following counter example. Thanks to Hunaif Muhammed for providing the correct explanation. 1 / \ 2 3 / \ / 4 5 6 Inorder traversal is 4 2 5 1 6 3 Preorder traversal is 1 2 4 5 3 6 2. The most appropriate matching for the following pairs X: depth first search 1: heap Y: breadth-first search 2: queue Z: sorting 3: stack is (GATE CS 2000): (a) X—1 Y—2 Z-3 (b) X—3 Y—1 Z-2 (c) X—3 Y—2 Z-1 (d) X—2 Y—3 Z-1 Answer: (c) Stack is used for Depth first Search Queue is used for Breadth First Search Heap is used for sorting 3. Consider the following nested representation of binary trees: (X Y Z) indicates Y and Z are the left and right sub stress, respectively, of node X. Note that Y and Z may be NULL, or further nested. Which of the following represents a valid binary tree? (a) (1 2 (4 5 6 7)) (b) (1 (2 3 4) 5 6) 7) (c) (1 (2 3 4)(5 6 7)) (d) (1 (2 3 NULL) (4 5)) Answer (c) 4. Let s be a sorted array of n integers. Let t(n) denote the time taken for the most efficient algorithm to determined if there are two elements with sum less than 1000 in s. which of the following statements is true? (GATE CS 2000) a) t (n) is 0 (1) b) n < t (n) < n log2n c) n log2n < t (n) < nC2 d) t (n) = nC2 Answer (a) Let array be sorted in ascending order, if sum of first two elements is less than 1000 then there are two elements with sum less than 1000 otherwise not. For array sorted in descending order we need to check last two elements. For an array data structure, number of operations are fixed in both the cases and not dependent on n, complexity is O(1) 5. B+ trees are preferred to binary trees in databases because (GATE CS 2000) (a) Disk capacities are greater than memory capacities (b) Disk access is much slower than memory access (c) Disk data transfer rates are much less than memory data transfer rates (d) Disks are more reliable than memory Answer (b) Disk access is slow and B+ Tree provide search in less number of disk hits. This is primarily because unlike binary search trees, B+ trees have very high fanout (typically on the order of 100 or more), which reduces the number of I/O operations required to find an element in the tree. surinderdawra388 marjanakhathimaav GATE-CS-DS-&-Algo GATE CS MCQ Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Page Replacement Algorithms in Operating Systems Inter Process Communication (IPC) Introduction of Operating System - Set 1 Semaphores in Process Synchronization Differences between TCP and UDP Operating Systems | Set 1 Practice questions on Height balanced/AVL Tree Data Structures and Algorithms | Set 10 Data Structures and Algorithms | Set 16 Data Structures and Algorithms | Set 11
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Dec, 2021" }, { "code": null, "e": 105, "s": 52, "text": "Following questions have been asked in GATE CS exam " }, { "code": null, "e": 404, "s": 105, "text": "1. Let LASTPOST, LASTIN and LASTPRE denote the last ...
Python | Remove the given substring from end of string
07 Jun, 2019 Sometimes we need to manipulate our string to remove extra information from string for better understanding and faster processing. Given a task in which substring needs to be removed from the end of the string. Given below are a few methods to solve the given task. Method #1: Using Naive Method # Python3 code to demonstrate# to remove a substring from end of the string # Initialising stringini_string = 'xbzefdgstb' # initializing stringsstring = 'stb' # printing initial string and substringprint ("initial_strings : ", ini_string, "\nsubstring : ", sstring) # removing substring from end# of string using Naive Methodif ini_string.endswith(sstring): res = ini_string[:-(len(sstring))] # printing resultprint ("resultant string", res) initial_strings : xbzefdgstb substring : stb resultant string xbzefdg Method #2: Using sub() method # Python3 code to demonstrate# to remove a substring from end of string import re # Initialising stringini_string = 'xbzefdgstb' # initializing stringsstring = 'stb' # printing initial string and substringprint ("initial_strings : ", ini_string, "\nsubstring : ", sstring) # removing substring from end# of string using sub Methodif ini_string.endswith(sstring): res = re.sub(sstring, '', ini_string) # printing resultprint ("resultant string", res) initial_strings : xbzefdgstb substring : stb resultant string xbzefdg Method #3: Using replace() method # Python3 code to demonstrate# to remove a substring from end of string # Initialising stringini_string = 'xbzefdgstb' # initializing stringsstring = 'stb' # printing initial string and substringprint ("initial_strings : ", ini_string, "\nsubstring : ", sstring) # removing substring from end# of string using replace Methodif ini_string.endswith(sstring): res = ini_string.replace(sstring, '') # printing resultprint ("resultant string", res) initial_strings : xbzefdgstb substring : stb resultant string xbzefdg 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": "\n07 Jun, 2019" }, { "code": null, "e": 295, "s": 28, "text": "Sometimes we need to manipulate our string to remove extra information from string for better understanding and faster processing. Given a task in which substring needs to be ...
Change view of Tensor in Pytorch - GeeksforGeeks
30 Jun, 2021 In this article, we are going to change the view of the given tensor in PyTorch. For this, we will use view() function to be used to change the tensor in two-dimensional format IE rows and columns. We have to specify the number of rows and the number of columns to be viewed. Syntax: tensor.view(no_of_rows,no_of_columns) Example 1: Python program to create a tensor with 10 elements and view with 5 rows and 2 columns and vice versa Python3 # importing torch moduleimport torch # create one dimensional tensor # 10 elementsa = torch.FloatTensor([10, 20, 30, 40, 50, 1, 2, 3, 4, 5]) # view tensor in 5 rows and 2# columnsprint(a.view(5, 2)) # view tensor in 2 rows and 5 # columnsprint(a.view(2, 5)) Output: Example 2: Change the view of a tensor into 4 rows and 3 columns and vice versa Python3 # importing torch moduleimport torch # create one dimensional tensor 12 elementsa = torch.FloatTensor([34, 56, 10, 20, 30, 40, 50, 1, 2, 3, 4, 5]) # view tensor in 4 rows and 3 columnsprint(a.view(4, 3)) # view tensor in 3 rows and 4 columnsprint(a.view(3, 4)) Output: Picked Python-PyTorch Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n30 Jun, 2021" }, { "code": null, "e": 25813, "s": 25537, "text": "In this article, we are going to change the view of the given tensor in PyTorch. For this, we will use view() function to be used to change the tensor in two-dimen...
Matplotlib.axes.Axes.stem() in Python - GeeksforGeeks
13 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. The Axes.stem() function in axes module of matplotlib library is used to create a stem plot. Syntax: Axes.stem(self, *args, linefmt=None, markerfmt=None, basefmt=None, bottom=0, label=None, use_line_collection=False, data=None) Parameters: This method accept the following parameters that are described below: x: This parameter is the sequence of x coordinates of the stems. y: This parameter is the sequence of y coordinates of the stem heads. linefmt: This parameter is the string defining the properties of the vertical lines. markerfmt: This parameter is the string defining the properties of the markers at the stem heads. basefmt: This parameter is the string defining the properties of the baseline. bottom: This parameter is the y-position of the baseline. label: This parameter is the label to use for the stems in legends. Returns: This returns the following: StemContainer: This returns the container which may be treated like a tuple (markerline, stemlines, baseline). Below examples illustrate the matplotlib.axes.Axes.broken_barh() function in matplotlib.axes: Example-1: # Implementation of matplotlib functionimport matplotlib.pyplot as plt fig, ax = plt.subplots() ax.stem([0.3, 1.5, 2.7], [1, 3.6, 2.7], label ="stem test") ax.legend()ax.set_title('matplotlib.axes.Axes.stem Example')plt.show() Output:Example-2: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np x = np.linspace(0.1, 2 * np.pi, 41)y = np.exp(np.sin(x)) fig, ax = plt.subplots() ax.stem(x, y, linefmt ='grey', markerfmt ='D', bottom = 1.1, use_line_collection = True) ax.set_title('matplotlib.axes.Axes.stem Example')plt.show() Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n13 Apr, 2020" }, { "code": null, "e": 25837, "s": 25537, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, ...
Sum of Array maximums after K operations by reducing max element to its half - GeeksforGeeks
20 Jan, 2022 Given an array arr[] of N integers and an integer K, the task is to find the sum of maximum of the array possible wherein each operation the current maximum of the array is replaced with its half. Example: Input: arr[] = {2, 4, 6, 8, 10}, K = 5Output: 33Explanation: In 1st operation, the maximum of the given array is 10. Hence, the value becomes 10 and the array after 1st operation becomes arr[] = {2, 4, 6, 8, 5}. The value after 2nd operation = 18 and arr[] = {2, 4, 6, 4, 5}. Similarly, proceeding forward, value after 5th operation will be 33. Input: arr[] = {6, 5}, K = 3Output: 14 Approach: The given problem can be solved with the help of a greedy approach. The idea is to use a max heap data structure. Therefore, traverse the given array and insert all the elements in the array arr[] into a max priority queue. At each operation, remove the maximum from the heap using pop operation, add it to the value and reinsert the value after dividing it by two into the heap. The value after repeating the above operation K times is the required answer. Below is the implementation of the above approach: C++ Java Python3 // C++ program of the above approach#include <bits/stdc++.h>using namespace std; // Function to find maximum possible// value after K given operationsint maxValue(vector<int> arr, int K){ // Stores required value int val = 0; // Initializing priority queue // with all elements of array priority_queue<int> pq(arr.begin(), arr.end()); // Loop to iterate through // each operation while (K--) { // Current Maximum int max = pq.top(); pq.pop(); // Update value val += max; // Reinsert maximum pq.push(max / 2); } // Return Answer return val;} // Driver Callint main(){ vector<int> arr = { 2, 4, 6, 8, 10 }; int K = 5; cout << maxValue(arr, K);} // Java code for the above approachimport java.util.Comparator;import java.util.PriorityQueue;class CustomComparator implements Comparator<Integer> { @Override public int compare(Integer number1, Integer number2) { int value = number1.compareTo(number2); // elements are sorted in reverse order if (value > 0) { return -1; } else if (value < 0) { return 1; } else { return 0; } }}class GFG { // Function to find maximum possible // value after K given operations static int maxValue(int[] arr, int K) { // Stores required value int val = 0; // Initializing priority queue // with all elements of array PriorityQueue<Integer> pq = new PriorityQueue<Integer>(new CustomComparator()); for (int i = 0; i < arr.length; i++) { pq.add(arr[i]); } // Loop to iterate through // each operation while (K != 0) { // Current Maximum int max = pq.poll(); // Update value val += max; // Reinsert maximum pq.add((int)Math.floor(max / 2)); K = K - 1; } // Return Answer return val; } // Driver Call public static void main(String[] args) { int[] arr = { 2, 4, 6, 8, 10 }; int K = 5; System.out.println(maxValue(arr, K)); }} // This code is conbtributed by Potta Lokesh # python3 program of the above approachfrom queue import PriorityQueue # Function to find maximum possible# value after K given operationsdef maxValue(arr, K): # Stores required value val = 0 # Initializing priority queue # with all elements of array pq = PriorityQueue() for dt in arr: pq.put(-1*dt) # Loop to iterate through # each operation while (True): # Current Maximum max = -1 * pq.get() # Update value val += max # Reinsert maximum pq.put(-1 * (max // 2)) K -= 1 if K == 0: break # Return Answer return val # Driver Callif __name__ == "__main__": arr = [2, 4, 6, 8, 10] K = 5 print(maxValue(arr, K)) # This code is contributed by rakeshsahni 33 Time Complexity: O(K*log N)Auxiliary Space: O(N) rakeshsahni lokeshpotta20 Algo-Geek 2021 Algo Geek Arrays Heap Queue Arrays Queue Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check if the given string is valid English word or not Sort strings on the basis of their numeric part Divide given number into two even parts Smallest set of vertices to visit all nodes of the given Graph Count of Palindrome Strings in given Array of strings Arrays in Java Arrays in C/C++ Maximum and minimum of an array using minimum number of comparisons Write a program to reverse an array or string Program for array rotation
[ { "code": null, "e": 27355, "s": 27327, "text": "\n20 Jan, 2022" }, { "code": null, "e": 27552, "s": 27355, "text": "Given an array arr[] of N integers and an integer K, the task is to find the sum of maximum of the array possible wherein each operation the current maximum of the...
PyQt5 – Set status bar message in window - GeeksforGeeks
26 Mar, 2020 In this article, we will see how to set message to status bar of window. A status bar is a graphical control element which poses an information area typically found at the window’s bottom. It can be divided into sections to group information. Its job is primarily to display information about the current state of its window. In order to do this we will use showMessage() method. Syntax : self.statusBar().showMessage(message) Argument : It takes string as argument. Action performed : It sets the message to status bar. Code : from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Python") # setting the geometry of window self.setGeometry(60, 60, 600, 400) # setting status bar message self.statusBar().showMessage("this is status bar") # creating a label widget self.label_1 = QLabel("Status Bar", self) # moving position self.label_1.move(100, 100) # setting up the border self.label_1.setStyleSheet("border :5px solid blue;") # resizing label self.label_1.resize(80, 100) # 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. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26251, "s": 26223, "text": "\n26 Mar, 2020" }, { "code": null, "e": 26577, "s": 26251, "text": "In this article, we will see how to set message to status bar of window. A status bar is a graphical control element which poses an information area typically foun...
Feistel Cipher - GeeksforGeeks
24 Feb, 2022 Feistel Cipher model is a structure or a design used to develop many block ciphers such as DES. Feistel cipher may have invertible, non-invertible and self invertible components in its design. Same encryption as well as decryption algorithm is used. A separate key is used for each round. However same round keys are used for encryption as well as decryption. Create a list of all the Plain Text characters. Convert the Plain Text to Ascii and then 8-bit binary format. Divide the binary Plain Text string into two halves: left half (L1)and right half (R1) Generate a random binary keys (K1 and K2) of length equal to the half the length of the Plain Text for the two rounds. First Round of Encryption a. Generate function f1 using R1 and K1 as follows: f1= xor(R1, K1) b. Now the new left half(L2) and right half(R2) after round 1 are as follows: R2= xor(f1, L1) L2=R1 Second Round of Encryption a. Generate function f2 using R2 and K2 as follows: f2= xor(R2, K2) b. Now the new left half(L3) and right half(R3) after round 2 are as follows: R3= xor(f2, L2) L3=R2 Concatenation of R3 to L3 is the Cipher Text Same algorithm is used for decryption to retrieve the Plain Text from the Cipher Text. Examples: Plain Text is: Hello Cipher Text: E1!w( Retrieved Plain Text is: b'Hello' Plain Text is: Geeks Cipher Text: O;Q Retrieved Plain Text is: b'Geeks' Python3 # Python program to demonstrate# Feistel Cipher Algorithm import binascii # Random bits key generationdef rand_key(p): import random key1 = "" p = int(p) for i in range(p): temp = random.randint(0,1) temp = str(temp) key1 = key1 + temp return(key1) # Function to implement bit exordef exor(a,b): temp = "" for i in range(n): if (a[i] == b[i]): temp += "0" else: temp += "1" return temp # Defining BinarytoDecimal() functiondef BinaryToDecimal(binary): # Using int function to convert to # string string = int(binary, 2) return string # Feistel CipherPT = "Hello"print("Plain Text is:", PT) # Converting the plain text to# ASCIIPT_Ascii = [ord(x) for x in PT] # Converting the ASCII to# 8-bit binary formatPT_Bin = [format(y,'08b') for y in PT_Ascii]PT_Bin = "".join(PT_Bin) n = int(len(PT_Bin)//2)L1 = PT_Bin[0:n]R1 = PT_Bin[n::]m = len(R1) # Generate Key K1 for the# first roundK1= rand_key(m) # Generate Key K2 for the# second roundK2= rand_key(m) # first round of Feistelf1 = exor(R1,K1)R2 = exor(f1,L1)L2 = R1 # Second round of Feistelf2 = exor(R2,K2)R3 = exor(f2,L2)L3 = R2 # Cipher textbin_data = L3 + R3str_data =' ' for i in range(0, len(bin_data), 7): # slicing the bin_data from index range [0, 6] # and storing it in temp_data temp_data = bin_data[i:i + 7] # passing temp_data in BinarytoDecimal() function # to get decimal value of corresponding temp_data decimal_data = BinaryToDecimal(temp_data) # Decoding the decimal value returned by # BinarytoDecimal() function, using chr() # function which return the string corresponding # character for given ASCII value, and store it # in str_data str_data = str_data + chr(decimal_data) print("Cipher Text:", str_data) # DecryptionL4 = L3R4 = R3 f3 = exor(L4,K2)L5 = exor(R4,f3)R5 = L4 f4 = exor(L5,K1)L6 = exor(R5,f4)R6 = L5PT1 = L6+R6 PT1 = int(PT1, 2)RPT = binascii.unhexlify( '%x'% PT1)print("Retrieved Plain Text is: ", RPT) Output: Plain Text is: Hello Cipher Text: E1!w( Retrieved Plain Text is: b'Hello' Akanksha_Rai surindertarika1234 malikhushbu6 cryptography python-utility Python cryptography Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python
[ { "code": null, "e": 25781, "s": 25753, "text": "\n24 Feb, 2022" }, { "code": null, "e": 26143, "s": 25781, "text": "Feistel Cipher model is a structure or a design used to develop many block ciphers such as DES. Feistel cipher may have invertible, non-invertible and self inverti...
HashSet toArray() method in Java with Example - GeeksforGeeks
24 Dec, 2018 The toArray() method of Java HashSet is used to form an array of the same elements as that of the HashSet. Basically, it copies all the element from a HashSet to a new array. Syntax: Object[] arr = HashSet.toArray() Parameters: The method does not take any parameters. Return Value: The method returns an array containing the elements similar to the HashSet. Below programs illustrate the HashSet.toArray() method: Program 1: // Java code to illustrate toArray() import java.util.*; public class HashSetDemo { public static void main(String args[]) { // Creating an empty HashSet HashSet<String> abs_col = new HashSet<String>(); // Use add() method to add // elements into the HashSet abs_col.add("Welcome"); abs_col.add("To"); abs_col.add("Geeks"); abs_col.add("For"); abs_col.add("Geeks"); // Displaying the HashSet System.out.println("The HashSet: " + abs_col); // Creating the array and using toArray() Object[] arr = abs_col.toArray(); System.out.println("The array is:"); for (int j = 0; j < arr.length; j++) System.out.println(arr[j]); }} The HashSet: [Geeks, For, Welcome, To] The array is: Geeks For Welcome To Program 2: // Java code to illustrate toArray() import java.util.*; public class HashSetDemo { public static void main(String args[]) { // Creating an empty HashSet HashSet<Integer> abs_col = new HashSet<Integer>(); // Use add() method to add // elements into the HashSet abs_col.add(10); abs_col.add(15); abs_col.add(30); abs_col.add(20); abs_col.add(5); abs_col.add(25); // Displaying the HashSet System.out.println("The HashSet: " + abs_col); // Creating the array and using toArray() Object[] arr = abs_col.toArray(); System.out.println("The array is:"); for (int j = 0; j < arr.length; j++) System.out.println(arr[j]); }} The HashSet: [20, 5, 25, 10, 30, 15] The array is: 20 5 25 10 30 15 Java - util package Java-Collections Java-Functions java-hashset Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java Stream In Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java Multithreading in Java Collections in Java Queue Interface In Java
[ { "code": null, "e": 25575, "s": 25547, "text": "\n24 Dec, 2018" }, { "code": null, "e": 25750, "s": 25575, "text": "The toArray() method of Java HashSet is used to form an array of the same elements as that of the HashSet. Basically, it copies all the element from a HashSet to a...
Java Program for Activity Selection Problem | Greedy Algo-1 - GeeksforGeeks
22 Aug, 2019 You are given n activities with their start and finish times. Select the maximum number of activities that can be performed by a single person, assuming that a person can only work on a single activity at a time.Example: Example 1 : Consider the following 3 activities sorted by finish time. start[] = {10, 12, 20}; finish[] = {20, 25, 30}; A person can perform at most two activities. The maximum set of activities that can be executed is {0, 2} [ These are indexes in start[] and finish[] ] Example 2 : Consider the following 6 activities sorted by by finish time. start[] = {1, 3, 0, 5, 8, 5}; finish[] = {2, 4, 6, 7, 9, 9}; A person can perform at most four activities. The maximum set of activities that can be executed is {0, 1, 3, 4} [ These are indexes in start[] and finish[] ] Java // The following implementation assumes that the activities// are already sorted according to their finish timeimport java.util.*;import java.lang.*;import java.io.*; class ActivitySelection { // Prints a maximum set of activities that can be done by a single // person, one at a time. // n --> Total number of activities // s[] --> An array that contains start time of all activities // f[] --> An array that contains finish time of all activities public static void printMaxActivities(int s[], int f[], int n) { int i, j; System.out.print("Following activities are selected : n"); // The first activity always gets selected i = 0; System.out.print(i + " "); // Consider rest of the activities for (j = 1; j < n; j++) { // If this activity has start time greater than or // equal to the finish time of previously selected // activity, then select it if (s[j] >= f[i]) { System.out.print(j + " "); i = j; } } } // driver program to test above function public static void main(String[] args) { int s[] = { 1, 3, 0, 5, 8, 5 }; int f[] = { 2, 4, 6, 7, 9, 9 }; int n = s.length; printMaxActivities(s, f, n); }} Following activities are selected : n0 1 3 4 Please refer complete article on Activity Selection Problem | Greedy Algo-1 for more details! nidhi_biet Java Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate Over the Characters of a String in Java How to Get Elements By Index from HashSet in Java? Java Program to Write into a File Java Program to Read a File to String How to Write Data into Excel Sheet using Java? How to Replace a Element in Java ArrayList? Java Program to Find Sum of Array Elements Tic-Tac-Toe Game in Java Removing last element from ArrayList in Java Comparing two ArrayList In Java
[ { "code": null, "e": 26132, "s": 26104, "text": "\n22 Aug, 2019" }, { "code": null, "e": 26353, "s": 26132, "text": "You are given n activities with their start and finish times. Select the maximum number of activities that can be performed by a single person, assuming that a per...
C++17 new feature : If Else and Switch Statements with initializers - GeeksforGeeks
27 Jan, 2018 In many cases, we need to check the value of something returned by a function and perform conditional operations based on this value. So our code looks something like this // Some functionreturn_type foo(params) // Call function with params and // store return in varauto var = foo(params); if (var == /* some value */) { //Do Something} else { //Do Something else} While this is alright, notice that there are a few subtleties The variable leaks into the surrounding scope, which is not intended and care must be taken to ensure that this variable doesn’t get mixed up with other variables Since this variable has already been defined, if we were to call another function (say bar()) later in the program we would need to create another variable to store the values returned from bar() Thirdly, if the compiler can know explicitly that the variable is going to be used only in one if-else block then it may be able to better optimize the code. Notice the general format in all conditional if-else blocks. Firstly there is an optional initial statement which sets up the variable, followed by the if-else block. So the general if-else block resembles as follows init-statement if (condition) { // Do Something } else { // Do Something else } In C++17 the init statement is called an initializer, and we can directly put it into the if-else block as follows if (init-statement; condition) { // Do Something } else { // Do Something else } The scope of the conditioned variable gets limited to the current if-else block. This also allows us to reuse the same named identifier in another conditional block. if (auto var = foo(); condition) { ...}else{ ...} // Another if-else blockif (auto var = bar(); condition) { ....}else { ....} Likewise the switch case block has been updated. We can now put an initial expression inside the switch parenthesis. After the initial statement we need to specify which variable is being used to check the cases switch (initial-statement; variable) { .... // cases } A complete program // Program to demonstrate init if-else// feature introduced in C++17#include <iostream>#include <cstdlib>using namespace std; int main() { // Set up rand function to be used // later in program srand(time(NULL)); // Before C++17 int i = 2; if ( i % 2 == 0) cout << i << " is even number" << endl; // After C++17 // if(init-statement; condition) if (int i = 4; i % 2 == 0 ) cout << i << " is even number" << endl; // Switch statement // switch(init;variable) switch (int i = rand() % 100; i) { default: cout << "i = " << i << endl; break; } } Output (Machine Dependent) 2 is even number 4 is even number i = 5 Note: To compile these programs we need latest versions of compilers. As of writing this article this feature has been completely implemented in clang 5 and gcc 7 onwards. To compile the programs we also need to specify the -std=c++17 flag g++-7 program_file.cpp -std=c++17 or clang++ program_file.cpp -std=c++17 cpp-advanced C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Pair in C++ Standard Template Library (STL) Inline Functions in C++ Queue in C++ Standard Template Library (STL) Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++
[ { "code": null, "e": 25367, "s": 25339, "text": "\n27 Jan, 2018" }, { "code": null, "e": 25539, "s": 25367, "text": "In many cases, we need to check the value of something returned by a function and perform conditional operations based on this value. So our code looks something l...
Python - math.asin() function - GeeksforGeeks
28 May, 2020 Math module contains a number of functions which is used for mathematical operations. The math.asin() function returns the arc sine value of a number. The value passed in this function should be between -1 to 1. Syntax: math.asin(x) Parameter:This method accepts only single parameters. x :This parameter is the value to be passed to asin() Returns:This function returns the arc sine value of a number. Below examples illustrate the use of above function: Example 1: # Python code to implement# the acos()function # importing "math"# for mathematical operations import math a = math.pi / 6 # returning the value of arc sine of pi / 6 print ("The value of arc sine of pi / 6 is : ", end ="") print (math.asin(a)) Output: The value of arc sine of pi / 6 is : 0.5510695830994463 Example 2: # Python code to implement# the aasin()functionimport math import matplotlib.pyplot as plt in_array = [-0.14159265, -0.57039399, -0.28559933, 0.28559933, 0.57039399, 0.94159265] out_array = [] for i in range(len(in_array)): out_array.append(math.asin(in_array[i])) i += 1 print("Input_Array : \n", in_array) print("\nOutput_Array : \n", out_array) plt.plot(in_array, out_array, "go:") plt.title("math.asin()") plt.xlabel("X") plt.ylabel("Y") plt.show() Output: Input_Array : [-0.14159265, -0.57039399, -0.28559933, 0.28559933, 0.57039399, 0.94159265] Output_Array : [-0.14207008957392517, -0.6069854488522558, -0.2896317474780172, 0.2896317474780172, 0.6069854488522558, 1.227328875116741] Python math-library Python math-library-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25441, "s": 25413, "text": "\n28 May, 2020" }, { "code": null, "e": 25653, "s": 25441, "text": "Math module contains a number of functions which is used for mathematical operations. The math.asin() function returns the arc sine value of a number. The value pa...
Flatten a Stream of Lists in Java using forEach loop - GeeksforGeeks
11 Dec, 2018 Given a Stream of Lists in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: lists = [ [1, 2], [3, 4, 5, 6], [8, 9] ] Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: lists = [ ['G', 'e', 'e', 'k', 's'], ['F', 'o', 'r'] ] Output: [G, e, e, k, s, F, o, r] Approach: Get the Lists in the form of 2D list.Create an empty list to collect the flattened elements.With the help of forEach loop, convert each elements of the list into stream and add it to the listNow convert this list into stream using stream() method.Now flatten the stream by converting it into list using collect() method. Get the Lists in the form of 2D list. Create an empty list to collect the flattened elements. With the help of forEach loop, convert each elements of the list into stream and add it to the list Now convert this list into stream using stream() method. Now flatten the stream by converting it into list using collect() method. Below is the implementation of the above approach: Example 1: Using lists of integer. // Java program to flatten a stream of lists// using forEach() method import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.*; class GFG { // Function to flatten a Stream of Lists public static <T> Stream<T> flattenStream(List<List<T> > lists) { // Create an empty list to collect the stream List<T> finalList = new ArrayList<>(); // Using forEach loop // convert the list into stream // and add the stream into list for (List<T> list : lists) { list.stream() .forEach(finalList::add); } // Convert the list into Stream and return it return finalList.stream(); } public static void main(String[] args) { // Get the lists to be flattened. List<Integer> a = Arrays.asList(1, 2); List<Integer> b = Arrays.asList(3, 4, 5, 6); List<Integer> c = Arrays.asList(7, 8, 9); List<List<Integer> > arr = new ArrayList<List<Integer> >(); arr.add(a); arr.add(b); arr.add(c); // Flatten the Stream List<Integer> flatList = new ArrayList<Integer>(); flatList = flattenStream(arr) .collect(Collectors.toList()); // Print the flattened list System.out.println(flatList); }} [1, 2, 3, 4, 5, 6, 7, 8, 9] Example 2: Using lists of Characters. // Java program to flatten a stream of lists// using forEach() method import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.*; class GFG { // Function to flatten a Stream of Lists public static <T> Stream<T> flattenStream(List<List<T> > lists) { // Create an empty list to collect the stream List<T> finalList = new ArrayList<>(); // Using forEach loop // convert the list into stream // and add the stream into list for (List<T> list : lists) { list.stream() .forEach(finalList::add); } // Convert the list into Stream and return it return finalList.stream(); } public static void main(String[] args) { // Get the lists to be flattened. List<Character> a = Arrays.asList('G', 'e', 'e', 'k', 's'); List<Character> b = Arrays.asList('F', 'o', 'r'); List<Character> c = Arrays.asList('G', 'e', 'e', 'k', 's'); List<List<Character> > arr = new ArrayList<List<Character> >(); arr.add(a); arr.add(b); arr.add(c); // Flatten the Stream List<Character> flatList = new ArrayList<Character>(); flatList = flattenStream(arr) .collect(Collectors.toList()); // Print the flattened list System.out.println(flatList); }} [G, e, e, k, s, F, o, r, G, e, e, k, s] Java - util package java-list Java-List-Programs java-stream Java-Stream-programs Java Java Programs 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 Interfaces in Java Stream In Java How to iterate any Map in Java Initializing a List in Java Convert a String to Character Array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 25441, "s": 25413, "text": "\n11 Dec, 2018" }, { "code": null, "e": 25532, "s": 25441, "text": "Given a Stream of Lists in Java, the task is to Flatten the Stream using forEach() method." }, { "code": null, "e": 25542, "s": 25532, "text": ...
Hello World in Golang - GeeksforGeeks
16 Nov, 2021 Hello, World! is the first basic program in any programming language. Let’s write the first program in the Go Language using the following steps: First of all open Go compiler. In Go language, the program is saved with .go extension and it is a UTF-8 text file. Now, first add the package main in your program:package mainEvery program must start with the package declaration. In Go language, packages are used to organize and reuse the code. In Go, there are two types of program available one is executable and another one is the library. The executable programs are those programs that we can run directly from the terminal and Libraries are the package of programs that we can reuse them in our program. Here, the package main tells the compiler that the package must compile in the executable program rather than a shared library. It is the starting point of the program and also contains the main function in it. package main Every program must start with the package declaration. In Go language, packages are used to organize and reuse the code. In Go, there are two types of program available one is executable and another one is the library. The executable programs are those programs that we can run directly from the terminal and Libraries are the package of programs that we can reuse them in our program. Here, the package main tells the compiler that the package must compile in the executable program rather than a shared library. It is the starting point of the program and also contains the main function in it. After adding main package import “fmt” package in your program:import( "fmt" ) Here, import keyword is used to import packages in your program and fmt package is used to implement formatted Input/Output with functions. import( "fmt" ) Here, import keyword is used to import packages in your program and fmt package is used to implement formatted Input/Output with functions. Now write the code in the main function to print hello world in Go language:func main() { fmt.Println("!... Hello World ...!") } In the above lines of code we have:func: It is used to create a function in Go language.main: It is the main function in Go language, which doesn’t contain the parameter, doesn’t return anything, and call when you execute your program.Println(): This method is present in fmt package and it is used to display “!... Hello World ...!” string. Here, Println means Print line. func main() { fmt.Println("!... Hello World ...!") } In the above lines of code we have: func: It is used to create a function in Go language. main: It is the main function in Go language, which doesn’t contain the parameter, doesn’t return anything, and call when you execute your program. Println(): This method is present in fmt package and it is used to display “!... Hello World ...!” string. Here, Println means Print line. Example: // First Go programpackage main import "fmt" // Main functionfunc main() { fmt.Println("!... Hello World ...!")} Output: !... Hello World ...! To run a Go program you need a Go compiler. In Go compiler, first you create a program and save your program with extension .go, for example, first.go. Now we run this first.go file in the go compiler using the following command, i.e: $ go run first.go Go-Basics Golang Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to concatenate two strings in Golang 6 Best Books to Learn Go Programming Language time.Sleep() Function in Golang With Examples strings.Contains Function in Golang with Examples Time Formatting in Golang strings.Replace() Function in Golang With Examples fmt.Sprintf() Function in Golang With Examples Golang Maps Different Ways to Find the Type of Variable in Golang Inheritance in GoLang
[ { "code": null, "e": 26176, "s": 26148, "text": "\n16 Nov, 2021" }, { "code": null, "e": 26322, "s": 26176, "text": "Hello, World! is the first basic program in any programming language. Let’s write the first program in the Go Language using the following steps:" }, { "co...
Python | Sort the list alphabetically in a dictionary - GeeksforGeeks
28 Jan, 2019 In Python Dictionary is quite a useful data structure, which is usually used to hash a particular key with value, so that they can be retrieved efficiently. Let’s see how to sort the list alphabetically in a dictionary. Example #1: # Python program to sort the list # alphabetically in a dictionarydict ={ "L1":[87, 34, 56, 12], "L2":[23, 00, 30, 10], "L3":[1, 6, 2, 9], "L4":[40, 34, 21, 67]} print("\nBefore Sorting: ")for x in dict.items(): print(x) print("\nAfter Sorting: ") for i, j in dict.items(): sorted_dict ={i:sorted(j)} print(sorted_dict) Before Sorting: ('L2', [23, 0, 30, 10]) ('L3', [1, 6, 2, 9]) ('L4', [40, 34, 21, 67]) ('L1', [87, 34, 56, 12]) After Sorting: {'L2': [0, 10, 23, 30]} {'L3': [1, 2, 6, 9]} {'L4': [21, 34, 40, 67]} {'L1': [12, 34, 56, 87]} Example #2: # Python program to sort the list # alphabetically in a dictionary dict ={ "L1":["Geeks", "for", "Geeks"], "L2":["A", "computer", "science"], "L3":["portal", "for", "geeks"],} print("\nBefore Sorting: ")for x in dict.items(): print(x) print("\nAfter Sorting: ")for i, j in dict.items(): sorted_dict ={i:sorted(j)} print(sorted_dict) Before Sorting: ('L3', ['portal', 'for', 'geeks']) ('L1', ['Geeks', 'for', 'Geeks']) ('L2', ['A', 'computer', 'science']) After Sorting: {'L3': ['for', 'geeks', 'portal']} {'L1': ['Geeks', 'Geeks', 'for']} {'L2': ['A', 'computer', 'science']} Example #3: # Python program to sort the list # alphabetically in a dictionarydict={ "L1":[87,34,56,12], "L2":[23,00,30,10], "L3":[1,6,2,9], "L4":[40,34,21,67]} print("\nBefore Sorting: ")for x in dict.items(): print(x) sorted_dict = {i: sorted(j) for i, j in dict.items()}print("\nAfter Sorting: ", sorted_dict) Before Sorting: ('L1', [87, 34, 56, 12]) ('L2', [23, 0, 30, 10]) ('L3', [1, 6, 2, 9]) ('L4', [40, 34, 21, 67]) After Sorting: {'L1': [12, 34, 56, 87], 'L2': [0, 10, 23, 30], 'L3': [1, 2, 6, 9], 'L4': [21, 34, 40, 67]} Picked Python dictionary-programs python-dict Python python-dict Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26197, "s": 26169, "text": "\n28 Jan, 2019" }, { "code": null, "e": 26354, "s": 26197, "text": "In Python Dictionary is quite a useful data structure, which is usually used to hash a particular key with value, so that they can be retrieved efficiently." }, ...
Binary Search on Singly Linked List - GeeksforGeeks
21 Jun, 2021 Given a singly linked list and a key, find key using binary search approach. To perform a Binary search based on Divide and Conquer Algorithm, determination of the middle element is important. Binary Search is usually fast and efficient for arrays because accessing the middle index between two given indices is easy and fast(Time Complexity O(1)). But memory allocation for the singly linked list is dynamic and non-contiguous, which makes finding the middle element difficult. One approach could be of using skip list, one could be traversing the linked list using one pointer.Prerequisite: Finding middle of a linked list.Note: The approach and implementation provided below are to show how Binary Search can be implemented on a linked list. The implementation takes O(n) time. Approach : Here, start node(set to Head of list), and the last node(set to NULL initially) are given. Middle is calculated using two pointers approach. If middle’s data matches the required value of search, return it. Else if middle’s data < value, move to upper half(setting start to middle’s next). Else go to lower half(setting last to middle). The condition to come out is, either element found or entire list is traversed. When entire list is traversed, last points to start i.e. last -> next == start. In main function, function InsertAtHead inserts value at the beginning of linked list. Inserting such values(for sake of simplicity) so that the list created is sorted. Examples : Input : Enter value to search : 7 Output : Found Input : Enter value to search : 12 Output : Not Found C++ Java Python C# Javascript // CPP code to implement binary search// on Singly Linked List#include<stdio.h>#include<stdlib.h> struct Node{ int data; struct Node* next;}; Node *newNode(int x){ struct Node* temp = new Node; temp->data = x; temp->next = NULL; return temp;} // function to find out middle elementstruct Node* middle(Node* start, Node* last){ if (start == NULL) return NULL; struct Node* slow = start; struct Node* fast = start -> next; while (fast != last) { fast = fast -> next; if (fast != last) { slow = slow -> next; fast = fast -> next; } } return slow;} // Function for implementing the Binary// Search on linked liststruct Node* binarySearch(Node *head, int value){ struct Node* start = head; struct Node* last = NULL; do { // Find middle Node* mid = middle(start, last); // If middle is empty if (mid == NULL) return NULL; // If value is present at middle if (mid -> data == value) return mid; // If value is more than mid else if (mid -> data < value) start = mid -> next; // If the value is less than mid. else last = mid; } while (last == NULL || last != start); // value not present return NULL;} // Driver Codeint main(){ Node *head = newNode(1); head->next = newNode(4); head->next->next = newNode(7); head->next->next->next = newNode(8); head->next->next->next->next = newNode(9); head->next->next->next->next->next = newNode(10); int value = 7; if (binarySearch(head, value) == NULL) printf("Value not present\n"); else printf("Present"); return 0;} // Java code to implement binary search// on Singly Linked List // Node Classclass Node{ int data; Node next; // Constructor to create a new node Node(int d) { data = d; next = null; }} class BinarySearch{ // function to insert a node at the beginning // of the Singaly Linked List static Node push(Node head, int data) { Node newNode = new Node(data); newNode.next = head; head = newNode; return head; } // Function to find middle element // using Fast and Slow pointers static Node middleNode(Node start, Node last) { if (start == null) return null; Node slow = start; Node fast = start.next; while (fast != last) { fast = fast.next; if (fast != last) { slow = slow.next; fast = fast.next; } } return slow; } // function to insert a node at the beginning // of the Singly Linked List static Node binarySearch(Node head, int value) { Node start = head; Node last = null; do { // Find Middle Node mid = middleNode(start, last); // If middle is empty if (mid == null) return null; // If value is present at middle if (mid.data == value) return mid; // If value is less than mid else if (mid.data > value) { start = mid.next; } // If the value is more than mid. else last = mid; } while (last == null || last != start); // value not present return null; } // Driver Code public static void main(String[] args) { Node head = null; // Using push() function to // convert singly linked list // 10 -> 9 -> 8 -> 7 -> 4 -> 1 head = push(head, 1); head = push(head, 4); head = push(head, 7); head = push(head, 8); head = push(head, 9); head = push(head, 10); int value = 7; if (binarySearch(head, value) == null) { System.out.println("Value not present"); } else { System.out.println("Present"); } }} // This code is contributed by Vivekkumar Singh # Python code to implement binary search# on Singly Linked List # Link list nodeclass Node: def __init__(self, data): self.data = data self.next = None self.prev = None def newNode(x): temp = Node(0) temp.data = x temp.next = None return temp # function to find out middle elementdef middle(start, last): if (start == None): return None slow = start fast = start . next while (fast != last): fast = fast . next if (fast != last): slow = slow . next fast = fast . next return slow # Function for implementing the Binary# Search on linked listdef binarySearch(head,value): start = head last = None while True : # Find middle mid = middle(start, last) # If middle is empty if (mid == None): return None # If value is present at middle if (mid . data == value): return mid # If value is more than mid elif (mid . data < value): start = mid . next # If the value is less than mid. else: last = mid if not (last == None or last != start): break # value not present return None # Driver Code head = newNode(1)head.next = newNode(4)head.next.next = newNode(7)head.next.next.next = newNode(8)head.next.next.next.next = newNode(9)head.next.next.next.next.next = newNode(10)value = 7if (binarySearch(head, value) == None): print("Value not present\n")else: print("Present") # This code is contributed by Arnab Kundu // C# code to implement binary search// on Singly Linked List using System; // Node Classpublic class Node{ public int data; public Node next; // Constructor to create a new node public Node(int d) { data = d; next = null; }} class BinarySearch{ // function to insert a node at the beginning // of the Singaly Linked List static Node push(Node head, int data) { Node newNode = new Node(data); newNode.next = head; head = newNode; return head; } // Function to find middle element // using Fast and Slow pointers static Node middleNode(Node start, Node last) { if (start == null) return null; Node slow = start; Node fast = start.next; while (fast != last) { fast = fast.next; if (fast != last) { slow = slow.next; fast = fast.next; } } return slow; } // function to insert a node at the beginning // of the Singly Linked List static Node binarySearch(Node head, int value) { Node start = head; Node last = null; do { // Find Middle Node mid = middleNode(start, last); // If middle is empty if (mid == null) return null; // If value is present at middle if (mid.data == value) return mid; // If value is less than mid else if (mid.data > value) { start = mid.next; } // If the value is more than mid. else last = mid; } while (last == null || last != start); // value not present return null; } // Driver Code public static void Main(String []args) { Node head = null; // Using push() function to // convert singly linked list // 10 -> 9 -> 8 -> 7 -> 4 -> 1 head = push(head, 1); head = push(head, 4); head = push(head, 7); head = push(head, 8); head = push(head, 9); head = push(head, 10); int value = 7; if (binarySearch(head, value) == null) { Console.WriteLine("Value not present"); } else { Console.WriteLine("Present"); } }} // This code is contributed by Arnab Kundu <script> // JavaScript code to implement binary search// on Singly Linked List // Node Classclass Node{ constructor(data) { this.data = data; this.next = null; }} // function to insert a node at the beginning// of the Singaly Linked Listfunction push(head, data){ var newNode = new Node(data); newNode.next = head; head = newNode; return head;} // Function to find middle element// using Fast and Slow pointersfunction middleNode(start, last){ if (start == null) return null; var slow = start; var fast = start.next; while (fast != last) { fast = fast.next; if (fast != last) { slow = slow.next; fast = fast.next; } } return slow;}// function to insert a node at the beginning// of the Singly Linked Listfunction binarySearch(head, value){ var start = head; var last = null; do { // Find Middle var mid = middleNode(start, last); // If middle is empty if (mid == null) return null; // If value is present at middle if (mid.data == value) return mid; // If value is less than mid else if (mid.data > value) { start = mid.next; } // If the value is more than mid. else last = mid; } while (last == null || last != start); // value not present return null;} // Driver Codevar head = null;// Using push() function to// convert singly linked list// 10 -> 9 -> 8 -> 7 -> 4 -> 1head = push(head, 1);head = push(head, 4);head = push(head, 7);head = push(head, 8);head = push(head, 9);head = push(head, 10);var value = 7;if (binarySearch(head, value) == null){ document.write("Value not present");}else{ document.write("Present");} </script> Present Time Complexity: O(N) Auxiliary Space: O(1) sunny94 Arun Prakash 1 HusenDevani Vivekkumar Singh andrew1234 rrrtnx Binary Search Divide and Conquer Linked List Searching Linked List Searching Divide and Conquer Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for Tower of Hanoi Divide and Conquer Algorithm | Introduction Median of two sorted arrays of different sizes Write a program to calculate pow(x,n) Count number of occurrences (or frequency) in a sorted array Reverse a linked list Stack Data Structure (Introduction and Program) LinkedList in Java Linked List vs Array Doubly Linked List | Set 1 (Introduction and Insertion)
[ { "code": null, "e": 25983, "s": 25955, "text": "\n21 Jun, 2021" }, { "code": null, "e": 26777, "s": 25983, "text": "Given a singly linked list and a key, find key using binary search approach. To perform a Binary search based on Divide and Conquer Algorithm, determination of the...
C Program for Red Black Tree Insertion - GeeksforGeeks
16 Sep, 2021 Following article is extension of article discussed here.In AVL tree insertion, we used rotation as a tool to do balancing after insertion caused imbalance. In Red-Black tree, we use two tools to do balancing.1) Recoloring 2) Rotation We try recoloring first, if recoloring doesn’t work, then we go for rotation. Following is detailed algorithm. The algorithms has mainly two cases depending upon the color of uncle. If uncle is red, we do recoloring. If uncle is black, we do rotations and/or recoloring.Color of a NULL node is considered as BLACK. Let x be the newly inserted node. 1. Perform standard BST insertion and make the color of newly inserted nodes as RED.2. If x is root, change color of x as BLACK (Black height of complete tree increases by 1).3. Do following if color of x’s parent is not BLACK or x is not root. 1. If x’s uncle is RED (Grand parent must have been black from property 4) 1. Change color of parent and uncle as BLACK. 2. color of grand parent as RED. 3. Change x = x’s grandparent, repeat steps 2 and 3 for new x. 2. If x’s uncle is BLACK, then there can be four configurations for x, x’s parent (p) and x’s grandparent (g) (This is similar to AVL Tree) 1. Determine the configuration: 1. Left Left Case (p is left child of g and x is left child of p). 2.Left Right Case (p is left child of g and x is right child of p). 3. Right Right Case (Mirror of case a). 4.Right Left Case (Mirror of case c). 2. Change x = x’s parent, repeat steps 2 and 3 for new x. Following are operations to be performed in four subcases when uncle is BLACK. Left Left Case (See g, p and x) Left Right Case (See g, p and x) Right Right Case (See g, p and x) Right Left Case (See g, p and x) Examples of Insertion Below is C++ Code. C++ C /** C++ implementation for Red-Black Tree Insertion This code is adopted from the code provided by Dinesh Khandelwal in comments **/#include <bits/stdc++.h>using namespace std; enum Color {RED, BLACK}; struct Node{ int data; bool color; Node *left, *right, *parent; // Constructor Node(int data) { this->data = data; left = right = parent = NULL; this->color = RED; }}; // Class to represent Red-Black Treeclass RBTree{private: Node *root;protected: void rotateLeft(Node *&, Node *&); void rotateRight(Node *&, Node *&); void fixViolation(Node *&, Node *&);public: // Constructor RBTree() { root = NULL; } void insert(const int &n); void inorder(); void levelOrder();}; // A recursive function to do inorder traversalvoid inorderHelper(Node *root){ if (root == NULL) return; inorderHelper(root->left); cout << root->data << " "; inorderHelper(root->right);} /* A utility function to insert a new node with given key in BST */Node* BSTInsert(Node* root, Node *pt){ /* If the tree is empty, return a new node */ if (root == NULL) return pt; /* Otherwise, recur down the tree */ if (pt->data < root->data) { root->left = BSTInsert(root->left, pt); root->left->parent = root; } else if (pt->data > root->data) { root->right = BSTInsert(root->right, pt); root->right->parent = root; } /* return the (unchanged) node pointer */ return root;} // Utility function to do level order traversalvoid levelOrderHelper(Node *root){ if (root == NULL) return; std::queue<Node *> q; q.push(root); while (!q.empty()) { Node *temp = q.front(); cout << temp->data << " "; q.pop(); if (temp->left != NULL) q.push(temp->left); if (temp->right != NULL) q.push(temp->right); }} void RBTree::rotateLeft(Node *&root, Node *&pt){ Node *pt_right = pt->right; pt->right = pt_right->left; if (pt->right != NULL) pt->right->parent = pt; pt_right->parent = pt->parent; if (pt->parent == NULL) root = pt_right; else if (pt == pt->parent->left) pt->parent->left = pt_right; else pt->parent->right = pt_right; pt_right->left = pt; pt->parent = pt_right;} void RBTree::rotateRight(Node *&root, Node *&pt){ Node *pt_left = pt->left; pt->left = pt_left->right; if (pt->left != NULL) pt->left->parent = pt; pt_left->parent = pt->parent; if (pt->parent == NULL) root = pt_left; else if (pt == pt->parent->left) pt->parent->left = pt_left; else pt->parent->right = pt_left; pt_left->right = pt; pt->parent = pt_left;} // This function fixes violations// caused by BST insertionvoid RBTree::fixViolation(Node *&root, Node *&pt){ Node *parent_pt = NULL; Node *grand_parent_pt = NULL; while ((pt != root) && (pt->color != BLACK) && (pt->parent->color == RED)) { parent_pt = pt->parent; grand_parent_pt = pt->parent->parent; /* Case : A Parent of pt is left child of Grand-parent of pt */ if (parent_pt == grand_parent_pt->left) { Node *uncle_pt = grand_parent_pt->right; /* Case : 1 The uncle of pt is also red Only Recoloring required */ if (uncle_pt != NULL && uncle_pt->color == RED) { grand_parent_pt->color = RED; parent_pt->color = BLACK; uncle_pt->color = BLACK; pt = grand_parent_pt; } else { /* Case : 2 pt is right child of its parent Left-rotation required */ if (pt == parent_pt->right) { rotateLeft(root, parent_pt); pt = parent_pt; parent_pt = pt->parent; } /* Case : 3 pt is left child of its parent Right-rotation required */ rotateRight(root, grand_parent_pt); swap(parent_pt->color, grand_parent_pt->color); pt = parent_pt; } } /* Case : B Parent of pt is right child of Grand-parent of pt */ else { Node *uncle_pt = grand_parent_pt->left; /* Case : 1 The uncle of pt is also red Only Recoloring required */ if ((uncle_pt != NULL) && (uncle_pt->color == RED)) { grand_parent_pt->color = RED; parent_pt->color = BLACK; uncle_pt->color = BLACK; pt = grand_parent_pt; } else { /* Case : 2 pt is left child of its parent Right-rotation required */ if (pt == parent_pt->left) { rotateRight(root, parent_pt); pt = parent_pt; parent_pt = pt->parent; } /* Case : 3 pt is right child of its parent Left-rotation required */ rotateLeft(root, grand_parent_pt); swap(parent_pt->color, grand_parent_pt->color); pt = parent_pt; } } } root->color = BLACK;} // Function to insert a new node with given datavoid RBTree::insert(const int &data){ Node *pt = new Node(data); // Do a normal BST insert root = BSTInsert(root, pt); // fix Red Black Tree violations fixViolation(root, pt);} // Function to do inorder and level order traversalsvoid RBTree::inorder() { inorderHelper(root);}void RBTree::levelOrder() { levelOrderHelper(root); } // Driver Codeint main(){ RBTree tree; tree.insert(7); tree.insert(6); tree.insert(5); tree.insert(4); tree.insert(3); tree.insert(2); tree.insert(1); cout << "Inorder Traversal of Created Tree\n"; tree.inorder(); cout << "\n\nLevel Order Traversal of Created Tree\n"; tree.levelOrder(); return 0;} /** C implementation for Red-Black Tree Insertion This code is provided by costheta_z **/#include <stdio.h>#include <stdlib.h> // Structure to represent each// node in a red-black treestruct node { int d; // data int c; // 1-red, 0-black struct node* p; // parent struct node* r; // right-child struct node* l; // left child}; // global root for the entire treestruct node* root = NULL; // function to perform BST insertion of a nodestruct node* bst(struct node* trav, struct node* temp){ // If the tree is empty, // return a new node if (trav == NULL) return temp; // Otherwise recur down the tree if (temp->d < trav->d) { trav->l = bst(trav->l, temp); trav->l->p = trav; } else if (temp->d > trav->d) { trav->r = bst(trav->r, temp); trav->r->p = trav; } // Return the (unchanged) node pointer return trav;} // Function performing right rotation// of the passed nodevoid rightrotate(struct node* temp){ struct node* left = temp->l; temp->l = left->r; if (temp->l) temp->l->p = temp; left->p = temp->p; if (!temp->p) root = left; else if (temp == temp->p->l) temp->p->l = left; else temp->p->r = left; left->r = temp; temp->p = left;} // Function performing left rotation// of the passed nodevoid leftrotate(struct node* temp){ struct node* right = temp->r; temp->r = right->l; if (temp->r) temp->r->p = temp; right->p = temp->p; if (!temp->p) root = right; else if (temp == temp->p->l) temp->p->l = right; else temp->p->r = right; right->l = temp; temp->p = right;} // This function fixes violations// caused by BST insertionvoid fixup(struct node* root, struct node* pt){ struct node* parent_pt = NULL; struct node* grand_parent_pt = NULL; while ((pt != root) && (pt->c != 0) && (pt->p->c == 1)) { parent_pt = pt->p; grand_parent_pt = pt->p->p; /* Case : A Parent of pt is left child of Grand-parent of pt */ if (parent_pt == grand_parent_pt->l) { struct node* uncle_pt = grand_parent_pt->r; /* Case : 1 The uncle of pt is also red Only Recoloring required */ if (uncle_pt != NULL && uncle_pt->c == 1) { grand_parent_pt->c = 1; parent_pt->c = 0; uncle_pt->c = 0; pt = grand_parent_pt; } else { /* Case : 2 pt is right child of its parent Left-rotation required */ if (pt == parent_pt->r) { leftrotate(parent_pt); pt = parent_pt; parent_pt = pt->p; } /* Case : 3 pt is left child of its parent Right-rotation required */ rightrotate(grand_parent_pt); int t = parent_pt->c; parent_pt->c = grand_parent_pt->c; grand_parent_pt->c = t; pt = parent_pt; } } /* Case : B Parent of pt is right child of Grand-parent of pt */ else { struct node* uncle_pt = grand_parent_pt->l; /* Case : 1 The uncle of pt is also red Only Recoloring required */ if ((uncle_pt != NULL) && (uncle_pt->c == 1)) { grand_parent_pt->c = 1; parent_pt->c = 0; uncle_pt->c = 0; pt = grand_parent_pt; } else { /* Case : 2 pt is left child of its parent Right-rotation required */ if (pt == parent_pt->l) { rightrotate(parent_pt); pt = parent_pt; parent_pt = pt->p; } /* Case : 3 pt is right child of its parent Left-rotation required */ leftrotate(grand_parent_pt); int t = parent_pt->c; parent_pt->c = grand_parent_pt->c; grand_parent_pt->c = t; pt = parent_pt; } } } root->c = 0;} // Function to print inorder traversal// of the fixated treevoid inorder(struct node* trav){ if (trav == NULL) return; inorder(trav->l); printf("%d ", trav->d); inorder(trav->r);} // driver codeint main(){ int n = 7; int a[7] = { 7, 6, 5, 4, 3, 2, 1 }; for (int i = 0; i < n; i++) { // allocating memory to the node and initializing: // 1. color as red // 2. parent, left and right pointers as NULL // 3. data as i-th value in the array struct node* temp = (struct node*)malloc(sizeof(struct node)); temp->r = NULL; temp->l = NULL; temp->p = NULL; temp->d = a[i]; temp->c = 1; // calling function that performs bst insertion of // this newly created node root = bst(root, temp); // calling function to preserve properties of rb // tree fixup(root, temp); } printf("Inorder Traversal of Created Tree\n"); inorder(root); return 0;} Output: Inorder Traversal of Created Tree 1 2 3 4 5 6 7 Level Order Traversal of Created Tree 6 4 7 2 5 1 3 YouTubeGeeksforGeeks507K subscribersRed Black Tree (Insertion) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:26•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=YCo2-H2CL6Q" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Mohsin Mohammaad. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Shlomi Elhaiani costheta_z saurabh1990aror Red Black Tree Self-Balancing-BST Binary Search Tree Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorted Array to Balanced BST Optimal Binary Search Tree | DP-24 Inorder Successor in Binary Search Tree Find the node with minimum value in a Binary Search Tree Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Difference between Binary Tree and Binary Search Tree Lowest Common Ancestor in a Binary Search Tree. Binary Tree to Binary Search Tree Conversion Find k-th smallest element in BST (Order Statistics in BST) Convert a normal BST to Balanced BST
[ { "code": null, "e": 25983, "s": 25955, "text": "\n16 Sep, 2021" }, { "code": null, "e": 26218, "s": 25983, "text": "Following article is extension of article discussed here.In AVL tree insertion, we used rotation as a tool to do balancing after insertion caused imbalance. In Red...
GATE | GATE-CS-2015 (Set 3) | Question 65 - GeeksforGeeks
28 Jun, 2021 Let # be a binary operator defined as X # Y = X′ + Y′ where X and Y are Boolean variables. Consider the following two statements. S1: (P # Q) # R = P # (Q # R) S2: Q # R = R # Q Which of the following is/are true for the Boolean variables P, Q and R? (A) Only S1 is True(B) Only S2 is True(C) Both S1 and S2 are True(D) Neither S1 nor S2 are TrueAnswer: (B)Explanation: S2 is true, as X' + Y' = Y' + X' S1 is false. Let P = 1, Q = 1, R = 0, we get different results (P # Q) # R = (P' + Q')' + R' = (0 + 0)' + 1 = 1 + 1 = 1 P # (Q # R) = P' + (Q' + R')' = 0 + (0 + 1)' = 0 + 0 = 0 Quiz of this Question My Personal Notes arrow_drop_up Save S1 is false. Let P = 1, Q = 1, R = 0, we get different results (P # Q) # R = (P' + Q')' + R' = (0 + 0)' + 1 = 1 + 1 = 1 P # (Q # R) = P' + (Q' + R')' = 0 + (0 + 1)' = 0 + 0 = 0 Quiz of this Question GATE-CS-2015 (Set 3) GATE-GATE-CS-2015 (Set 3) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE MOCK 2017 | Question 24 GATE | GATE-CS-2006 | Question 47 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25657, "s": 25629, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25787, "s": 25657, "text": "Let # be a binary operator defined as X # Y = X′ + Y′ where X and Y are Boolean variables. Consider the following two statements." }, { "code": null, "...
How to redirect back to original URL in Node.js ? - GeeksforGeeks
14 Jan, 2022 Node.js with the help of Express, supports web page routing. This means that when the client makes different requests, the application is routed to different web pages depending upon the request made and the routing methods defined. To learn more about Node.js routing and the implementation, refer this article. In this article, we will discuss how to redirect back to original URL in Node.js. The res.redirect() is a URL utility function which helps to redirect the web pages according to the specified paths. Syntax: return res.redirect([status], path) For the first example we will redirect the user to a specified URL with a different domain. Make sure to install express in your project before running the code. Javascript const express= require('express'); var app= express(); app.get('/',function(req,res){ // On getting the home route request, // the user will be redirected to GFG website res.redirect('https://www.geeksforgeeks.org');}); app.listen(3000,function(req,res){ console.log("Server is running at port 3000");}); When the above code is executed using node, we will be redirected to the GeeksforGeeks website when we make request for home route on port 3000. Output: Other methods: Other than redirecting to a different domain, we have some other methods available to redirect as following. Domain relative redirect: We can use this method to redirect to a different page under the same domain. For example, if the user is at http://example.com/gfg/post1 , then we can redirect to http://example.com/article by using the following line of code res.redirect('/article'); Pathname relative redirect: We can use this method to redirect to the previous path on the website. For example, if the user is at http://example.com/gfg/post1, then we can redirect to http://example.com/gfg by using the following line of code res.redirect('..'); Redirecting back to original URL: After learning about res.redirect() function, we can now discuss how to redirect back to original URL in NodeJS. Back redirect: We can use this method to redirects the request back to the referrer. If no referrer is present, the request is redirected to “/” route by default. res.redirect('back'); Example: Let’s suppose we are at ‘/example’ route. On requesting the ‘/redex’ route, we will be automatically redirected to ‘/’ route as defined in the code below Javascript const express= require('express'); var app= express(); //Defining '/' routeapp.get('/',function(req,res){ res.redirect('https://www.geeksforgeeks.org');}); //Defining '/example' routeapp.get('/example',function(req,res){ res.redirect('https://www.geeksforgeeks.org/array-data-structure/');}); //Defining '/redex' routeapp.get('/redex',function(req,res){ res.redirect('back');}) app.listen(3000,function(req,res){ console.log("Server is running at port 3000");}); Output: Reference:https://expressjs.com/en/5x/api.html#res.redirect adnanirshad158 NodeJS-Questions Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between dependencies, devDependencies and peerDependencies Node.js Export Module How to connect Node.js with React.js ? Mongoose find() Function Mongoose Populate() Method 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": 26267, "s": 26239, "text": "\n14 Jan, 2022" }, { "code": null, "e": 26580, "s": 26267, "text": "Node.js with the help of Express, supports web page routing. This means that when the client makes different requests, the application is routed to different web p...
C# | How to check whether a List contains the elements that match the specified conditions - GeeksforGeeks
01 Feb, 2019 List<T>.Exists(Predicate<T>) Method is used to check whether the List<T> contains elements which match the conditions defined by the specified predicate. Properties of List: It is different from the arrays. A list can be resized dynamically but arrays cannot. List class can accept null as a valid value for reference types and it also allows duplicate elements. If the Count becomes equals to Capacity then the capacity of the List increases automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element. Syntax: public bool Exists (Predicate<T> match); Parameter: match: It is the Predicate<T> delegate which defines the conditions of the elements to search for. Return Value: This method returns True if the List<T> contains one or more elements that match the conditions defined by the specified predicate otherwise it returns False. Exception: This method will give ArgumentNullException if the match is null. Below programs illustrate the use List<T>.Exists(Predicate<T>) Method: Example 1: // C# Program to check whether a List contains// the elements that match the specified conditions// defined by the predicateusing System;using System.Collections;using System.Collections.Generic; class Geeks { // function which checks whether an // element is even or not. Or you can // say it is the specified condition private static bool isEven(int i) { return ((i % 2) == 0); } // Main Method public static void Main(String[] args) { // Creating an List<T> of Integers List<int> firstlist = new List<int>(); // Adding elements to List for (int i = 1; i <= 10; i++) { firstlist.Add(i); } Console.WriteLine("Elements Present in List:\n"); // Displaying the elements of List foreach(int k in firstlist) { Console.WriteLine(k); } Console.WriteLine(" "); Console.Write("Result: "); // Check the elements of firstlist that // match the conditions defined by predicate Console.WriteLine(firstlist.Exists(isEven)); }} Output: Elements Present in List: 1 2 3 4 5 6 7 8 9 10 Result: True Example 2: // C# Program to check whether a List contains// the elements that match the specified conditions// defined by the predicateusing System;using System.Collections;using System.Collections.Generic; class Geeks { // function which checks whether an // element is even or not. Or you can // say it is the specified condition private static bool isEven(int i) { return ((i % 2) == 0); } // Main Method public static void Main(String[] args) { // Creating an List<T> of Integers List<int> firstlist = new List<int>(); // Adding elements to List firstlist.Add(5); firstlist.Add(7); firstlist.Add(9); firstlist.Add(11); firstlist.Add(3); firstlist.Add(17); firstlist.Add(19); Console.WriteLine("Elements Present in List:\n"); // Displaying the elements of List foreach(int k in firstlist) { Console.WriteLine(k); } Console.WriteLine(" "); Console.Write("Result: "); // Check the elements of firstlist that // match the conditions defined by predicate Console.WriteLine(firstlist.Exists(isEven)); }} Output: Elements Present in List: 5 7 9 11 3 17 19 Result: False Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.exists?view=netframework-4.7.2 CSharp-Collections-Namespace CSharp-Generic-List CSharp-Generic-Namespace CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# | Delegates Top 50 C# Interview Questions & Answers Introduction to .NET Framework C# | Constructors Extension Method in C# C# | Class and Object C# | Abstract Classes Common Language Runtime (CLR) in C# C# | Encapsulation C# | Method Overloading
[ { "code": null, "e": 24127, "s": 24099, "text": "\n01 Feb, 2019" }, { "code": null, "e": 24281, "s": 24127, "text": "List<T>.Exists(Predicate<T>) Method is used to check whether the List<T> contains elements which match the conditions defined by the specified predicate." }, {...
Facing the ARIMA Model against Neural Networks | by ds_mt | Towards Data Science
Introduction The purpose of this small project is to go through the ARIMA model to evaluate its performance in a univariate dataset. Also, its performance will be compared with other techniques that are currently available to create predictions in time series using neural networks. The dataset that is going to be used, belongs to the UCI repository (http://archive.ics.uci.edu/ml/datasets/Beijing+PM2.5+Data) It has an hourly measurement of the quantity of PM2.5 in the air in the city of Beijing. This dataset comes with other information such as the meteorological data from that city. However, as the purpose of this exercise is to make a model from a univariate variable, this other information is not going to be taken into account. We will go step by step through the whole process: starting by importing the data, getting some insights to it, applying the ARIMA model and finally comparing the results with a neural network to evaluate the performance of each model. (Disclosure)This post consists of different methods for forecasting time series. However, none of these methods is perfect as there is no perfect way to predict the future, so these results should be taken with care and always with the advice of an expert. If the code is what you are looking for is all accessible in a Jupyter Notebook here As I mentioned previously this dataset contains the information about the amount of PM2.5 (ug/m3) concentration of particles in the air of Beijing. These are particles with a diameter of fewer than 2.5 micrometres that are floating in the air.(https://www.who.int/news-room/fact-sheets/detail/ambient-(outdoor)-air-quality-and-health)The world health organization states that exposure to these particles can cause cardiovascular and respiratory diseases and cancer. They estimate that this air pollution caused 4.2 million premature death per year in 2016. A quick look at the data to see what we need to handle. Regarding this first plot, we can see that at the end and at the beginning of each year the concentration of PM2.5 particles is higher than in other periods of the year, but it is still fuzzy data and we can barely have a better understanding of what is really happening. Because of this, some transformations are needed to be able to get a deeper insight into our data. There are many tools available, and here we are only going to use two, but there are many others that can provide better or different insights. Grouping by different frames of time The first method is as simple as to compute the mean of the data measurements by week or month. As we can see from the plots, the information that we get from the data using this method is not very clear. Moving average This time we are still going to use the mean but in a different way, by using the Moving Average, that computes the average of N given time steps. It will smooth the data allowing the viewer to infer some visible patterns or trends. In this last plot, we can clearly spot some regular patterns. However, these methods are very sensitive to outliers and as we can see in the first plot our data has many of them. Please note the difference between these two transformations because they look similar but they are not the same. In the average, we just compute the average per week and in the Moving Average (MA) we compute the average of N lagged observations. Although, the second one is more useful because it will help us to smooth the data removing the noise. First Conclusion There is nothing clear we can get from the data even though it seems to have many outliers. and one can think of these outliers as faulty measures by the devices related to any kind of misfunction. However, doing some research we will find that these levels have been already reached and documented in the capital of China. www.theguardian.com Getting closer to the last weeks The data that we have evaluated so far looks quite messy, and as the objective of this small project is to apply different forecasting techniques, we are going to focus the efforts in the last four weeks of the entire dataset. By doing so the visualizations are going the be easier and we will see clearly how the predictions fit in our data. In the distribution of the data, we can see that most of the data is grouped in the first values, looking like the exponential distribution. In this data dataset, there are 716 measures of the particle’s concentration, around one month of data. With a mean of 78 particles per hour. This means is considered as unhealthy and people should not be exposed during long periods of time to these levels. Stationarity Before applying any statistical model it’s important to check if our data is considered as stationary Stationarity basically means that the properties such as the mean and variance don’t change over time. (https://www.itl.nist.gov/div898/handbook/pmc/section4/pmc442.htm) There are various ways to check if data is stationary, and one good way is the Test Dickey-Fuller, which states that if the p-value is lower than a given threshold it won’t be considered as stationary. Test Dickey-Fuller As we proved with Dickey-Fuller Test, fortunately, our data is stationary which means that it doesn’t have any kind of trend and therefore it doesn’t need any transformations and we can directly to apply ARIMA. Sometimes the time series are non-stationary. For these cases, it is possible to apply transformations to the data that will make them stationary. Before going through ARIMA we are going to split the data that will help us to train the model, and after that evaluate how accurate it is with the test dataset. train_dataset = last_weeks['2014-12': '2014-12-29']test_dataset = last_weeks['2014-12-30': '2014'] Train dataset has the data of 29 days and the test set has 2 days. The purpose of splitting the dataset is because the model has to be tested with some labelled data, that means to see how the predictions are close to the real data. ARIMA stands for Autorregresive Integrated Moving Average. It is used for time series forecasting. It contains three different components. The autoregressive the regression of the time series onto himself, the Integrated (I) component is to correct the non-stationarity of the data. The last component Moving Average (MA) models the errors based on past errors. Each component receives different parameters AR(p), I(d), MA(q). To estimate the value of each parameter we need to get the Autocorrelation Function (ACF) and the Partial Autocorrelation Function (PACF) Autocorrelation Function (ACF) and Partial Autocorrelation Function (PACF) This functions will tell us how correlated are the observations in the time series. Also, and the main purpose is that the will indicate us which are the best coefficient to use in our ARIMA model. In our case the pattern in the PACF (significant correlations at the first or second lag followed by correlations that are not significant). The number of significant correlations in the PACF tells us the term of the autoregressive (AR) model. In our case, the coefficient is three. However, based on the pattern of the ACF (the function progressively decrease), we cannot infer the term for the Moving Average (MA) so the best option is to use zero. Applying ARIMA This first plot shows the residuals of our data, and we can observe that most of the data is distributed around zero. Let’s see more in detail how this is distributed. As we can see it has a similar shape as the Normal or Gaussian distributions (Symmetrical bell-shaped curve). Get some predictions Now it is time to get some predictions from the model, to evaluate how accurate our model is, we are going to use the test dataset we have made.Also, we need to perform a rolling forecast, that means after calculating each prediction add it and recalculate the model. In the plot above we can see the result of our data in the test data, looking like pretty well fitted! Evaluation Calculate the Mean Squared Error to obtain the accuracy MSE: 338.9 Now a model of neural networks is going to be applied, concretely we are going to use Recurrent Neural Networks Recurrent Neural Networks (RNN) RNN is a type of neural networks, which mainly are used in natural language processing (NLP) and predicting Time Series. The basic idea behind these type is that the state of each neuron is stored and fed to the next layer. This is why it is so used in NLP and Time series because it has in count the last observations to predict the next one. There is a type of RNN called Long Short-Term Memory, it was proposed to solve a huge problem that all the RNN presented, this is called The Vanishing Gradient Problems but we are not going to enter in this kind of details. This is all we need to know to apply to our dataset. This part is going to be much shorter than the previous one because basically to apply Neural Networks is easier than to apply ARIMA Model For the sake of the example, we are going to work on the last four weeks. Also, the datasets to train and test the network are going to be the same to correctly compare the two models. To have better accuracy in our network we need to first normalize the values of our data. Now our dataset is ranged between 0 and 1. The Recurrent Neural Networks predict the new observation based on X lagged observations. For our case, let’s try with 168 lagged observations what means around one week to get a new prediction. Now it’s time to create the architecture of the Neural Network! We are going to use Keras, which is a popular framework that is made on top of TensorFlow (the neural network library published by Google). Keras is so famous because it makes the task to build the Networks really easy. Now it’s time to create the architecture of the Neural Network! We are going to use Keras, which is a popular framework that is made on top of TensorFlow (the neural network library published by Google). Keras is so famous because it makes the task to build the Networks really easy. The architecture of the network Our network is made by LSTM layers, it contains five layers with 100x200x300x200x100 neurons.I used dropout to improve accuracy and reduce the loss after epoch.In order to calculate the loss of the network, I used the same loss function as before, the Mean Squared Error (MSE) function. regressor.fit(X_train, y_train, epochs = 100, batch_size = 32) Now the model is fitted to our train dataset the model and it’s time to create the predictions. Luckily, it looks that the predictions suit well to the real values, but the MSE tells a different thing. MSE: 409.1 It looks like we have a winner, as we can see the result with the Neural Networks is worse than the one obtained by ARIMA! During this practical case, we saw many different things starting by different concepts of statistical model and time series manipulations (different transformations, stationarity in time series, autocorrelation functions). Following by one statistical model (ARIMA) and Recurrent Neural Networks applied to our particular data set. We can see that ARIMA performs better to our test set with a smaller Mean squared error of 338.96 compared to 409.1 provided by the neural networks. There are still some other things to try but for this specific dataset with around 720 observations the price goes to the statistical model! Future projects Once this is understood the first thing that comes to mind is to apply the same methods to the whole dataset (with more than 41.000 observations. Here we will see which one behave better with a higher amount of data. The next (still with the same dataset) is to use the other variables to create the forecasting. In the beginning, we have got rid of around 7 different variables with valuable information that we are not using in our model. We can also, improve the architecture of the neural network until we reach an optimal point. There is another statistical model such as Seasonal Arima (SARIMA) that can maybe improve the metrics. Finally and the purpose of all of this study is to extract useful insights from the data, in our case, it will be about the PM2.5 levels in Beijing. ... but let’s see all these things in new posts.
[ { "code": null, "e": 185, "s": 172, "text": "Introduction" }, { "code": null, "e": 455, "s": 185, "text": "The purpose of this small project is to go through the ARIMA model to evaluate its performance in a univariate dataset. Also, its performance will be compared with other tec...
Difference between service-oriented (SOA) and Micro service Architecture (MSA) - GeeksforGeeks
28 Jul, 2020 1. Service-oriented architecture (SOA) :It is a huge collection of services in which services communicate with each other. This framework is used for designing a software system using a software architecture that views all components as services. The communication is provided by SOA generally used for data passing it could communicate two or more services and complete some activity. It provides various microservices as function which has following – 1. Loosely coupled 2. Reusable 3. Composable 4. Autonomic 5. Standardized 2. Microservice Architecture (MSA) :It takes large number of services and breaks down into small services or shareable components. It also called a monolith in which all functionality is placed into a single process. This approach is used for developing application and communication with different approaches which may write in different programming language and data storage. Here are some characteristic functions of MSA – 1. Business capabilities 2. Products 3. Smart End Point 4. Automation 5. Evolutionary Difference between SOA and MSA : Difference Between Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference between Process and Thread Stack vs Heap Memory Allocation Difference Between Method Overloading and Method Overriding in Java Differences between JDK, JRE and JVM Types of Software Testing Software Engineering | COCOMO Model Software Engineering | Spiral Model Software Engineering | Classical Waterfall Model Functional vs Non Functional Requirements
[ { "code": null, "e": 23815, "s": 23787, "text": "\n28 Jul, 2020" }, { "code": null, "e": 24201, "s": 23815, "text": "1. Service-oriented architecture (SOA) :It is a huge collection of services in which services communicate with each other. This framework is used for designing a s...
How to print number of paragraphs in textview in android?
This example demonstrate about How to print number of paragraphs in textview in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center_horizontal" android:layout_marginTop="100dp" tools:context=".MainActivity"> <TextView android:id="@+id/text" android:gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content"> </TextView> </LinearLayout> In the above code, we have taken textview to show paragraph and toast will show the information about number of paragraphs. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { TextView text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text = findViewById(R.id.text); text.setText("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."); String[] para = text.getText().toString().split("\r\n\r\n"); Toast.makeText(MainActivity.this, "" + para.length, Toast.LENGTH_LONG).show(); } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code
[ { "code": null, "e": 1151, "s": 1062, "text": "This example demonstrate about How to print number of paragraphs in textview in android." }, { "code": null, "e": 1280, "s": 1151, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all requir...
How to build a Neural Network for Voice Classification | by Jurgen Arias | Towards Data Science
Wouldn’t it be great to be able to have transcriptions of our Zoom meetings telling us in plain text who said what during the meeting? This project was born from the idea of transcribing meetings telling you what each person said. We have many transcribing tools for speech to text but not many for identifying each speaker. For this, we will build a python voice classifier from scratch with all the code included here. First, as always, we need data. This data comes from OpenSLR. We will use 30 different speakers and 4 samples per speaker for our training data, giving us 120 samples. The samples average 15 seconds each thus about one minute per speaker for training. 30 speakers is a good amount of people for our problem statement; and as I have conducted this project already, I can assert that one minute is good enough to give us good results. In addition to the 120 samples for training, we also need validation and testing data. We will validate on 3 samples and test on 3 samples. Since we have 30 speakers, we will need 90 samples for validation and 90 samples for testing. Therefore, we will need 10 voice clips from each speaker. To summarize the samples, we will use 120 voice clips for the training data, 90 voice clips for validation data, and 90 voice clips for testing data for a total of 300 voice clips. Once we have our voice clips in three different folders for training, validation and testing, we can create our pandas dataframes. We need to import os so that we can create a dataframe from the files in our folders (I am working on a mac, for other operating systems, the process might be a little different). My folder for training is called 30_speakers_train. import os#list the filesfilelist = os.listdir('30_speakers_train') #read them into pandastrain_df = pd.DataFrame(filelist) This will create a dataframe for my training data. It is very important to check the size of our dataframe, in order to make sure that it matches the number of files in our folder. Let us name the file column as ‘file’. # Renaming the column name to filetrain_df = train_df.rename(columns={0:'file'}) Sometimes a ‘.DS_Store’ file is created and we have to find and drop that specific file in order to continue. After that we would need to reset the index of our dataframe. Here is an example of that: # Code in case we have to drop the '.DS_Store' and reset the indextrain_df[train_df['file']=='.DS_Store']train_df.drop(16, inplace=True)train_df = train_df.sample(frac=1).reset_index(drop=True) Now, we need to identify each speaker. In my file names, the first set of numbers is the speaker ID thus I wrote a little code to create a column with that ID. # We create an empty list where we will append all the speakers ids for each row of our dataframe by slicing the file name since we know the id is the first number before the hashspeaker = []for i in range(0, len(df)): speaker.append(df['file'][i].split('-')[0])# We now assign the speaker to a new column train_df['speaker'] = speaker Our dataframe should look like this: We do the same for the validation and testing files and get three different dataframes. Now that we have the dataframes, we need to write a function to extract the audio properties of each audio file. For this we use librosa which is a great python library for audio manipulation. We need to pip install librosa and import librosa. The following is the function that parses through every file in our folder and extracts 5 numerical features from each file, namely the mfccs, chroma, mel, contrast and tonnetz. def extract_features(files): # Sets the name to be the path to where the file is in my computer file_name = os.path.join(os.path.abspath('30_speakers_train')+'/'+str(files.file))# Loads the audio file as a floating point time series and assigns the default sample rate # Sample rate is set to 22050 by default X, sample_rate = librosa.load(file_name, res_type='kaiser_fast')# Generate Mel-frequency cepstral coefficients (MFCCs) from a time series mfccs = np.mean(librosa.feature.mfcc(y=X, sr=sample_rate, n_mfcc=40).T,axis=0)# Generates a Short-time Fourier transform (STFT) to use in the chroma_stft stft = np.abs(librosa.stft(X))# Computes a chromagram from a waveform or power spectrogram. chroma = np.mean(librosa.feature.chroma_stft(S=stft, sr=sample_rate).T,axis=0)# Computes a mel-scaled spectrogram. mel = np.mean(librosa.feature.melspectrogram(X, sr=sample_rate).T,axis=0)# Computes spectral contrast contrast = np.mean(librosa.feature.spectral_contrast(S=stft, sr=sample_rate).T,axis=0)# Computes the tonal centroid features (tonnetz) tonnetz = np.mean(librosa.feature.tonnetz(y=librosa.effects.harmonic(X), sr=sample_rate).T,axis=0)return mfccs, chroma, mel, contrast, tonnetz Each mfcc is an array of length 40, chroma is 12, mel is 128, contrast is 7 and tonnetz is 6. Overall we have 193 numerical features for each voice clip from the audio features we have chosen. Feel free to try different ones if you would like from: librosa feature extraction. We apply the function to each single audio file and store that information. Note that this does take some minutes and it might even take hours depending on how much data you are using and your computing power. train_features = train_df.apply(extract_features, axis=1) Now we concatenate all those numerical features for each file so that we have a single array of 193 numbers for each file to feed into our neural network. features_train = []for i in range(0, len(train_features)): features_train.append(np.concatenate(( train_features[i][0], train_features[i][1], train_features[i][2], train_features[i][3], train_features[i][4]), axis=0)) Now we can set our X_train to be the numpy array of our features: X_train = np.array(features_train) Similarly, we do the same steps from above from the very beginning for our validation and test data. We should get an X_val and X_test. Now, we are done with our X data. For Y, we need the speakers’ IDs. Remember we are doing supervised learning so we need the target data. We have that from our original dataframes, therefore we just get those values. y_train = np.array(train_df['speaker'])y_val = np.array(val_df['speaker']) We need to hot encode y in order to be able to use it for our neural network. You will need to import LabelEncoder from sklearn and to_categorical from keras which uses Tensorflow. from sklearn.preprocessing import LabelEncoderfrom keras.utils.np_utils import to_categorical# Hot encoding ylb = LabelEncoder()y_train = to_categorical(lb.fit_transform(y_train))y_val = to_categorical(lb.fit_transform(y_val)) Now we need to scale our X: from sklearn.preprocessing import StandardScalerss = StandardScaler()X_train = ss.fit_transform(X_train)X_val = ss.transform(X_val)X_test = ss.transform(X_test) And finally, we are ready for the fun part: building the neural network! We will use a simple feed forward neural network. The input will be our 193 features. I played around with the dropout rates but you can change those values if you would like. Using relu is pretty standard. The output is softmax since we have 30 different classes and we use categorical crossentropy because of the different classes. from keras.models import Sequentialfrom keras.layers import Dense, Dropout, Activation, Flattenfrom keras.callbacks import EarlyStopping# Build a simple dense model with early stopping and softmax for categorical classification, remember we have 30 classesmodel = Sequential()model.add(Dense(193, input_shape=(193,), activation = 'relu'))model.add(Dropout(0.1))model.add(Dense(128, activation = 'relu'))model.add(Dropout(0.25))model.add(Dense(128, activation = 'relu'))model.add(Dropout(0.5))model.add(Dense(30, activation = 'softmax'))model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam')early_stop = EarlyStopping(monitor='val_loss', min_delta=0, patience=100, verbose=1, mode='auto') Now we fit the model with the training and validation data: history = model.fit(X_train, y_train, batch_size=256, epochs=100, validation_data=(X_val, y_val), callbacks=[early_stop]) This is some code to see a graph of the training and validation accuracy: # Check out our train accuracy and validation accuracy over epochs.train_accuracy = history.history['accuracy']val_accuracy = history.history['val_accuracy']# Set figure size.plt.figure(figsize=(12, 8))# Generate line plot of training, testing loss over epochs.plt.plot(train_accuracy, label='Training Accuracy', color='#185fad')plt.plot(val_accuracy, label='Validation Accuracy', color='orange')# Set titleplt.title('Training and Validation Accuracy by Epoch', fontsize = 25)plt.xlabel('Epoch', fontsize = 18)plt.ylabel('Categorical Crossentropy', fontsize = 18)plt.xticks(range(0,100,5), range(0,100,5))plt.legend(fontsize = 18); It should look something like this: It looks like we got some good accuracy! Let’s check the values with our test data. We can generate predictions with the results of our neural network and compare them to the actual values. # We get our predictions from the test datapredictions = model.predict_classes(X_test)# We transform back our predictions to the speakers idspredictions = lb.inverse_transform(predictions)# Finally, we can add those predictions to our original dataframetest_df['predictions'] = predictions Now our test data dataframe should look like this: # Code to see which values we got wrongtest_df[test_df['speaker'] != test_df['predictions']]# Code to see the numerical accuracy(1-round(len(test_df[test_df['speaker'] != test_df['predictions']])/len(test_df),3))*100 You should get something like this: 98.9% correct predictions! I had to run the neural network four times to finally get one of the predictions wrong. In the previous three runs, the neural network got all predictions right but I wanted to show how to find a wrong prediction. Thus with one minute of training audio, the neural network is near perfect for 30 speakers! This proves how powerful a simple neural network is! I hope it was helpful! Here is a link to my jupyter notebook with all the code. I also did this and similar projects using Convolutional Neural Networks (CNN), you can see my other post explaining that process here in case you are interested. Datasets: http://www.openslr.org/12/ [1] David Kaspar, Alexander Bailey, Patrick Fuller, Librosa: A Python Audio Library (2019) [2] Rami S. Alkhawaldeh, DGR: Gender Recognition of Human Speech Using One-Dimensional Conventional Neural Network (2019) [3] Kory Becker, Identifying the Gender of a Voice using Machine Learning (2016) [4] Jonathan Balaban, Deep Learning Tips and Tricks (2018) [5] Youness Mansar, Audio Classification : A Convolutional Neural Network Approach (2018) [6] Faizan Shaikh, Getting Started with Audio Data Analysis using Deep Learning (with case study) (2017) [7] Mike Smales, Sound Classification using Deep Learning, (2019) [8] Aaqib Saeed, Urban Sound Classification, Part 1, (2016) [9] Marc Palet Gual, Voice gender identification using deep neural networks running on FPGA, (2016) [10] Kamil Ciemniewski, Speech Recognition from scratch using Dilated Convolutions and CTC in TensorFlow, (2019) [11] Admond Lee, How To Build A Speech Recognition Bot With Python (2019) [12] Adrian Yijie Xu, Urban Sound Classification using Convolutional Neural Networks with Keras: Theory and Implementation, (2019) [13] Sainath Adapa, Kaggle freesound audio tagging (2018) [14] Librosa Feature Extraction
[ { "code": null, "e": 593, "s": 172, "text": "Wouldn’t it be great to be able to have transcriptions of our Zoom meetings telling us in plain text who said what during the meeting? This project was born from the idea of transcribing meetings telling you what each person said. We have many transcribin...
Ticket sellers | Practice | GeeksforGeeks
There are N ticket sellers where the ith ticket seller has A[i] tickets. The price of a ticket is the number of tickets remaining with the ticket seller. They are allowed to sell at most K tickets. Find the maximum amount they can earn by selling K tickets. The amount of tickets of each seller is provided in array A. Give the answer modulo 109 + 7. Example 1: Input: N = 5, K = 3 A = {4, 3, 6, 2, 4} Output: 15 Explaination: Consider 0 based indexing. For first two turns the 2nd seller sells. For the third turn either 0th or 2nd seller can sell. So the total becomes 6 + 5 + 4 = 15. Example 2: Input: N = 6, K = 2 A = {5, 3, 5, 2, 4, 4} Output: 10 Explaination: The turns are taken by 0th and 2nd seller. 5 + 5 = 10 is the maximum amount. Your Task: You do not need to take input or print anything. Your task is to complete the function maxAmount() which takes N, K, and the array A as input parameters and returns the maximum amount they can get by selling K tickets. Expected Time Complexity: O(N) Expected Auxiliary Space: O(N) Constraints: 1 ≤ N ≤ 105 1 ≤ A[i], K ≤ 106 -1 chessnoobdj4 months ago C++ int maxAmount(int N, int K, int A[]) { int ans = 0, mod = 1e9+7; priority_queue <int> pq; for(int i=0; i<N; i++) pq.push(A[i]); while(K--){ int num = pq.top(); pq.pop(); ans += num; pq.push(num-1); ans %= mod; } return ans; } 0 pratikpatil56116 months ago Error In Driver Code 0 chiragjaiswal4547 months ago Expected Time Complexity Should be : O(NlogN) 0 Chirag Jaiswal7 months ago Chirag Jaiswal All solution are of O(NlogN) or O(NlogK) time complexity...Is there any solution exist with O(N) ???? 0 Chirag Jaiswal This comment was deleted. 0 Chirag Jaiswal This comment was deleted. 0 Sk Jishan Ali7 months ago Sk Jishan Ali please update the driver code in java as the array 'A' is initialized as int A=new int[N]; 0 Tushar Saini8 months ago Tushar Saini void heapify(int arr[],int index,int n){ int left=2*index+1; int right=2*index+2; int largest=index; if(left<n &&="" arr[largest]<arr[left])="" largest="left;" if(right<n="" &&="" arr[largest]<arr[right])="" largest="right;" if(largest!="index)" {="" swap(arr[largest],arr[index]);="" heapify(arr,largest,n);="" }="" }="" void="" buildheap(int="" arr[],int="" n)="" {="" for(int="" i="n/2" -1;i="">=0;i--) heapify(arr,i,n);}class Solution{public: int maxAmount(int n, int k, int arr[]) { int count=0;//track of count int mx=0;//number totla buildheap(arr,n); while(count<k) {="" mx="(mx%1000000007" +="" arr[0]%1000000007)%1000000007;="" arr[0]--;="" heapify(arr,0,n);="" count++;="" }="" o(n)+o(kl0ogn="" return="" mx;="" }="" };=""> 0 VISHAL SHARMA8 months ago VISHAL SHARMA https://uploads.disquscdn.c... Using Priority queue 0 navidulhaque10 months ago navidulhaque time taken 0.95sec---int maxAmount(int N, int K, int A[]) { // code here vector < int > v; int max1 = 0; int curr = 0; for (int i = 0; i < N; i++) { v.push_back(A[i]); } make_heap(v.begin(), v.end()); while (K--) { curr = v.front(); pop_heap(v.begin(), v.end()); v.pop_back(); max1 += curr % 1000000007; v.push_back((curr - 1)); push_heap(v.begin(), v.end()); } return max1 % 1000000007;} 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": 300, "s": 226, "text": "There are N ticket sellers where the ith ticket seller has A[i] tickets. " }, { "code": null, "e": 486, "s": 300, "text": "The price of a ticket is the number of tickets remaining with the ticket seller. They are allowed to sell at mos...
C++ Iterator Library - advance
It advances the iterator it by n element positions. Following is the declaration for std::advance. template <class InputIterator, class Distance> void advance (InputIterator& it, Distance n); it − Iterator used in advance. it − Iterator used in advance. n − It is the number of position to be advanced in iterator. n − It is the number of position to be advanced in iterator. none If any of the arithmetical operations performed on the iterator throws. constant for random-access iterators. The following example shows the usage of std::advance. #include <iostream> #include <iterator> #include <list> int main () { std::list<int> mylist; for (int i = 0; i < 10; i++) mylist.push_back (i*10); std::list<int>::iterator it = mylist.begin(); std::advance (it,9); std::cout << "The 9th element in mylist is: " << *it << '\n'; return 0; } Let us compile and run the above program, this will produce the following result − The 9th element in mylist is: 90 Print Add Notes Bookmark this page
[ { "code": null, "e": 2655, "s": 2603, "text": "It advances the iterator it by n element positions." }, { "code": null, "e": 2702, "s": 2655, "text": "Following is the declaration for std::advance." }, { "code": null, "e": 2798, "s": 2702, "text": "template <cl...
Seaborn can do the job, then why Matplotlib? | by Mahbubul Alam | Towards Data Science
I had this thought a while back — is learning Matplotlib essential for beginners? Or can they get away with Seaborn? That thought came back recently while mentoring a cohort of data science students. I know Matplotlib is a great library, it gives a lot of flexibility for customized data visualization. But I also know it’s a complex library, especially for people who are new to data science and data visualization. It can be intimidating to some too! In most data science curriculums Matplotlib and Seaborn are taught simultaneously, which, in my observation, creates quite a bit of confusion among people. They don’t understand why they needed both libraries if just one works. To alleviate this confusion I generally advise students to learn Seaborn first; and once they get comfortable with it, and understand its limitations, they will naturally realize the value of Matplotlib. If the purpose of data visualization is to visualize distribution, trends and relationships of variables, Seaborn has all of these capabilities. All major statistical plots — distribution plot, boxplot, violin plot, scatter plot, barplot — can be created with Seaborn. For beginners, that’s all they need. But then why Matplotlib? Because Seaborn takes you just that far. Seaborn is a clear winner at the beginning due to its syntax simplicity and aesthetics. But with complexity, Matplotlib flexes its muscles. The purpose of this article is to compare Seaborn and Matplotlib with a few basic figures and with minimal code. I’ll also show areas where Matplotlib shines and what makes it powerful in data visualization. I am using the following dataset for the demo that comes with Seaborn: import seaborn as snsdf = sns.load_dataset('tips')df.head() As long as basic statistical plots are concerned, there is not much difference. We can create a simple scatterplot for two variables total_bill and tips using Seaborn: sns.scatterplot(x='total_bill', y = 'tip', data = df) We can do the same using Matplotlib: plt.scatter(x='total_bill', y = 'tip', data = df) If you take a closer look you’ll probably see some minor differences already, but let’s ignore that for a moment. Let’s try another plot, this time a boxplot. sns.boxplot(y='total_bill', data = df) And this is how it appears in Matplotlib: plt.boxplot(x='total_bill', data = df) In both cases, Seaborn and Matplotlib deliver similar statistical information, for example. But you probably realize the differences in plot quality and appearance. Seaborn shines in two areas: 1) simplicity and 2) aesthetics. By simplicity I mean its short, intuitive syntax to create plots. Let’s check out this example — the scatterplot above but with some added features. First with Matplotlib: color = {'Lunch': 'blue', 'Dinner': 'darkorange'}plt.scatter(x='total_bill', y='tip', data=df, c = df['time'].map(color)) Now with Seaborn: sns.scatterplot(x='total_bill', y='tip', data=df, hue='time') If you look at the codes, you’ll admit Seaborn is quite elegant and intuitive whereas Matplotlib’s codes are messy. Now let’s turn to aesthetics. Granted, aesthetics is a subjective matter, but even then, you’ll appreciate the plot which looks better and aesthetically pleasing to you. plt.violinplot(df['total_bill']) sns.violinplot(y=df['total_bill'] If you compare the two violin plots created by two libraries, two things stand out: Seaborn’s plot is aesthetically pleasing Seaborn generates more information (do you see a boxplot inside the violin plot?) Matplotlib is a massive library, with more than 70,000 lines of code I hear. People say it is a “low-level” library — meaning, it gives data scientists a lot of flexibility compared to the “high-level” one-liner Seaborn codes. Here are just a few examples of how Matplotlib powers up data visualization. Matplotlib shines its best at subplots. You can create as many subplots as you want with plt.subplot(nrows, ncols)and put anything you want in each subplot. Below is a figure created with 4 empty subplots (nrows=2, ncols=2). fig, ax = plt.subplots(2,2, figsize=(10,6)) We can now add Seaborn plots and place them wherever we want in the figure. Let’s utilize the 2nd and 4th subplots clockwise to place a boxplot and a scatterplot. fig, ax = plt.subplots(2,2, figsize=(10,6))# boxplotsns.boxplot(y='tip', data=df, ax=ax[0,1])ax[0,1].set_title('This is Seaborn boxplot')# scatterplotsns.scatterplot(x='total_bill', y='tip', data=df, ax=ax[1,0])ax[1,0].set_title("This is Seaborn scatterplot")fig.tight_layout() You can annotate your plots in a variety of ways —by adding texts, symbols, points, boxes, circles and much more. Here is an example — in the scatterplot below we want to indicate two data points as outliers. plt.figure(figsize=(8,6))fig, ax = plt.subplots()sns.scatterplot(ax = ax, x=df['total_bill'], y = df['tip'])ax.annotate('Outlier', xy=(50, 10), xytext=(40, 9), arrowprops=dict(facecolor='red'))ax.annotate('Outlier', xy=(7.5, 5.3), xytext=(10, 7), arrowprops=dict(facecolor='red')) You can take this idea in many directions and customize it in many different ways (e.g. annotating a time series plot to explain high points and low points). Data scientists usually visualize data in two-dimensional plots. But Matplotlib also provides functionalities to create three-dimensional plots with its mplot3d toolkit. All you need to do is pass the keyword projection='3d' to an axis creation routine (e.g. add_subplot(projection=’3d’)). Here’s an example: import matplotlib.pyplot as pltimport numpy as npn_radii = 8n_angles = 36radii = np.linspace(0.125, 1.0, n_radii)angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)[..., np.newaxis]x = np.append(0, (radii*np.cos(angles)).flatten())y = np.append(0, (radii*np.sin(angles)).flatten())z = np.sin(-x*y)ax = plt.figure(figsize=(14,8)).add_subplot(projection='3d')ax.plot_trisurf(x, y, z, linewidth=0.2, antialiased=True) All in all, Matplotlib helps create all kinds of custom plots of production quality. You can lay out your figure exactly the way you want, set the appropriate resolution and annotate figures as needed. To extend functionalities, there are several available toolkits such as Basemap, Cartopy, matplotlib2tikz, Qt, GTK etc. If you are interested in specific specialties of visualization there are plenty of resources and extensive documentation available online. Seaborn is a high-level library. It provides simple codes to visualize complex statistical plots, which also happen to be aesthetically pleasing. But Seaborn was built on top of Matplotlib, meaning it can be further powered up with Matplotlib functionalities. The original intent behind this article was to investigate whether you need to learn Matplotlib and Seaborn libraries as a beginner. You do not have to choose one or the other, you need both, but the question is do you need to learn them together at once? To reiterate what I already said: learn Seaborn first, spend some time visualizing with it, understand its limitations. Seaborn’s limitations will naturally lead you into Matplotlib. Hope it was a useful discussion, if you have comments feel free to write them down below or connect with me via Medium, Twitter or LinkedIn.
[ { "code": null, "e": 372, "s": 172, "text": "I had this thought a while back — is learning Matplotlib essential for beginners? Or can they get away with Seaborn? That thought came back recently while mentoring a cohort of data science students." }, { "code": null, "e": 475, "s": 372,...
How to access the table values in R?
Sometimes we want to extract table values, especially in cases when we have a big table. This helps us to understand the frequency for a particular item in the table. To access the table values, we can use single square brackets. For example, if we have a table called TABLE then the first element of the table can accessed by using TABLE[1]. Live Demo x1<−rpois(200,5) x1 [1] 10 7 6 4 3 8 4 5 4 4 2 8 7 5 3 5 3 5 3 9 7 5 8 4 2 [26] 7 6 6 5 3 11 3 5 8 7 6 3 5 6 1 3 7 8 4 6 6 3 6 7 6 [51] 14 3 3 3 8 9 4 3 9 2 8 5 2 2 3 8 4 3 3 6 5 6 6 5 5 [76] 5 4 3 1 6 11 9 10 7 6 4 4 5 8 4 4 2 6 6 7 5 3 5 3 4 [101] 5 2 6 6 5 6 2 5 5 6 3 4 5 4 16 5 2 0 2 5 5 5 2 4 3 [126] 6 3 3 2 3 5 5 6 3 7 4 5 7 4 7 5 6 5 5 6 11 3 2 7 4 [151] 4 5 7 4 9 6 4 1 4 8 4 3 3 10 7 4 8 5 4 9 5 6 3 2 4 [176] 8 4 5 7 4 6 5 5 1 7 4 7 6 5 4 7 9 3 11 5 6 4 4 3 4 Table1<−table(x1) Table1 x1 0 1 2 3 4 5 6 7 8 9 10 11 14 16 1 4 14 31 35 39 29 19 12 7 3 4 1 1 Table1[1] 0 1 Table1[2] 1 4 Table1[5] 4 35 Table1[10] 9 7 Live Demo x2<−rpois(200,10) x2 [1] 8 8 10 12 12 9 7 8 13 8 9 3 10 8 9 11 11 15 10 12 9 5 14 8 9 [26] 14 7 4 7 8 9 12 8 10 16 7 7 6 10 9 14 17 11 6 10 7 13 13 8 11 [51] 11 6 8 9 11 9 16 8 10 11 6 12 10 13 10 10 11 6 12 6 9 7 6 7 17 [76] 16 13 9 9 13 13 9 10 10 10 13 9 11 10 10 13 13 11 15 10 12 7 11 15 2 [101] 10 7 14 7 15 9 9 13 19 16 12 3 13 20 10 16 7 16 16 17 13 11 7 11 8 [126] 8 9 2 10 16 12 13 6 10 12 16 10 15 8 5 9 11 8 3 5 7 10 10 5 11 [151] 5 8 6 11 2 7 8 9 17 9 10 10 15 7 8 8 14 8 10 15 6 12 12 11 8 [176] 8 14 8 8 17 8 11 14 11 8 12 13 9 13 9 9 7 5 12 9 6 12 9 11 12 Table2<−table(x2) Table2 x2 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 19 20 3 3 1 6 11 17 26 25 26 20 16 16 7 7 9 5 1 1 Table2[2] 3 3 Table2[10] 11 20 Table2[15] 16 9 Live Demo x3<−sample(501:510,200,replace=TRUE) x3 [1] 501 505 508 503 506 510 505 507 502 501 503 502 502 509 506 509 507 504 [19] 501 510 501 509 506 504 501 501 503 506 509 504 505 505 509 502 509 509 [37] 508 504 505 506 503 504 505 503 507 506 503 510 506 506 506 505 502 506 [55] 502 503 510 501 505 510 501 508 506 506 501 507 508 508 507 505 508 509 [73] 507 506 508 504 510 506 510 505 509 504 505 505 510 507 504 505 503 506 [91] 507 509 504 504 506 508 503 502 505 508 510 508 506 501 501 507 506 501 [109] 504 507 501 510 508 504 510 507 506 505 502 507 510 506 501 510 509 508 [127] 503 508 504 508 504 505 503 503 508 506 501 503 502 509 502 508 509 506 [145] 510 502 508 507 509 507 506 510 501 508 502 505 502 503 510 508 503 506 [163] 505 505 509 502 504 501 501 508 508 507 509 501 505 509 502 508 508 505 [181] 508 502 509 501 508 502 510 507 504 509 503 503 509 501 504 503 508 501 [199] 506 502 Table3<−table(x3) Table3 x3 501 502 503 504 505 506 507 508 509 510 22 18 18 17 21 25 16 26 20 17 Table3[1] 501 22 Table3[5] 505 21 Table3[1:5] x3 501 502 503 504 505 22 18 18 17 21 Table3[6:10] x3 506 507 508 509 510 25 16 26 20 17
[ { "code": null, "e": 1405, "s": 1062, "text": "Sometimes we want to extract table values, especially in cases when we have a big table. This helps us to understand the frequency for a particular item in the table. To access the table values, we can use single square brackets. For example, if we have...
MySQL query to convert timediff() to seconds?
For this, you can use TIME_TO_SEC() function. Let us first create a table − mysql> create table DemoTable -> ( -> SourceTime time, -> DestinationTime time -> ); Query OK, 0 rows affected (1.33 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values('10:20:00','4:50:54'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values('12:05:10','7:45:12'); Query OK, 1 row affected (0.30 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +------------+-----------------+ | SourceTime | DestinationTime | +------------+-----------------+ | 10:20:00 | 04:50:54 | | 12:05:10 | 07:45:12 | +------------+-----------------+ 2 rows in set (0.00 sec) Following is query to convert the time difference to seconds − mysql> SELECT ABS(TIME_TO_SEC(timediff(DestinationTime, SourceTime))) from DemoTable; This will produce the following output − +---------------------------------------------------------+ | ABS(TIME_TO_SEC(timediff(DestinationTime, SourceTime))) | +---------------------------------------------------------+ | 19746 | | 15598 | +---------------------------------------------------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1138, "s": 1062, "text": "For this, you can use TIME_TO_SEC() function. Let us first create a table −" }, { "code": null, "e": 1272, "s": 1138, "text": "mysql> create table DemoTable\n -> (\n -> SourceTime time,\n -> DestinationTime time\n -> );\nQuer...
math Package in Golang
08 Jun, 2020 Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. Example 1: // Golang program to illustrate how to // find the IEEE 754 binary representation package main import ( "fmt" "math") // Main function func main() { // Finding IEEE 754 binary // representation of the // given numbers // Using Float64bits() function res_1 := math.Float64bits(2) res_2 := math.Float64bits(1) res_3 := math.Float64bits(0) res_4 := math.Float64bits(2.3) // Displaying the result fmt.Println("Result 1: ", res_1) fmt.Println("Result 2: ", res_2) fmt.Println("Result 3: ", res_3) fmt.Println("Result 4: ", res_4) } Output: Result 1: 4611686018427387904 Result 2: 4607182418800017408 Result 3: 0 Result 4: 4612361558371493478 Example 2: // Golang program to illustrate // the use of math.Yn() function package main import ( "fmt" "math") // Main function func main() { // Finding the order-n Bessel // function of the second kind // Using Yn() function res_1 := math.Yn(-3, -2) res_2 := math.Yn(6, 3) res_3 := math.Yn(1, 1.1) res_4 := math.Yn(1, math.NaN()) res_5 := math.Yn(-1, 0) // Displaying the result fmt.Println("Result 1: ", res_1) fmt.Println("Result 2: ", res_2) fmt.Println("Result 3: ", res_3) fmt.Println("Result 4: ", res_4) fmt.Println("Result 5: ", res_5) } Output: Result 1: NaN Result 2: -5.436470340703773 Result 3: -0.698119560067667 Result 4: NaN Result 5: +Inf Golang-Math Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. strings.Replace() Function in Golang With Examples fmt.Sprintf() Function in Golang With Examples Arrays in Go Golang Maps Interfaces in Golang Slices in Golang How to Parse JSON in Golang? How to convert a string in lower case in Golang? How to Trim a String in Golang? Different Ways to Find the Type of Variable in Golang
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jun, 2020" }, { "code": null, "e": 184, "s": 28, "text": "Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package." }, { "code...
How to create a Hero Image using HTML and CSS ?
30 Sep, 2021 Hero image can be designed using HTML and CSS. This article contains two sections. The first section attaches the image and design the basic structure. The second section design the image and texts on the images. The hero image looks attractive when you are using it as a banner. Suppose you want to inform others about your newly added features then it will be the best procedure to proceed to use those features. Creating Structure: In this section, we will create the basic structure for the hero image cover picture. We will attach the image and put the text that will be placed on the image in the next section. HTML code: The HTML code is used to create a structure of hero image. Since it does not contain CSS so it is just a simple structure. We will use some CSS property to make it attractive. HTML <!DOCTYPE html><html> <head> <title>Create a hero image</title></head> <body> <div class="container"> <!-- background image --> <img class="gfg" src="https://media.geeksforgeeks.org/wp-content/uploads/20191213145442/img40.png"> <!-- title and tag line with button --> <div class="logo"> <h1>GeeksforGeeks</h1> <p>A Computer Science Portal for Geeks</p> <button>Hire with Us</button> </div> </div></body> </html> Designing the Structure: In the previous section, we have created the structure of the basic web-page and now we are going to use the hero image with the title, tag, and a button. We will design the structure in this section. CSS code: CSS code is used to make an attractive website. This CSS property is used to make the hero image attractive and eye catching. HTML <style> /* blurring the image */ .gfg { filter: blur(5px); width: 100%; } /* designing title and tag line */ .logo { text-align:center; position: absolute; font-size: 18px; top: 50px; left: 27%; color: white; } h1, p { border: 4px solid white; padding: 10px 50px; position: relative; border-radius: 10px; font-family: Arial, Helvetica, sans-serif; } h1:hover { background: -webkit-linear-gradient( green, lime); -webkit-background-clip: text; -webkit-text-fill-color: transparent; } /* Designing button */ .logo button { border: none; outline: 0; display: inline-block; padding: 10px 25px; color: black; background-color: #ddd; text-align: center; cursor: pointer } .logo button:hover { background-color: green; color: white; }</style> Combining the HTML and CSS Code: This examples combine both HTML and CSS code to design Hero image. HTML <!DOCTYPE html><html> <head> <title>Create a hero image</title> <style> /* blurring the image */ .gfg { filter: blur(5px); width: 100%; } /* designing title and tag line */ .logo { text-align:center; position: absolute; font-size: 18px; top: 50px; left: 27%; color: white; } h1, p { border: 4px solid white; padding: 10px 50px; position: relative; border-radius: 10px; font-family: Arial, Helvetica, sans-serif; } h1:hover { background: -webkit-linear-gradient( green, lime); -webkit-background-clip: text; -webkit-text-fill-color: transparent; } /* Designing button */ .logo button { border: none; outline: 0; display: inline-block; padding: 10px 25px; color: black; background-color: #ddd; text-align: center; cursor: pointer } .logo button:hover { background-color: green; color: white; } </style></head> <body> <div class="container"> <!-- background image --> <img class="gfg" src="https://media.geeksforgeeks.org/wp-content/uploads/20191213145442/img40.png"> <!-- title and tag line with button --> <div class="logo"> <h1>GeeksforGeeks</h1> <p>A Computer Science Portal for Geeks</p> <button>Hire with Us</button> </div> </div></body> </html> Output: kalrap615 arorakashish0911 CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 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? REST API (Introduction) Hide or show elements in HTML using display property
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Sep, 2021" }, { "code": null, "e": 468, "s": 52, "text": "Hero image can be designed using HTML and CSS. This article contains two sections. The first section attaches the image and design the basic structure. The second section des...
PostgreSQL – JSON Data Type
22 Feb, 2021 JSON stands for JavaScript Object Notation. It is used to store data in the form of key-value pairs and is generally used for communicating between the server and the client. Contrary to other formats, JSON is human-readable text.PostgreSQL has support for native JSON data type since version 9.2. It offers numerous functions and operators for handling JSON data. Syntax: variable_name json; Now let’s look into a few examples for demonstration. Example 1:First, create a table (say, orders) using the below command: CREATE TABLE orders ( ID serial NOT NULL PRIMARY KEY, info json NOT NULL ); Now insert some data into the orders table as follows: INSERT INTO orders (info) VALUES ( '{ "customer": "Raju Kumar", "items": {"product": "coffee", "qty": 6}}' ); Now we will query for the orders information using the below command: SELECT info FROM orders; Output: Example 2:In the above example we created an orders table and added single JSON data into it. In this example we will be looking onto inserting multiple JSON data in the same table using the command below: INSERT INTO orders (info) VALUES ( '{ "customer": "Nikhil Aggarwal", "items": {"product": "Diaper", "qty": 24}}' ), ( '{ "customer": "Anshul Aggarwal", "items": {"product": "Tampons", "qty": 1}}' ), ( '{ "customer": "Naveen Arora", "items": {"product": "Toy Train", "qty": 2}}' ); Now we will query for the orders information using the below command: SELECT info FROM orders; Output: postgreSQL postgreSQL-dataTypes PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Feb, 2021" }, { "code": null, "e": 393, "s": 28, "text": "JSON stands for JavaScript Object Notation. It is used to store data in the form of key-value pairs and is generally used for communicating between the server and the client. ...
Largest trapezoid that can be inscribed in a semicircle
29 Jun, 2022 Given a semicircle of radius r, the task is to find the largest trapezoid that can be inscribed in the semicircle, with base lying on the diameter.Examples: Input: r = 5 Output: 32.476 Input: r = 8 Output: 83.1384 Approach: Let r be the radius of the semicircle, x be the lower edge of the trapezoid, and y the upper edge, & h be the height of the trapezoid. Now from the figure, r^2 = h^2 + (y/2)^2or, 4r^2 = 4h^2 + y^2y^2 = 4r^2 – 4h^2y = 2√(r^2 – h^2)We know, Area of Trapezoid, A = (x + y)*h/2So, A = hr + h√(r^2 – h^2)taking the derivative of this area function with respect to h, (noting that r is a constant since we are given the semicircle of radius r to start with)dA/dh = r + √(r^2 – h^2) – h^2/√(r^2 – h^2)To find the critical points we set the derivative equal to zero and solve for h, we geth = √3/2 * rSo, x = 2 * r & y = r So, A = (3 * √3 * r^2)/4 Below is the implementation of above approach: C++ Java Python 3 C# PHP Javascript // C++ Program to find the biggest trapezoid// which can be inscribed within the semicircle#include <bits/stdc++.h>using namespace std; // Function to find the area// of the biggest trapezoidfloat trapezoidarea(float r){ // the radius cannot be negative if (r < 0) return -1; // area of the trapezoid float a = (3 * sqrt(3) * pow(r, 2)) / 4; return a;} // Driver codeint main(){ float r = 5; cout << trapezoidarea(r) << endl; return 0;} // Java Program to find the biggest trapezoid// which can be inscribed within the semicircle import java.util.*;import java.lang.*;import java.io.*; class GFG{// Function to find the area// of the biggest trapezoidstatic float trapezoidarea(float r){ // the radius cannot be negative if (r < 0) return -1; // area of the trapezoid float a = (3 * (float)Math.sqrt(3) * (float)Math.pow(r, 2)) / 4; return a;} // Driver codepublic static void main(String args[]){ float r = 5; System.out.printf("%.3f",trapezoidarea(r));}} # Python 3 Program to find the biggest trapezoid# which can be inscribed within the semicircle # from math import everythingfrom math import * # Function to find the area# of the biggest trapezoiddef trapezoidarea(r) : # the radius cannot be negative if r < 0 : return -1 # area of the trapezoid a = (3 * sqrt(3) * pow(r,2)) / 4 return a # Driver code if __name__ == "__main__" : r = 5 print(round(trapezoidarea(r),3)) # This code is contributed by ANKITRAI1 // C# Program to find the biggest// trapezoid which can be inscribed// within the semicircleusing System; class GFG{// Function to find the area// of the biggest trapezoidstatic float trapezoidarea(float r){ // the radius cannot be negative if (r < 0) return -1; // area of the trapezoid float a = (3 * (float)Math.Sqrt(3) * (float)Math.Pow(r, 2)) / 4; return a;} // Driver codepublic static void Main(){ float r = 5; Console.WriteLine("" + trapezoidarea(r));}} // This code is contributed// by inder_verma <?php// PHP Program to find the biggest// trapezoid which can be inscribed// within the semicircle // Function to find the area// of the biggest trapezoidfunction trapezoidarea($r){ // the radius cannot be negative if ($r < 0) return -1; // area of the trapezoid $a = (3 * sqrt(3) * pow($r, 2)) / 4; return $a;} // Driver code$r = 5;echo trapezoidarea($r)."\n"; // This code is contributed// by ChitraNayal?> <script> // javascript Program to find the biggest trapezoid// which can be inscribed within the semicircle // Function to find the area// of the biggest trapezoidfunction trapezoidarea(r){ // the radius cannot be negative if (r < 0) return -1; // area of the trapezoid var a = (3 * Math.sqrt(3) * Math.pow(r, 2)) / 4; return a;} // Driver code var r = 5;document.write(trapezoidarea(r).toFixed(3)); // This code contributed by Princi Singh </script> 32.476 Time complexity: O(1) Auxiliary space: O(1) tufan_gupta2000 ankthon inderDuMCA ukasp princi singh krishnav4 circle school-programming Geometric Mathematical Mathematical Geometric 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, 2022" }, { "code": null, "e": 187, "s": 28, "text": "Given a semicircle of radius r, the task is to find the largest trapezoid that can be inscribed in the semicircle, with base lying on the diameter.Examples: " }, { "c...
Find the smallest positive number missing from an unsorted array | Set 2 - GeeksforGeeks
22 Apr, 2021 Given an unsorted array with both positive and negative elements. Find the smallest positive number missing from the array in O(n) time using constant extra space. It is allowed to modify the original array.Examples: Input: {2, 3, 7, 6, 8, -1, -10, 15} Output: 1 Input: { 2, 3, -7, 6, 8, 1, -10, 15 } Output: 4 Input: {1, 1, 0, -1, -2} Output: 2 We have discussed an O(n) time and O(1) extra space solution in the previous post. In this post, another alternative solution is discussed. We make the value at the index corresponding to the given array element equal to an array element. For example: consider the array = {2, 3, 7, 6, 8, -1, -10, 15}. To mark the presence of element 2 in this array, we make arr[2-1] = 2. In array subscript [2-1], 2 is the element to be marked and 1 is subtracted because we are mapping an element value range [1, N] on index value range [0, N-1]. But if we make arr[1] = 2, we will lose data stored at arr[1]. To avoid this, we first store the value present at arr[1] and then update it. Next, we will mark the presence of element previously present at arr[1], i.e. 3. Clearly this lead to some type of random traversal over the array. Now we have to specify a condition to mark the end of this traversal. There are three conditions that mark the end of this traversal: 1. If the element to be marked is negative: No need to mark the presence of this element as we are interested in finding the first missing positive integer. So if a negative element is found, simply end the traversal as no more marking of the presence of an element is done. 2. If the element to be marked is greater than N: No need to mark the presence of this element because if this element is present then certainly it has taken a place of an element in the range [1, N] in an array of size N and hence ensuring that our answer lies in the range[1, N]. So simply end the traversal as no more marking of the presence of an element is done. 3. If the presence of the current element is already marked: Suppose the element to be marked present is val. If arr[val-1] = val, then we have already marked the presence of this element. So simply end the traversal as no more marking of the presence of an element is done. Also note that it is possible that all the elements of an array in the range [1, N] are not marked present in the current traversal. To ensure that all the elements in the range are marked present, we check each element of the array lying in this range. If the element is not marked, then we start a new traversal beginning from that array element.After we have marked the presence of all array elements lying in the range [1, N], we check which index value ind is not equal to ind+1. If arr[ind] is not equal to ind+1, then ind+1 is the smallest positive missing number. Recall that we are mapping index value range [0, N-1] to element value range [1, N], so 1 is added to ind. If no such ind is found, then all elements in the range [1, N] are present in the array. So the first missing positive number is N+1.How does this solution work in O(n) time? Observe that each element in the range [1, N] is traversed at most twice in the worst case. First while performing a traversal started from some other element in the range. Second when checking if a new traversal is required to be initiated from this element to mark the presence of unmarked elements. In the worst case, each element in the range [1, N] is present in the array and thus all N elements are traversed twice. So total computations are 2*n, and hence the time complexity is O(n).Below is the implementation of above approach: C++ Java Python 3 C# PHP Javascript /* CPP program to find the smallest positive missing number */#include <bits/stdc++.h>using namespace std; // Function to find smallest positive// missing number.int findMissingNo(int arr[], int n){ // to store current array element int val; // to store next array element in // current traversal int nextval; for (int i = 0; i < n; i++) { // if value is negative or greater // than array size, then it cannot // be marked in array. So move to // next element. if (arr[i] <= 0 || arr[i] > n) continue; val = arr[i]; // traverse the array until we // reach at an element which // is already marked or which // could not be marked. while (arr[val - 1] != val) { nextval = arr[val - 1]; arr[val - 1] = val; val = nextval; if (val <= 0 || val > n) break; } } // find first array index which is // not marked which is also the // smallest positive missing // number. for (int i = 0; i < n; i++) { if (arr[i] != i + 1) { return i + 1; } } // if all indices are marked, then // smallest missing positive // number is array_size + 1. return n + 1;} // Driver codeint main(){ int arr[] = { 2, 3, 7, 6, 8, -1, -10, 15 }; int arr_size = sizeof(arr) / sizeof(arr[0]); int missing = findMissingNo(arr, arr_size); cout << "The smallest positive missing number is " << missing; return 0;} /* Java program to find the smallestpositive missing number */import java.io.*; class GFG { // Function to find smallest positive // missing number. static int findMissingNo(int []arr, int n) { // to store current array element int val; // to store next array element in // current traversal int nextval; for (int i = 0; i < n; i++) { // if value is negative or greater // than array size, then it cannot // be marked in array. So move to // next element. if (arr[i] <= 0 || arr[i] > n) continue; val = arr[i]; // traverse the array until we // reach at an element which // is already marked or which // could not be marked. while (arr[val - 1] != val) { nextval = arr[val - 1]; arr[val - 1] = val; val = nextval; if (val <= 0 || val > n) break; } } // find first array index which is // not marked which is also the // smallest positive missing // number. for (int i = 0; i < n; i++) { if (arr[i] != i + 1) { return i + 1; } } // if all indices are marked, then // smallest missing positive // number is array_size + 1. return n + 1; } // Driver code public static void main (String[] args) { int arr[] = { 2, 3, 7, 6, 8, -1, -10, 15 }; int arr_size = arr.length; int missing = findMissingNo(arr, arr_size); System.out.println( "The smallest positive" + " missing number is " + missing); }} // This code is contributed by anuj_67. # Python 3 program to find the smallest# positive missing number # Function to find smallest positive# missing number.def findMissingNo(arr, n): # to store current array element # to store next array element in # current traversal for i in range(n) : # if value is negative or greater # than array size, then it cannot # be marked in array. So move to # next element. if (arr[i] <= 0 or arr[i] > n): continue val = arr[i] # traverse the array until we # reach at an element which # is already marked or which # could not be marked. while (arr[val - 1] != val): nextval = arr[val - 1] arr[val - 1] = val val = nextval if (val <= 0 or val > n): break # find first array index which is # not marked which is also the # smallest positive missing # number. for i in range(n): if (arr[i] != i + 1) : return i + 1 # if all indices are marked, then # smallest missing positive # number is array_size + 1. return n + 1 # Driver codeif __name__ == "__main__": arr = [ 2, 3, 7, 6, 8, -1, -10, 15 ] arr_size = len(arr) missing = findMissingNo(arr, arr_size) print( "The smallest positive", "missing number is ", missing) # This code is contributed# by ChitraNayal /* C# program to find the smallestpositive missing number */using System; class GFG{ // Function to find smallest // positive missing number. static int findMissingNo(int []arr, int n) { // to store current // array element int val; // to store next array element // in current traversal int nextval; for (int i = 0; i < n; i++) { // if value is negative or greater // than array size, then it cannot // be marked in array. So move to // next element. if (arr[i] <= 0 || arr[i] > n) continue; val = arr[i]; // traverse the array until we // reach at an element which // is already marked or which // could not be marked. while (arr[val - 1] != val) { nextval = arr[val - 1]; arr[val - 1] = val; val = nextval; if (val <= 0 || val > n) break; } } // find first array index which // is not marked which is also // the smallest positive missing // number. for (int i = 0; i < n; i++) { if (arr[i] != i + 1) { return i + 1; } } // if all indices are marked, // then smallest missing // positive number is // array_size + 1. return n + 1; } // Driver code public static void Main (String[] args) { int []arr = {2, 3, 7, 6, 8, -1, -10, 15}; int arr_size = arr.Length; int missing = findMissingNo(arr, arr_size); Console.Write("The smallest positive" + " missing number is " + missing); }} // This code is contributed// by shiv_bhakt. <?php// PHP program to find// the smallest positive// missing number // Function to find smallest// positive missing number.function findMissingNo($arr, $n){ // to store current // array element $val; // to store next array element // in current traversal $nextval; for ($i = 0; $i < $n; $i++) { // if value is negative or // greater than array size, // then it cannot be marked // in array. So move to // next element. if ($arr[$i] <= 0 || $arr[$i] > $n) continue; $val = $arr[$i]; // traverse the array until // we reach at an element // which is already marked // or which could not be marked. while ($arr[$val - 1] != $val) { $nextval = $arr[$val - 1]; $arr[$val - 1] = $val; $val = $nextval; if ($val <= 0 || $val > $n) break; } } // find first array index // which is not marked // which is also the smallest // positive missing number. for ($i = 0; $i < $n; $i++) { if ($arr[$i] != $i + 1) { return $i + 1; } } // if all indices are marked, // then smallest missing // positive number is // array_size + 1. return $n + 1;} // Driver code$arr = array(2, 3, 7, 6, 8, -1, -10, 15);$arr_size = sizeof($arr) / sizeof($arr[0]);$missing = findMissingNo($arr, $arr_size);echo "The smallest positive " . "missing number is " , $missing; // This code is contributed// by shiv_bhakt.?> <script> /* Javascript program to find the smallest positive missing number */ // Function to find smallest positive// missing number.function findMissingNo(arr, n){ // to store current array element var val; // to store next array element in // current traversal var nextval; for (var i = 0; i < n; i++) { // if value is negative or greater // than array size, then it cannot // be marked in array. So move to // next element. if (arr[i] <= 0 || arr[i] > n) continue; val = arr[i]; // traverse the array until we // reach at an element which // is already marked or which // could not be marked. while (arr[val - 1] != val) { nextval = arr[val - 1]; arr[val - 1] = val; val = nextval; if (val <= 0 || val > n) break; } } // find first array index which is // not marked which is also the // smallest positive missing // number. for (var i = 0; i < n; i++) { if (arr[i] != i + 1) { return i + 1; } } // if all indices are marked, then // smallest missing positive // number is array_size + 1. return n + 1;} // Driver codevar arr = [ 2, 3, 7, 6, 8, -1, -10, 15 ];var arr_size = arr.length;var missing = findMissingNo(arr, arr_size);document.write( "The smallest positive missing number is " + missing); </script> The smallest positive missing number is 1 Time Complexity: O(n) Auxiliary Space: O(1) vt_m Vishal_Khoda ukasp noob2000 Arrays Searching Arrays Searching 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 Binary Search Maximum and minimum of an array using minimum number of comparisons Linear Search Search an element in a sorted and rotated array Find the Missing Number
[ { "code": null, "e": 26705, "s": 26677, "text": "\n22 Apr, 2021" }, { "code": null, "e": 26924, "s": 26705, "text": "Given an unsorted array with both positive and negative elements. Find the smallest positive number missing from the array in O(n) time using constant extra space....
Centered hexagonal number - GeeksforGeeks
13 Jul, 2021 Given a number N and the task is to find Nth centered hexagonal number. Also, find the Centered hexagonal series.Examples: Input: N = 2 Output: 7Input: N = 10 Output: 271 Centered Hexagonal Numbers – The Centered Hexagonal numbers are figurate numbers and are in the form of the Hexagon. The Centered Hexagonal number is different from Hexagonal Number because it contains one element at the center.Some of the Central Hexagonal numbers are – 1, 7, 19, 37, 61, 91, 127, 169 ... For Example: The First N numbers are - 1, 7, 19, 37, 61, 91, 127 ... The cumulative sum of these numbers are - 1, 1+7, 1+7+19, 1+7+19+37... which is nothing but the sequence - 1, 8, 27, 64, 125, 216 ... That is in the form of - 13, 23, 33, 43, 53, 63 .... As Central Hexagonal numbers sum up to Nth term will be the N3. That is – 13 + 23 + 33 + 43 + 53 + 63 .... upto N terms = N3Then, Nth term will be – => N3 – (N – 1)3 => 3*N*(N – 1) + 1 Approach: For finding the Nth term of the Centered Hexagonal Number use the formulae – 3*N*(N – 1) + 1.Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // Program to find nth// centered hexadecimal number.#include <bits/stdc++.h>using namespace std; // Function to find centered// hexadecimal number.int centeredHexagonalNumber(int n){ // Formula to calculate nth // centered hexadecimal number // and return it into main function. return 3 * n * (n - 1) + 1;} // Driver Codeint main(){ int n = 10; cout << n << "th centered hexagonal number: "; cout << centeredHexagonalNumber(n); return 0;} // Java Program to find nth// centered hexadecimal numberimport java.io.*; class GFG{ // Function to find centered // hexadecimal number static int centeredHexagonalNumber(int n) { // Formula to calculate nth // centered hexadecimal number // and return it into main function return 3 * n * (n - 1) + 1; } // Driver Code public static void main(String args[]) { int n = 10; System.out.print(n + "th centered " + "hexagonal number: "); System.out.println(centeredHexagonalNumber(n)); }} // This code is contributed by Nikita Tiwari. # Python 3 program to find nth# centered hexagonal number # Function to find# centered hexagonal numberdef centeredHexagonalNumber(n) : # Formula to calculate # nth centered hexagonal return 3 * n * (n - 1) + 1 # Driver Codeif __name__ == '__main__' : n = 10 print(n, "th centered hexagonal number: " , centeredHexagonalNumber(n)) # This code is contributed# by 'Akanshgupta' // C# Program to find nth// centered hexadecimal numberusing System; class GFG{ // Function to find centered // hexadecimal number static int centeredHexagonalNumber(int n) { // Formula to calculate nth // centered hexadecimal number // and return it into main function return 3 * n * (n - 1) + 1; } // Driver Code public static void Main() { int n = 10; Console.Write(n + "th centered "+ "hexagonal number: "); Console.Write(centeredHexagonalNumber(n)); }} // This code is contributed by vt_m. <?php// PHP Program to find nth// centered hexadecimal number. // Function to find centered// hexadecimal number.function centeredHexagonalNumber( $n){ // Formula to calculate nth // centered hexadecimal // number and return it // into main function. return 3 * $n * ($n - 1) + 1;} // Driver Code $n = 10; echo $n , "th centered hexagonal number: "; echo centeredHexagonalNumber($n); // This code is contributed by anuj_67.?> <script> // Program to find nth// centered hexadecimal number. // Function to find centered// hexadecimal number.function centeredHexagonalNumber(n){ // Formula to calculate nth // centered hexadecimal number // and return it into main function. return 3 * n * (n - 1) + 1;} // Driver Codelet n = 10;document.write(n + "th centered hexagonal number: ");document.write(centeredHexagonalNumber(n)); // This code is contributed by rishavmahato348. </script> Output : 10th centered hexagonal number: 271 Performance Analysis: Time Complexity: In the above given approach we are finding the Nth term of the Centered Hexagonal Number which takes constant time. Therefore, the complexity will be O(1) Space Complexity: In the above given approach, we are not using any other auxiliary space for the computation. Therefore, the space complexity will be O(1). Given a number N, the task is to find centered hexagonal series till N.Approach: Iterate the loop using a loop variable (say i) and find the each ith term of the Centered Hexagonal Number using the formulae – 3*i*(i – 1) + 1Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // Program to find the series// of centered hexadecimal number#include <bits/stdc++.h>using namespace std; // Function to find the// series of centered// hexadecimal number.void centeredHexagonalSeries(int n){ // Formula to calculate // nth centered hexadecimal // number. for (int i = 1; i <= n; i++) cout << 3 * i * (i - 1) + 1 << " ";} // Driver Codeint main(){ int n = 10; centeredHexagonalSeries(n); return 0;} // Program to find the series of// centered hexadecimal number.import java.io.*; class GFG{ // Function to find the series of // centered hexadecimal number. static void centeredHexagonalSeries(int n) { // Formula to calculate nth // centered hexadecimal number. for (int i = 1; i <= n; i++) System.out.print( 3 * i * (i - 1) + 1 + " "); } // Driver Code public static void main(String args[]) { int n = 10; centeredHexagonalSeries(n); }} // This code is contributed by Nikita Tiwari. # Python3 program to find# nth centered hexagonal number # Function to find centered hexagonal# series till n given numbers.def centeredHexagonalSeries(n) : for i in range(1, n + 1) : # Formula to calculate nth # centered hexagonal series. print(3 * i * (i - 1) + 1, end=" ") # Driver Codeif __name__ == '__main__' : n = 10 centeredHexagonalSeries(n) # This code is contributed# by 'Akanshgupta' // C# Program to find the// series of centered// hexadecimal number.using System; class GFG{ // Function to find the // series of centered // hexadecimal number. static void centeredHexagonalSeries(int n) { // Formula to calculate nth // centered hexadecimal number. for (int i = 1; i <= n; i++) Console.Write( 3 * i * (i - 1) + 1 + " "); } // Driver Code public static void Main() { int n = 10; centeredHexagonalSeries(n); }} // This code is contributed by vt_m. <?php// Program to find the// series of centered// hexadecimal number. // Function to find the// series of centered// hexadecimal number.function centeredHexagonalSeries( $n){ // Formula to calculate // nth centered hexadecimal // number. for ( $i = 1; $i <= $n; $i++) echo 3 * $i * ($i - 1) + 1 ," ";} // Driver Code$n = 10;centeredHexagonalSeries($n); // This code is contributed by anuj_67.?> <script> // JavaScript program to find the series of// centered hexadecimal number. // Function to find the series of // centered hexadecimal number. function centeredHexagonalSeries(n) { // Formula to calculate nth // centered hexadecimal number. for (let i = 1; i <= n; i++) document.write( 3 * i * (i - 1) + 1 + " "); } // Driver code let n = 10; centeredHexagonalSeries(n); </script> Output : 1 7 19 37 61 91 127 169 217 271 Time Complexity: O(n)Auxiliary Space: O(1) vt_m Archit_Dwevedi0 nidhi_biet rishavmahato348 susmitakundugoaldanga manikarora059 series Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Sieve of Eratosthenes Print all possible combinations of r elements in a given array of size n Operators in C / C++ The Knight's tour problem | Backtracking-1 Program for factorial of a number Program for Decimal to Binary Conversion
[ { "code": null, "e": 26469, "s": 26441, "text": "\n13 Jul, 2021" }, { "code": null, "e": 26594, "s": 26469, "text": "Given a number N and the task is to find Nth centered hexagonal number. Also, find the Centered hexagonal series.Examples: " }, { "code": null, "e": 2...
Tracing memory usage in Linux - GeeksforGeeks
26 Sep, 2017 Often it’s necessary to trace memory usage of the system in order to determine the program that consumes all CPU resources or the program that is responsible to slowing down the activities of the CPU. Tracing memory usage also becomes necessary to determine the load on the server. Parsing the usage data enables the servers to be able to balance the load and serve the user’s request without slowing down the system. free Displays the amount of memory which is currently available and used by the system(both physical and swapped). free command gathers this data by parsing /proc/meminfo. By default, the amount of memory is display in kilobytes.free command in UNIXwatch -n 5 free -m watch command is used to execute a program periodically.According to the image above, there is a total of 2000 MB of RAM and 1196 MB of swap space allotted to Linux system. Out of this 2000 MB of RAM, 834 MB is currently used where as 590 MB is free. Similarly for swap space, out of 1196 MB, 0 MB is use and 1196 MB is free currently in the system.vmstat vmstat command is used to display virtual memory statistics of the system. This command reports data about the memory, paging, disk and CPU activities, etc. The first use of this command returns the data averages since the last reboot. Further uses returns the data based on sampling periods of length delays.vmstat -d Reports disk statisticsvmstat -s Displays the amount of memory used and availabletop top command displays all the currently running process in the system. This command displays the list of processes and thread currently being handled by the kernel. top command can also be used to monitor the total amount of memory usage. top -H Threads-mode operation Displays individual thread that are currently in the system. Without this command option, a summation of all thread in each process is displayed./proc/meminfo This file contains all the data about the memory usage. It provides the current memory usage details rather than old stored values.htop htop is an interactive process viewer. This command is similar to top command except that it allows to scroll vertically and horizontally to allows users to view all processes running on the system, along with their full command line as well as viewing them as a process tree, selecting multiple processes and acting on them all at once.working of htop command in UNIX: free Displays the amount of memory which is currently available and used by the system(both physical and swapped). free command gathers this data by parsing /proc/meminfo. By default, the amount of memory is display in kilobytes.free command in UNIXwatch -n 5 free -m watch command is used to execute a program periodically.According to the image above, there is a total of 2000 MB of RAM and 1196 MB of swap space allotted to Linux system. Out of this 2000 MB of RAM, 834 MB is currently used where as 590 MB is free. Similarly for swap space, out of 1196 MB, 0 MB is use and 1196 MB is free currently in the system. free command in UNIX watch -n 5 free -m watch command is used to execute a program periodically. According to the image above, there is a total of 2000 MB of RAM and 1196 MB of swap space allotted to Linux system. Out of this 2000 MB of RAM, 834 MB is currently used where as 590 MB is free. Similarly for swap space, out of 1196 MB, 0 MB is use and 1196 MB is free currently in the system. vmstat vmstat command is used to display virtual memory statistics of the system. This command reports data about the memory, paging, disk and CPU activities, etc. The first use of this command returns the data averages since the last reboot. Further uses returns the data based on sampling periods of length delays.vmstat -d Reports disk statisticsvmstat -s Displays the amount of memory used and available vmstat -d Reports disk statistics vmstat -s Displays the amount of memory used and available top top command displays all the currently running process in the system. This command displays the list of processes and thread currently being handled by the kernel. top command can also be used to monitor the total amount of memory usage. top -H Threads-mode operation Displays individual thread that are currently in the system. Without this command option, a summation of all thread in each process is displayed. top -H Threads-mode operation Displays individual thread that are currently in the system. Without this command option, a summation of all thread in each process is displayed. /proc/meminfo This file contains all the data about the memory usage. It provides the current memory usage details rather than old stored values. htop htop is an interactive process viewer. This command is similar to top command except that it allows to scroll vertically and horizontally to allows users to view all processes running on the system, along with their full command line as well as viewing them as a process tree, selecting multiple processes and acting on them all at once.working of htop command in UNIX: working of htop command in UNIX: Reference: Ubuntu Manual 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 contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. linux-command Linux-Unix Operating Systems Operating Systems 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 Types of Operating Systems Banker's Algorithm in Operating System Page Replacement Algorithms in Operating Systems Program for FCFS CPU Scheduling | Set 1 Paging in Operating System
[ { "code": null, "e": 25677, "s": 25649, "text": "\n26 Sep, 2017" }, { "code": null, "e": 26095, "s": 25677, "text": "Often it’s necessary to trace memory usage of the system in order to determine the program that consumes all CPU resources or the program that is responsible to sl...
XNOR of two numbers - GeeksforGeeks
28 Apr, 2021 XNOR gives the reverse of XOR if binary bit. First bit | Second bit | XNOR 0 0 1 0 1 0 1 0 0 1 1 1 It gives 1 if bits are same else if bits are different it gives 0. It is reverse of XOR but we can’t implement it directly so this is the program for implement XNOR Examples: Input : 10 20 Output : 1 Binary of 20 is 10100 Binary of 10 is 1010 So the XNOR is 00001 So output is 1 Input : 10 10 Output : 15 Binary of 10 is 1010 Binary of 10 is 1010 So the XNOR is 1111 So output is 15 First Method:- (O(logn)) In this solution we check one bit at a time. If two bits are same, we put 1 in result, else we put 0.Let’s understand it with below code C++ Java Python3 C# PHP Javascript // CPP program to find// XNOR of two numbers#include <iostream>using namespace std; // log(n) solutionint xnor(int a, int b){ // Make sure a is larger if (a < b) swap(a, b); if (a == 0 && b == 0) return 1; int a_rem = 0; // for last bit of a int b_rem = 0; // for last bit of b // counter for count bit // and set bit in xnornum int count = 0; // to make new xnor number int xnornum = 0; // for set bits in new xnor number while (a) { // get last bit of a a_rem = a & 1; // get last bit of b b_rem = b & 1; // Check if current two // bits are same if (a_rem == b_rem) xnornum |= (1 << count); // counter for count bit count++; a = a >> 1; b = b >> 1; } return xnornum;} // Driver codeint main(){ int a = 10, b = 50; cout << xnor(a, b); return 0;} // Java program to find// XNOR of two numbersimport java.util.*;import java.lang.*; public class GfG { public static int xnor(int a, int b) { // Make sure a is larger if (a < b) { // swapping a and b; int t = a; a = b; b = t; } if (a == 0 && b == 0) return 1; // for last bit of a int a_rem = 0; // for last bit of b int b_rem = 0; // counter for count bit // and set bit in xnornum int count = 0; // to make new xnor number int xnornum = 0; // for set bits in new xnor number while (true) { // get last bit of a a_rem = a & 1; // get last bit of b b_rem = b & 1; // Check if current two bits are same if (a_rem == b_rem) xnornum |= (1 << count); // counter for count bit count++; a = a >> 1; b = b >> 1; if (a < 1) break; } return xnornum; } // Driver function public static void main(String argc[]) { int a = 10, b = 50; System.out.println(xnor(a, b)); }} # Python3 program to find XNOR# of two numbersimport math def swap(a,b): temp=a a=b b=temp # log(n) solutiondef xnor(a, b): # Make sure a is larger if (a < b): swap(a, b) if (a == 0 and b == 0) : return 1; # for last bit of a a_rem = 0 # for last bit of b b_rem = 0 # counter for count bit and # set bit in xnor num count = 0 # for make new xnor number xnornum = 0 # for set bits in new xnor # number while (a!=0) : # get last bit of a a_rem = a & 1 # get last bit of b b_rem = b & 1 # Check if current two # bits are same if (a_rem == b_rem): xnornum |= (1 << count) # counter for count bit count=count+1 a = a >> 1 b = b >> 1 return xnornum; # Driver methoda = 10b = 50print(xnor(a, b)) # This code is contributed by Gitanjali // C# program to find// XNOR of two numbersusing System; public class GfG { public static int xnor(int a, int b) { // Make sure a is larger if (a < b) { // swapping a and b; int t = a; a = b; b = t; } if (a == 0 && b == 0) return 1; // for last bit of a int a_rem = 0; // for last bit of b int b_rem = 0; // counter for count bit // and set bit in xnornum int count = 0; // to make new xnor number int xnornum = 0; // for set bits in new xnor number while (true) { // get last bit of a a_rem = a & 1; // get last bit of b b_rem = b & 1; // Check if current two bits are same if (a_rem == b_rem) xnornum |= (1 << count); // counter for count bit count++; a = a >> 1; b = b >> 1; if (a < 1) break; } return xnornum; } // Driver function public static void Main() { int a = 10, b = 50; Console.WriteLine(xnor(a, b)); }} // This code is contributed by vt_m <?php// PHP program to find// XNOR of two numbers // log(n) solutionfunction xnor($a, $b){ // Make sure a is larger if ($a < $b) list($a, $b) = array($b, $a); if ($a == 0 && $b == 0) return 1; // for last bit of a $a_rem = 0; // for last bit of b $b_rem = 0; // counter for count bit // and set bit in xnornum $count = 0; // to make new xnor number $xnornum = 0; // for set bits in // new xnor number while ($a) { // get last bit of a $a_rem = $a & 1; // get last bit of b $b_rem = $b & 1; // Check if current two // bits are same if ($a_rem == $b_rem) $xnornum |= (1 << $count); // counter for count bit $count++; $a = $a >> 1; $b = $b >> 1; } return $xnornum;} // Driver code $a = 10; $b = 50; echo xnor($a, $b); // This code is contributed by mits. ?> <script> // javascript program to find// XNOR of two numbers function xnor(a, b) { // Make sure a is larger if (a < b) { // swapping a and b; let t = a; a = b; b = t; } if (a == 0 && b == 0) return 1; // for last bit of a let a_rem = 0; // for last bit of b let b_rem = 0; // counter for count bit // and set bit in xnornum let count = 0; // to make new xnor number let xnornum = 0; // for set bits in new xnor number while (true) { // get last bit of a a_rem = a & 1; // get last bit of b b_rem = b & 1; // Check if current two bits are same if (a_rem == b_rem) xnornum |= (1 << count); // counter for count bit count++; a = a >> 1; b = b >> 1; if (a < 1) break; } return xnornum; } // Driver Function let a = 10, b = 50; document.write(xnor(a, b)); // This code is contributed by susmitakundugoaldanga.</script> Output: 7 Second Method:- O(1) 1) Find maximum of two given numbers. 2) Toggle all bits in higher of two numbers. 3) Return XOR of original smaller number and modified larger number. C++ Java Python C# PHP Javascript // CPP program to find XNOR of two numbers.#include <iostream>using namespace std; // Please refer below post for details of this// function// https://www.geeksforgeeks.org/toggle-bits-significant-bit/int togglebit(int n){ if (n == 0) return 1; // Make a copy of n as we are // going to change it. int i = n; // Below steps set bits after // MSB (including MSB) // Suppose n is 273 (binary // is 100010001). It does following // 100010001 | 010001000 = 110011001 n |= n >> 1; // This makes sure 4 bits // (From MSB and including MSB) // are set. It does following // 110011001 | 001100110 = 111111111 n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; return i ^ n;} // Returns XNOR of num1 and num2int XNOR(int num1, int num2){ // if num2 is greater then // we swap this number in num1 if (num1 < num2) swap(num1, num2); num1 = togglebit(num1); return num1 ^ num2;} // Driver codeint main(){ int num1 = 10, num2 = 20; cout << XNOR(num1, num2); return 0;} // Java program to find XNOR// of two numbersimport java.io.*; class GFG { // Please refer below post for // details of this function // https://www.geeksforgeeks.org/toggle-bits-significant-bit/ static int togglebit(int n) { if (n == 0) return 1; // Make a copy of n as we are // going to change it. int i = n; // Below steps set bits after // MSB (including MSB) // Suppose n is 273 (binary // is 100010001). It does following // 100010001 | 010001000 = 110011001 n |= n >> 1; // This makes sure 4 bits // (From MSB and including MSB) // are set. It does following // 110011001 | 001100110 = 111111111 n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; return i ^ n; } // Returns XNOR of num1 and num2 static int xnor(int num1, int num2) { // if num2 is greater then // we swap this number in num1 if (num1 < num2) { int temp = num1; num1 = num2; num2 = temp; } num1 = togglebit(num1); return num1 ^ num2; } /* Driver program to test above function */ public static void main(String[] args) { int a = 10, b = 20; System.out.println(xnor(a, b)); }} // This code is contributed by Gitanjali # python program to find XNOR of two numbersimport math # Please refer below post for details of this function# https://www.geeksforgeeks.org/toggle-bits-significant-bit/def togglebit( n): if (n == 0): return 1 # Make a copy of n as we are # going to change it. i = n # Below steps set bits after # MSB (including MSB) # Suppose n is 273 (binary # is 100010001). It does following # 100010001 | 010001000 = 110011001 n = n|(n >> 1) # This makes sure 4 bits # (From MSB and including MSB) # are set. It does following # 110011001 | 001100110 = 111111111 n |= n >> 2 n |= n >> 4 n |= n >> 8 n |= n >> 16 return i ^ n # Returns XNOR of num1 and num2def xnor( num1, num2): # Make sure num1 is larger if (num1 < num2): temp = num1 num1 = num2 num2 = temp num1 = togglebit(num1) return num1 ^ num2 # Driver codea = 10b = 20print (xnor(a, b)) # This code is contributed by 'Gitanjali'. // C# program to find XNOR// of two numbersusing System; class GFG { // Please refer below post for // details of this function // https://www.geeksforgeeks.org/toggle-bits-significant-bit/ static int togglebit(int n) { if (n == 0) return 1; // Make a copy of n as we are // going to change it. int i = n; // Below steps set bits after // MSB (including MSB) // Suppose n is 273 (binary // is 100010001). It does following // 100010001 | 010001000 = 110011001 n |= n >> 1; // This makes sure 4 bits // (From MSB and including MSB) // are set. It does following // 110011001 | 001100110 = 111111111 n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; return i ^ n; } // Returns XNOR of num1 and num2 static int xnor(int num1, int num2) { // if num2 is greater then // we swap this number in num1 if (num1 < num2) { int temp = num1; num1 = num2; num2 = temp; } num1 = togglebit(num1); return num1 ^ num2; } // Driver program public static void Main() { int a = 10, b = 20; Console.WriteLine(xnor(a, b)); }} // This code is contributed by vt_m <?php// PHP program to find XNOR// of two numbers. // Please refer below post// for details of this function// https://www.geeksforgeeks.org/toggle-bits-significant-bit/ function togglebit($n){ if ($n == 0) return 1; // Make a copy of n as we are // going to change it. $i = $n; // Below steps set bits after // MSB (including MSB) // Suppose n is 273 (binary // is 100010001). It does following // 100010001 | 010001000 = 110011001 $n |= $n >> 1; // This makes sure 4 bits // (From MSB and including MSB) // are set. It does following // 110011001 | 001100110 = 111111111 $n |= $n >> 2; $n |= $n >> 4; $n |= $n >> 8; $n |= $n >> 16; return $i ^ $n;} // Returns XNOR of num1 and num2function XNOR($num1, $num2){ // if num2 is greater then // we swap this number in num1 if ($num1 < $num2) list($num1, $num2)=array($num2, $num1); $num1 = togglebit($num1); return $num1 ^ $num2;} // Driver code$num1 = 10;$num2 = 20;echo XNOR($num1, $num2); // This code is contributed by Smitha.?> <script>// Javascript program to find XNOR of two numbers. // Please refer below post for details of this// function// https://www.geeksforgeeks.org/toggle-bits-significant-bit/function togglebit(n){ if (n == 0) return 1; // Make a copy of n as we are // going to change it. let i = n; // Below steps set bits after // MSB (including MSB) // Suppose n is 273 (binary // is 100010001). It does following // 100010001 | 010001000 = 110011001 n |= n >> 1; // This makes sure 4 bits // (From MSB and including MSB) // are set. It does following // 110011001 | 001100110 = 111111111 n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; return i ^ n;} // Returns XNOR of num1 and num2function XNOR(num1, num2){ // if num2 is greater then // we swap this number in num1 if (num1 < num2) { let temp = num1; num1 = num2; num2 = temp; } num1 = togglebit(num1); return num1 ^ num2;} // Driver code let num1 = 10, num2 = 20; document.write(XNOR(num1, num2)); </script> Output : 1 Mithun Kumar Smitha Dinesh Semwal susmitakundugoaldanga souravmahato348 Bitwise-XOR Bit Magic Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Little and Big Endian Mystery Cyclic Redundancy Check and Modulo-2 Division Binary representation of a given number Program to find whether a given number is power of 2 Add two numbers without using arithmetic operators Set, Clear and Toggle a given bit of a number in C Josephus problem | Set 1 (A O(n) Solution) Bit Fields in C Find the element that appears once C++ bitset and its application
[ { "code": null, "e": 26257, "s": 26229, "text": "\n28 Apr, 2021" }, { "code": null, "e": 26304, "s": 26257, "text": "XNOR gives the reverse of XOR if binary bit. " }, { "code": null, "e": 26517, "s": 26304, "text": "First bit | Second bit | XNOR \n0 ...
Brahmagupta Fibonacci Identity - GeeksforGeeks
01 Jul, 2021 Brahmagupta Fibonacci identity states that the product of two numbers each of which is a sum of 2 squares can be represented as sum of 2 squares in 2 different forms.Mathematically, If a = p^2 + q^2 and b = r^2 + s^2 then a * b can be written in two different forms: = (p^2 + q^2) * (r^2 + s^2) = (pr – qs)^2 + (ps + qr)^2 ............(1) = (pr + qs)^2 + (ps – qr)^2 ............(2) Some Examples are: a = 5(= 1^2 + 2^2) b = 25(= 3^2 + 4^2) a*b = 125 Representation of a * b as sum of 2 squares: 2^2 + 11^2 = 125 5^2 + 10^2 = 125 em>Explanations: a = 5 and b = 25 each can be expressed as a sum of 2 squares and their product a*b which is 125 can be expressed as sum of 2 squares in two different forms. This is according to the Brahmagupta Fibonacci Identity and satisfies the identity condition.a = 13(= 2^2 + 3^2) b = 41(= 4^2 + 5^2) a*b = 533 Representation of a * b as sum of 2 squares: 2^2 + 23^2 = 533 7^2 + 22^2 = 533a = 85(= 6^2 + 7^2) b = 41(= 4^2 + 5^2) a*b = 3485 Representation of a * b as sum of 2 squares: 2^2 + 59^2 = 3485 11^2 + 58^2 = 3485 26^2 + 53^2 = 3485 37^2 + 46^2 = 3485 Below is a program to verify Brahmagupta Fibonacci identity for given two numbers which are sums of two squares. C++ Java Python 3 C# PHP Javascript // CPP code to verify// Brahmagupta Fibonacci identity#include <bits/stdc++.h>using namespace std; void find_sum_of_two_squares(int a, int b){ int ab = a*b; // represent the product // as sum of 2 squares for (int i = 0; i * i <= ab; i++) { for (int j = i; i * i + j * j <= ab; j++) { // check identity criteria if (i * i + j * j == ab) cout << i << "^2 + " << j << "^2 = " << ab << "\n"; } }} // Driver codeint main(){ // 1^2 + 2^2 int a = 1 * 1 + 2 * 2; // 3^2 + 4^2 int b = 3 * 3 + 4 * 4; cout << "Representation of a * b as sum" " of 2 squares:\n"; // express product of sum of 2 squares // as sum of (sum of 2 squares) find_sum_of_two_squares(a, b);} // Java code to verify Brahmagupta// Fibonacci identity class GFG{ static void find_sum_of_two_squares(int a, int b){ int ab = a * b; // represent the product // as sum of 2 squares for (int i = 0; i * i <= ab; i++) { for (int j = i; i * i + j * j <= ab; j++) { // check identity criteria if (i * i + j * j == ab) System.out.println(i + "^2 + " + j +"^2 = " + ab); } }} // Driver codepublic static void main(String[] args){ // 1^2 + 2^2 int a = 1 * 1 + 2 * 2; // 3^2 + 4^2 int b = 3 * 3 + 4 * 4; System.out.println("Representation of a * b " + "as sum of 2 squares:"); // express product of sum // of 2 squares as sum of // (sum of 2 squares) find_sum_of_two_squares(a, b);}} // This code is contributed// by Smitha Dinesh Semwal # Python 3 code to verify# Brahmagupta Fibonacci identity def find_sum_of_two_squares(a, b): ab = a * b # represent the product # as sum of 2 squares i=0; while(i * i <= ab): j = i while(i * i + j * j <= ab): # check identity criteria if (i * i + j * j == ab): print(i,"^2 + ",j,"^2 = ",ab) j += 1 i += 1 # Driver codea = 1 * 1 + 2 * 2 # 1^2 + 2^2b = 3 * 3 + 4 * 4 # 3^2 + 4^2 print("Representation of a * b as sum" " of 2 squares:") # express product of sum of 2 squares# as sum of (sum of 2 squares)find_sum_of_two_squares(a, b) # This code is contributed by# Smitha Dinesh Semwal // C# code to verify Brahmagupta// Fibonacci identityusing System; class GFG{ static void find_sum_of_two_squares(int a, int b) { int ab = a * b; // represent the product // as sum of 2 squares for (int i = 0; i * i <= ab; i++) { for (int j = i; i * i + j * j <= ab; j++) { // check identity criteria if (i * i + j * j == ab) Console.Write(i + "^2 + " + j + "^2 = " + ab + "\n"); } }} // Driver codepublic static void Main(){ // 1^2 + 2^2 int a = 1 * 1 + 2 * 2; // 3^2 + 4^2 int b = 3 * 3 + 4 * 4; Console.Write("Representation of a * b " + "as sum of 2 squares:\n"); // express product of sum of // 2 squares as sum of (sum of // 2 squares) find_sum_of_two_squares(a, b);}} // This code is contributed// by Smitha Dinesh Semwal <?php// PHP code to verify// Brahmagupta Fibonacci identity function find_sum_of_two_squares($a, $b){ $ab = $a * $b; // represent the product // as sum of 2 squares for ($i = 0; $i * $i <= $ab; $i++) { for ($j = $i; $i * $i + $j * $j <= $ab; $j++) { // check identity criteria if ($i * $i + $j * $j == $ab) echo $i ,"^2 + ", $j , "^2 = " , $ab ,"\n"; } }} // Driver code// 1^2 + 2^2$a = 1 * 1 + 2 * 2; // 3^2 + 4^2$b = 3 * 3 + 4 * 4; echo "Representation of a * b ". "as sum of 2 squares:\n"; // express product of sum of// 2 squares as sum of (sum// of 2 squares)find_sum_of_two_squares($a, $b); // This code is contributed by aj_36?> <script> // JavaScript program to verify Brahmagupta// Fibonacci identity function find_sum_of_two_squares(a, b){ let ab = a * b; // represent the product // as sum of 2 squares for (let i = 0; i * i <= ab; i++) { for (let j = i; i * i + j * j <= ab; j++) { // check identity criteria if (i * i + j * j == ab) document.write(i + "^2 + " + j +"^2 = " + ab + "<br/>"); } }} // Driver code // 1^2 + 2^2 let a = 1 * 1 + 2 * 2; // 3^2 + 4^2 let b = 3 * 3 + 4 * 4; document.write("Representation of a * b " + "as sum of 2 squares:" + "<br/>"); // express product of sum // of 2 squares as sum of // (sum of 2 squares) find_sum_of_two_squares(a, b); // This code is contributed by code_hunt.</script> Representation of a * b as sum of 2 squares: 2^2 + 11^2 = 125 5^2 + 10^2 = 125 Smitha Dinesh Semwal jit_t code_hunt abhishek0719kadiyan number-theory Mathematical number-theory Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Count all possible paths from top left to bottom right of a mXn matrix Modular multiplicative inverse Fizz Buzz Implementation Program to multiply two matrices Check if a number is Palindrome Count ways to reach the n'th stair Merge two sorted arrays with O(1) extra space Generate all permutation of a set in Python
[ { "code": null, "e": 25961, "s": 25933, "text": "\n01 Jul, 2021" }, { "code": null, "e": 26145, "s": 25961, "text": "Brahmagupta Fibonacci identity states that the product of two numbers each of which is a sum of 2 squares can be represented as sum of 2 squares in 2 different for...
GATE | GATE-CS-2014-(Set-3) | Question 65 - GeeksforGeeks
28 Jun, 2021 In the following pairs of OSI protocol layer/sub-layer and its functionality, the INCORRECT pair is(A) Network layer and Routing(B) Data Link Layer and Bit synchronization(C) Transport layer and End-to-end process communication(D) Medium Access Control sub-layer and Channel sharingAnswer: (B)Explanation: 1) Yes, Network layer does Rotuing 2) No, Bit synchronization is provided by Physical Layer 3) Yes, Transport layer provides End-to-end process communication 4) Yes, Medium Access Control sub-layer of Data Link Layer provides Channel sharing. Quiz of this Question GATE-CS-2014-(Set-3) GATE-GATE-CS-2014-(Set-3) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE-CS-2006 | Question 47 GATE | GATE MOCK 2017 | Question 24 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25663, "s": 25635, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25969, "s": 25663, "text": "In the following pairs of OSI protocol layer/sub-layer and its functionality, the INCORRECT pair is(A) Network layer and Routing(B) Data Link Layer and Bit synchro...
How to set the Foreground Color of the Label in C#? - GeeksforGeeks
30 Jun, 2019 In Windows Forms, Label control is used to display text on the form and it does not take part in user input or in mouse or keyboard events. You are allowed to set the foreground color of the Label control using the ForeColor Property. It makes your label more attractive. It is an ambient property which means if we do not set the value of this property, it will automatically retrieve from the parent control. You can set this property using two different methods: 1. Design-Time: It is the easiest method to set the ForeColor property of the Label 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 Label control from the ToolBox and drop it on the windows form. You are allowed to place a Label control anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the Label control to set the ForeColor property of the Label.Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the foreground color of the Label control programmatically with the help of given syntax: public virtual System.Drawing.Color ForeColor { get; set; } Here, Color indicates the foreground color of the Label. Following steps are used to set the ForeColor property of the Label: Step 1: Create a label using the Label() constructor is provided by the Label class.// Creating label using Label class Label mylab = new Label(); // Creating label using Label class Label mylab = new Label(); Step 2: After creating Label, set the ForeColor property of the Label provided by the Label class.// Set ForeColor property of the label mylab.ForeColor = Color.DarkBlue; // Set ForeColor property of the label mylab.ForeColor = Color.DarkBlue; Step 3: And last add this Label control to form using Add() method.// Add this label to the form this.Controls.Add(mylab); 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 WindowsFormsApp16 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the label Label mylab = new Label(); mylab.Text = "GeeksforGeeks"; mylab.Location = new Point(222, 90); mylab.Size = new Size(120, 25); mylab.BorderStyle = BorderStyle.FixedSingle; mylab.BackColor = Color.LightBlue; mylab.Font = new Font("Calibri", 12); mylab.ForeColor = Color.DarkBlue; // Adding this control to the form this.Controls.Add(mylab); }}}Output: // Add this label to the form this.Controls.Add(mylab); 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 WindowsFormsApp16 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the label Label mylab = new Label(); mylab.Text = "GeeksforGeeks"; mylab.Location = new Point(222, 90); mylab.Size = new Size(120, 25); mylab.BorderStyle = BorderStyle.FixedSingle; mylab.BackColor = Color.LightBlue; mylab.Font = new Font("Calibri", 12); mylab.ForeColor = Color.DarkBlue; // Adding this control to the form this.Controls.Add(mylab); }}} Output: C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Delegates C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | Class and Object C# | Constructors C# | String.IndexOf( ) Method | Set - 1 C# | Replace() Method Introduction to .NET Framework
[ { "code": null, "e": 26309, "s": 26281, "text": "\n30 Jun, 2019" }, { "code": null, "e": 26775, "s": 26309, "text": "In Windows Forms, Label control is used to display text on the form and it does not take part in user input or in mouse or keyboard events. You are allowed to set ...
How to test Typing Speed using Python? - GeeksforGeeks
09 Sep, 2021 Prerequisites: Python GUI – tkinter In this article, we will create a program test the typing speed of the user with a basic GUI application using Python language. Here the Python libraries like Tkinter and Timeit are used for the GUI and Calculation of time for speed testing respectively. Also, the Random function is used to fetch the random words for the speed testing calculation. Following command is used to install the above-mentioned libraries: pip install tkintertable pip install pytest-timeit Firstly, all the libraries are imported that are installed as mentioned above, and using the bottom-up approach the programming for testing the typing speed using python is created. Below is the implementation. Python3 # importing all librariesfrom tkinter import *from timeit import default_timer as timerimport random # creating window using guiwindow = Tk() # the size of the window is definedwindow.geometry("450x200") x = 0 # defining the function for the testdef game(): global x # loop for destroying the window # after on test if x == 0: window.destroy() x = x+1 # defining function for results of test def check_result(): if entry.get() == words[word]: # here start time is when the window # is opened and end time is when # window is destroyed end = timer() # we deduct the start time from end # time and calculate results using # timeit function print(end-start) else: print("Wrong Input") words = ['programming', 'coding', 'algorithm', 'systems', 'python', 'software'] # Give random words for testing the speed of user word = random.randint(0, (len(words)-1)) # start timer using timeit function start = timer() windows = Tk() windows.geometry("450x200") # use label method of tkinter for labeling in window x2 = Label(windows, text=words[word], font="times 20") # place of labeling in window x2.place(x=150, y=10) x3 = Label(windows, text="Start Typing", font="times 20") x3.place(x=10, y=50) entry = Entry(windows) entry.place(x=280, y=55) # buttons to submit output and check results b2 = Button(windows, text="Done", command=check_result, width=12, bg='grey') b2.place(x=150, y=100) b3 = Button(windows, text="Try Again", command=game, width=12, bg='grey') b3.place(x=250, y=100) windows.mainloop() x1 = Label(window, text="Lets start playing..", font="times 20")x1.place(x=10, y=50) b1 = Button(window, text="Go", command=game, width=12, bg='grey')b1.place(x=150, y=100) # calling windowwindow.mainloop() Output: In the above code, we first create the speed testing window using Tkinter. The function is defined for calculating and printing the correct output after the user input. A specific list of words is provided to the user to type and test the speed of typing. For that, we provide a list of words and generate them with the random function. simranarora5sos Python Tkinter-exercises Python-projects Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25618, "s": 25590, "text": "\n09 Sep, 2021" }, { "code": null, "e": 25654, "s": 25618, "text": "Prerequisites: Python GUI – tkinter" }, { "code": null, "e": 26073, "s": 25654, "text": "In this article, we will create a program test the typ...
Lodash _.isEmpty() Method - GeeksforGeeks
29 Jul, 2020 The Lodash _.isEmpty() Method Checks if the value is an empty object, collection, map, or set. Objects are considered empty if they have no own enumerable string keyed properties. Collections are considered empty if they have a 0 length. Similarly, maps and sets are considered empty if they have a 0 size. Syntax: _.isEmpty( value ) Parameters: This method accepts a single parameter as mentioned above and described below: value: This parameter holds the value that needs to be Checked for Empty value. Return Value: This method returns a Boolean value(Returns true if the given value is an Empty value, else false). Example 1: This method returns true when the value is null. // Defining Lodash variableconst _ = require('lodash'); // Checking for Empty Valueconsole.log("The Value is Empty : " +_.isEmpty(null)); Output: The Value is Empty : true Example 2: This method returns true when an Array is empty. // Defining Lodash variableconst _ = require('lodash'); var val = [] // Checking for Empty Valueconsole.log("The Value is Empty : " +_.isEmpty(val)); Output: The Value is Empty : true Example 3: This method returns true for Boolean value. // Defining Lodash variableconst _ = require('lodash'); var val = false; // Checking for Empty Valueconsole.log("The Value is Empty : " +_.isEmpty(val)); Output: The Value is Empty : true Example 4: In this example, the method will return false. // Defining Lodash variableconst _ = require('lodash'); var val = { "a": 1 }; // Checking for Empty Valueconsole.log("The Value is Empty : " +_.isEmpty(val)); Output: The Value is Empty : false Note: This will not work in normal JavaScript because it requires the lodash library to be installed. Lodash library can be installed using npm install lodash. JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array 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": 25869, "s": 25841, "text": "\n29 Jul, 2020" }, { "code": null, "e": 26176, "s": 25869, "text": "The Lodash _.isEmpty() Method Checks if the value is an empty object, collection, map, or set. Objects are considered empty if they have no own enumerable string k...
How to Add Local HTML File in Android Studio? - GeeksforGeeks
18 Feb, 2021 HTML stands for HyperText Markup Language. It is used to design web pages using a markup language. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. A markup language is used to define the text document within the tag which defines the structure of web pages. HTML is a markup language that is used by the browser to manipulate text, images, and other content to display it in the required format. Some basic characteristics of HTML are given below: Easy to understand: It is the easiest language you can say, very easy to grasp this language, and easy to develop. Flexibility: This language is so much flexible that you can create whatever you want, a flexible way to design web pages along with the text. Linkable: You can make linkable text like users can connect from one page to another page or website through these characteristics. Limitless features: You can add videos, gifs, pictures, or sound anything you want that will make the website more attractive and understandable. Support: You can use this language to display the documents on any platform like Windows, Linux, or Mac. The structure of the HTML document are given below: HTML <!DOCTYPE html><html> <head> <title> <!-- title bar --> </title> <!-- header for the website --> </head> <body> <!-- body section of the website --> </body></html> Android Studio is the official integrated development environment for Google’s Android operating system, built on JetBrains’ IntelliJ IDEA software and designed specifically for Android development. In Android, we usually need HTML files for displaying the content in WebView. If the developer wants to add any website page or want to create a local webpage for the app then it could be done using HTML files. In this article, we are going to will show how to add a local HTML file in Android Studio. We can do it using two methods. Step 1: To add a local HTML file into your Android project there must be an asset folder in it. To create an asset folder in Android studio open your project in Android mode first as shown in the below image. Step 2: Go to the app > right-click > New > Folder > Asset Folder and create the asset folder. Step 3: Android Studio will open a dialog box. Keep all the settings default. Under the target source set, option main should be selected. and click on the finish button. Step 4: The asset folder has been created as shown in the below image. Go to assets > right-click > New > File and a dialog box will pop up. Step 5: Provide a name to your file as shown below. For example “demo.html“. Step 6: Now your HTML file has been created as shown in the below image. You may write your HTML code inside the code section. Method 2 is very easy to implement. You have to just follow two simple steps as follows: Step 1: Create an HTML page anywhere on your PC and then copy the required HTML files. Step 2: Paste it inside the assets folder by right-clicking on the assets folder as shown in the below image. android Android-Studio Android Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Resource Raw Folder in Android Studio Android RecyclerView in Kotlin CardView in Android With Example Content Providers in Android with Example Navigation Drawer in Android How to Update Gradle in Android Studio? Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android?
[ { "code": null, "e": 26339, "s": 26311, "text": "\n18 Feb, 2021" }, { "code": null, "e": 26847, "s": 26339, "text": "HTML stands for HyperText Markup Language. It is used to design web pages using a markup language. HTML is the combination of Hypertext and Markup language. Hypert...
Check if lowercase and uppercase characters are in same order - GeeksforGeeks
15 Feb, 2022 Given a string str containing only lower and uppercase alphabets. The task is to check if both lowercase characters and uppercase characters follow the same order respectively. Note: If a character occurs more than once in lowercase then the occurrence of the same character in the uppercase should be same.Examples: Input: str = "geeGkEEsKS" Output: Yes Lowercase = geeks, Uppercase = GEEKS Input: str = "GeEkKg" Output: No Lowercase = ekg, Uppercase = GEK Approach: Traverse the string.Store the lowercase alphabets and uppercase alphabets in two separate strings lowerStr and upperStr respectively.Convert lowercase string to uppercase.Check if both uppercase strings are equal or not.Print Yes if equal, else print No. Traverse the string. Store the lowercase alphabets and uppercase alphabets in two separate strings lowerStr and upperStr respectively. Convert lowercase string to uppercase. Check if both uppercase strings are equal or not. Print Yes if equal, else print No. Below is the implementation of above approach: C++ Java Python 3 C# Javascript // C++ program to check if lowercase and// uppercase characters are in same order#include <bits/stdc++.h>using namespace std; // Function to check if both the// case follow the same orderbool isCheck(string str){ int len = str.length(); string lowerStr = "", upperStr = ""; // Traverse the string for (int i = 0; i < len; i++) { // Store both lowercase and uppercase // in two different strings if (str[i] >= 65 && str[i] <= 91) upperStr = upperStr + str[i]; else lowerStr = lowerStr + str[i]; } // using transform() function and ::toupper in STL transform(lowerStr.begin(), lowerStr.end(), lowerStr.begin(), ::toupper); return lowerStr == upperStr;} // Driver codeint main(){ string str = "geeGkEEsKS"; isCheck(str) ? cout << "Yes" : cout << "No"; return 0;} //Java program to check if lowercase and// uppercase characters are in same order public class GFG { //Function to check if both the //case follow the same order static boolean isCheck(String str) { int len = str.length(); String lowerStr = "", upperStr = ""; char[] str1 = str.toCharArray(); // Traverse the string for (int i = 0; i < len; i++) { // Store both lowercase and uppercase // in two different strings if ((int)(str1[i]) >= 65 && (int)str1[i] <= 91) upperStr = upperStr + str1[i]; else lowerStr = lowerStr + str1[i]; } // transform lowerStr1 to upper String transformStr = lowerStr.toUpperCase(); return(transformStr.equals(upperStr)); } //Driver code public static void main(String[] args) { String str = "geeGkEEsKS"; if (isCheck(str)) System.out.println("Yes"); else System.out.println("No"); }} # Python 3 program to Check if lowercase and# uppercase characters are in same order # Function to check if both the# case follow the same orderdef isCheck(str) : length = len(str) lowerStr, upperStr = "", "" # Traverse the string for i in range(length) : # Store both lowercase and # uppercase in two different # strings if (ord(str[i]) >= 65 and ord(str[i]) <= 91) : upperStr = upperStr + str[i] else : lowerStr = lowerStr + str[i] # transform lowerStr to uppercase transformStr = lowerStr.upper() return transformStr == upperStr # Driver Codeif __name__ == "__main__" : str = "geeGkEEsKS" if isCheck(str) : print("Yes") else : print("No") # This code is contributed# by ANKITRAI1 // C# program to check if lowercase and// uppercase characters are in same orderusing System; class GFG { //Function to check if both the //case follow the same order static bool isCheck(string str) { int len = str.Length; string lowerStr = "", upperStr = ""; char[] str1 = str.ToCharArray(); // Traverse the string for (int i = 0; i < len; i++) { // Store both lowercase and uppercase // in two different strings if ((int)(str1[i]) >= 65 && (int)str1[i] <= 91) upperStr = upperStr + str1[i]; else lowerStr = lowerStr + str1[i]; } // transform lowerStr1 to upper String transformStr = lowerStr.ToUpper(); return(transformStr.Equals(upperStr)); } //Driver code public static void Main(String[] args) { String str = "geeGkEEsKS"; if (isCheck(str)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} <script> // Javascript program to check if lowercase and// uppercase characters are in same order // Function to check if both the// case follow the same orderfunction isCheck(str){ var len = str.length; var lowerStr = "", upperStr = ""; // Traverse the string for (var i = 0; i < len; i++) { // Store both lowercase and uppercase // in two different strings if (str[i] >= 'A' && str[i] < 'a') upperStr = upperStr + str[i]; else lowerStr = lowerStr + str[i]; } lowerStr = lowerStr.toUpperCase(); console.log(lowerStr); return lowerStr === upperStr;} // Driver codevar str = "geeGkEEsKS";isCheck(str) ? document.write( "Yes") : document.write( "No"); </script> Yes Time Complexity: O(len) Auxiliary Space: O(len), where len is the length of the string. ankthon ukasp Kirti_Mangal noob2000 sweetyty rohitsingh07052 School Programming Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Constructors in Java Exceptions in Java Data Types Inline Functions in C++ Pure Virtual Functions and Abstract Classes in C++ Write a program to reverse an array or string Write a program to print all permutations of a given string Longest Common Subsequence | DP-4 Check for Balanced Brackets in an expression (well-formedness) using Stack KMP Algorithm for Pattern Searching
[ { "code": null, "e": 25439, "s": 25411, "text": "\n15 Feb, 2022" }, { "code": null, "e": 25758, "s": 25439, "text": "Given a string str containing only lower and uppercase alphabets. The task is to check if both lowercase characters and uppercase characters follow the same order ...
C# | Check if Output is Redirected on the Console or not - GeeksforGeeks
28 Jan, 2019 Given the normal Console in C#, the task is to check if the Output is Redirected on the Console. Approach: This can be done using the IsOutputRedirected property in the Console class of the System package in C#. This property returns a boolean value stating whether the Output is Redirected or not. Program: // C# program to demonstrate the// Console.IsOutputRedirected Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { // Main Method static void Main(string[] args) { // Check if Output is Redirected Console.WriteLine("Is Output Redirected: {0}", Console.IsOutputRedirected); }}} Output: CSharp-Console-Class C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers Switch Statement in C# Convert String to Character Array in C# C# | How to insert an element in an Array? Linked List Implementation in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n28 Jan, 2019" }, { "code": null, "e": 25644, "s": 25547, "text": "Given the normal Console in C#, the task is to check if the Output is Redirected on the Console." }, { "code": null, "e": 25846, "s": 25644, "t...
Histograms Equalization using Python OpenCv Module
This is a method in image processing to do contrast adjustment using the image's histogram. Actually this method usually increases the global contrast of many images, especially when the usable data of the image is represented by close contrast values and through this adjustment, the intensities can be better distributed on the histogram and it allows for areas of lower local contrast to gain a higher contrast. OpenCV has a function to do this, cv2.equalizeHist() and its input is just grayscale image and output is our histogram equalized image. This technique is good when histogram of the image is confined to a particular region and it won't work good in places where there are large intensity variations and where histogram covers a large region, i.e. both bright and dark pixels are present. import cv2 # import Numpy import numpy as np # reading an image using imreadmethod my_img = cv2.imread('C:/Users/TP/Pictures/west bengal/bishnupur/pp.jpg', 0) equ = cv2.equalizeHist(my_img) # stacking both the images side-by-side orientation res = np.hstack((my_img, equ)) # showing image input vs output cv2.imshow('image', res) cv2.waitKey(0) cv2.destroyAllWindows()
[ { "code": null, "e": 1154, "s": 1062, "text": "This is a method in image processing to do contrast adjustment using the image's histogram." }, { "code": null, "e": 1477, "s": 1154, "text": "Actually this method usually increases the global contrast of many images, especially when...
How to Learn C++ Programming?
So you've decided to learn how to program in C++ but don't know where to start. Here's a brief overview of how you can get started. This is the first step you'd want to do before starting learning to program in C++. There are good free C++ compilers available for all major OS platforms. Download one that suits your platform or you can use the tutorialspoint.com's online compiler on www.tutorialspoint.com/compile_cpp_online.php GCC − GCC is the GNU Compiler chain that is basically a collection of a bunch of different compilers created by GNU. You can download and install this compiler from http://gcc.gnu.org/ GCC − GCC is the GNU Compiler chain that is basically a collection of a bunch of different compilers created by GNU. You can download and install this compiler from http://gcc.gnu.org/ Clang − Clang is a compiler collection released by the LLVM community. It is available on all platforms and you can download and find install instructions on http://clang.llvm.org/get_started.html Clang − Clang is a compiler collection released by the LLVM community. It is available on all platforms and you can download and find install instructions on http://clang.llvm.org/get_started.html Visual C++ 2017 Community − This is a free C++ compiler built for windows by Microsoft. You can download and install this compiler from www.visualstudio.com/vs/cplusplus/ Visual C++ 2017 Community − This is a free C++ compiler built for windows by Microsoft. You can download and install this compiler from www.visualstudio.com/vs/cplusplus/ Now that you have a compiler installed, its time to write a C++ program. Let's start with the epitome of programming example's, it, the Hello world program. We'll print hello world to the screen using C++ in this example. Create a new file called hello.cpp and write the following code to it − #include<iostream> int main() { std::cout << "Hello World\n"; } Let's dissect this program. Line 1 − We start with the #include<iostream> line which essentially tells the compiler to copy the code from the iostream file(used for managing input and output streams) and paste it in our source file. Header iostream, that allows performing standard input and output operations, such as writing the output of this program (Hello World) to the screen. Lines beginning with a hash sign (#) are directives read and interpreted by what is known as the preprocessor. Line 2 − A blank line: Blank lines have no effect on a program. Line 3 − We then declare a function called main with the return type of int. main() is the entry point of our program. Whenever we run a C++ program, we start with the main function and begin execution from the first line within this function and keep executing each line till we reach the end. We start a block using the curly brace({) here. This marks the beginning of main's function definition, and the closing brace (}) at line 5, marks its end. All statements between these braces are the function's body that defines what happens when main is called. Line 4 − std::cout << "Hello World\n"; This line is a C++ statement. This statement has three parts: First, std::cout, which identifies the standard console output device. Second the insertion operator << which indicates that what follows is inserted into std::cout. Last, we have a sentence within quotes that we'd like printed on the screen. This will become more clear to you as we proceed in learning C++. In short, we provide a cout object with a string "Hello world\n" to be printed to the standard output device. Note that the statement ends with a semicolon (;). This character marks the end of the statement Now that we've written the program, we need to translate it to a language that the processor understands, ie, in binary machine code. We do this using a compiler we installed in the first step. You need to open your terminal/cmd and navigate to the location of the hello.cpp file using the cd command. Assuming you installed the GCC, you can use the following command to compile the program − $ g++ -o hello hello.cpp This command means that you want the g++ compiler to create an output file, hello using the source file hello.cpp. Now that we've written our program and compiled it, time to run it! You can run the program using − $ ./hello You will get the output − Hello world Now that you've learned how to get started with the C++ programming language, you can start learning it by reading up some material on C++ on websites like C++http://www.cplusplus.com/doc/tutorial/, etc. These websites have excellent guides to get started with learning C++ and can help you get started. Some other very helpful resources are books by various authors like Bjarne Stroustrup, Scott Meyers, etc. You can start with the book The tour of C++ and then move on to Effective C++ and the like. Here is a definitive book list for c++ you can check out: https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list. You can also check out the C++ standard to learn more about the language itself. It's freely available as a draft on the ISO C++ website: ISO
[ { "code": null, "e": 1194, "s": 1062, "text": "So you've decided to learn how to program in C++ but don't know where to start. Here's a brief overview of how you can get started." }, { "code": null, "e": 1493, "s": 1194, "text": "This is the first step you'd want to do before sta...
Find all substrings containing exactly K unique vowels - GeeksforGeeks
28 Feb, 2022 Given string str of length N containing both uppercase and lowercase letters, and an integer K. The task is to find all substrings containing exactly K distinct vowels. Examples: Input: str = “aeiou”, K = 2Output: “ae”, “ei”, “io”, “ou”Explanation: These are the substrings containing exactly 2 distinct vowels. Input: str = “TrueGeek”, K = 3Output: “”Explanation: Though the string has more than 3 vowels but there is not three unique vowels.So the answer is empty. Input: str = “TrueGoik”, K = 3Output: “TrueGo”, “rueGo”, “ueGo”, “eGoi”, “eGoik” Approach: This problem can be solved by greedy approach. Generate the substrings and check for every substring. Follow the steps mentioned below to solve the problem: First generate all substrings starting from each index i in range 0 to N. Then for each substring:Keep a hash array to store the occurrences of unique vowels.Check if a new character in the substring is a vowel or not.If it is a vowel, increment its occurrence in the hash and keep a count of distinct vowels foundNow for each substring, if the distinct count of vowels is K, print the substring. Keep a hash array to store the occurrences of unique vowels. Check if a new character in the substring is a vowel or not. If it is a vowel, increment its occurrence in the hash and keep a count of distinct vowels found Now for each substring, if the distinct count of vowels is K, print the substring. If for any loop to find substrings starting from i, the count of distinct vowels exceeds K, or, the substring length has reached string length, break the loop and look for substrings starting from i+1. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ program to find all substrings with// exactly k distinct vowels#include <bits/stdc++.h>using namespace std; #define MAX 128 // Function to check whether// a character is vowel or notbool isVowel(char x){ return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U');} int getIndex(char ch){ return (ch - 'A' > 26 ? ch - 'a' : ch - 'A');} // Function to find all substrings// with exactly k unique vowelsvoid countkDist(string str, int k){ int n = str.length(); // Consider all substrings // beginning with str[i] for (int i = 0; i < n; i++) { int dist_count = 0; // To store count of characters // from 'a' to 'z' vector<int> cnt(26, 0); // Consider all substrings // between str[i..j] for (int j = i; j < n; j++) { // If this is a new vowel // for this substring, // increment dist_count. if (isVowel(str[j]) && cnt[getIndex(str[j])] == 0) { dist_count++; } // Increment count of // current character cnt[getIndex(str[j])]++; // If distinct vowels count // becomes k, then print the // substring. if (dist_count == k) { cout << str.substr(i, j - i + 1) << endl; } if (dist_count > k) break; } }} // Driver codeint main(){ string str = "TrueGoik"; int K = 3; countkDist(str, K); return 0;} // Java program to find all subStrings with// exactly k distinct vowelsimport java.util.*; class GFG{ static final int MAX = 128; // Function to check whether // a character is vowel or not static boolean isVowel(char x) { return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U'); } static int getIndex(char ch) { return (ch - 'A' > 26 ? ch - 'a' : ch - 'A'); } // Function to find all subStrings // with exactly k unique vowels static void countkDist(String str, int k) { int n = str.length(); // Consider all subStrings // beginning with str[i] for (int i = 0; i < n; i++) { int dist_count = 0; // To store count of characters // from 'a' to 'z' int[] cnt = new int[26]; // Consider all subStrings // between str[i..j] for (int j = i; j < n; j++) { String print = new String(str); // If this is a new vowel // for this subString, // increment dist_count. if (isVowel(str.charAt(j)) && cnt[getIndex(str.charAt(j))] == 0) { dist_count++; } // Increment count of // current character cnt[getIndex(str.charAt(j))]++; // If distinct vowels count // becomes k, then print the // subString. if (dist_count == k) { System.out.print(print.substring(i, j +1) +"\n"); } if (dist_count > k) break; } } } // Driver code public static void main(String[] args) { String str = "TrueGoik"; int K = 3; countkDist(str, K); }} // This code is contributed by Rajput-Ji # python3 program to find all substrings with# exactly k distinct vowelsMAX = 128 # Function to check whether# a character is vowel or notdef isVowel(x): return (x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u' or x == 'A' or x == 'E' or x == 'I' or x == 'O' or x == 'U') def getIndex(ch): if ord(ch) - ord('A') > 26: return ord(ch) - ord('a') else: return ord(ch) - ord('A') # Function to find all substrings# with exactly k unique vowelsdef countkDist(str, k): n = len(str) # Consider all substrings # beginning with str[i] for i in range(0, n): dist_count = 0 # To store count of characters # from 'a' to 'z' cnt = [0 for _ in range(26)] # Consider all substrings # between str[i..j] for j in range(i, n): # If this is a new vowel # for this substring, # increment dist_count. if (isVowel(str[j]) and cnt[getIndex(str[j])] == 0): dist_count += 1 # Increment count of # current character cnt[getIndex(str[j])] += 1 # If distinct vowels count # becomes k, then print the # substring. if (dist_count == k): print(str[i:i+j - i + 1]) if (dist_count > k): break # Driver codeif __name__ == "__main__": str = "TrueGoik" K = 3 countkDist(str, K) # This code is contributed by rakeshsahni // C# program to find all substrings with// exactly k distinct vowelsusing System;class GFG { // Function to check whether // a character is vowel or not static bool isVowel(char x) { return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U'); } static int getIndex(char ch) { return (ch - 'A' > 26 ? ch - 'a' : ch - 'A'); } // Function to find all substrings // with exactly k unique vowels static void countkDist(string str, int k) { int n = str.Length; // Consider all substrings // beginning with str[i] for (int i = 0; i < n; i++) { int dist_count = 0; // To store count of characters // from 'a' to 'z' int[] cnt = new int[26]; // Consider all substrings // between str[i..j] for (int j = i; j < n; j++) { // If this is a new vowel // for this substring, // increment dist_count. if (isVowel(str[j]) && cnt[getIndex(str[j])] == 0) { dist_count++; } // Increment count of // current character cnt[getIndex(str[j])]++; // If distinct vowels count // becomes k, then print the // substring. if (dist_count == k) { Console.WriteLine( str.Substring(i, j - i + 1)); } if (dist_count > k) break; } } } // Driver code public static void Main() { string str = "TrueGoik"; int K = 3; countkDist(str, K); }} // This code is contributed by ukasp. <script> // JavaScript code for the above approach // Function to check whether // a character is vowel or not function isVowel(x) { return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U'); } function getIndex(ch) { return ((ch.charCodeAt(0) - 'A'.charCodeAt(0)) > 26 ? (ch.charCodeAt(0) - 'a'.charCodeAt(0)) : (ch.charCodeAt(0) - 'A'.charCodeAt(0))); } // Function to find all substrings // with exactly k unique vowels function countkDist(str, k) { let n = str.length; // Consider all substrings // beginning with str[i] for (let i = 0; i < n; i++) { let dist_count = 0; // To store count of characters // from 'a' to 'z' let cnt = new Array(26).fill(0); // Consider all substrings // between str[i..j] for (let j = i; j < n; j++) { // If this is a new vowel // for this substring, // increment dist_count. if (isVowel(str[j]) && cnt[getIndex(str[j])] == 0) { dist_count++; } // Increment count of // current character cnt[getIndex(str[j])]++; // If distinct vowels count // becomes k, then print the // substring. if (dist_count == k) { document.write(str.slice(i, i + j - i + 1) + '<br>'); } if (dist_count > k) break; } } } // Driver code let s = "TrueGoik"; let K = 3 countkDist(s, K); // This code is contributed by Potta Lokesh </script> TrueGo rueGo ueGo eGoi eGoik Time Complexity: O(N2)Auxiliary Space: O(N2) to store the resulting substrings lokeshpotta20 rakeshsahni ukasp Rajput-Ji Algo-Geek 2021 substring Algo Geek Hash Mathematical Strings Hash Strings Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Maximize partitions that if sorted individually makes the whole Array sorted Day-Stout-Warren algorithm to balance given Binary Search Tree Count Subarrays with strictly decreasing consecutive elements Find Characteristic Polynomial of a Square Matrix Find all Palindrome Strings in given Array of strings Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Count pairs with given sum Hashing | Set 3 (Open Addressing)
[ { "code": null, "e": 25063, "s": 25035, "text": "\n28 Feb, 2022" }, { "code": null, "e": 25232, "s": 25063, "text": "Given string str of length N containing both uppercase and lowercase letters, and an integer K. The task is to find all substrings containing exactly K distinct vo...
Python | shutil.copystat() method - GeeksforGeeks
07 Jul, 2021 Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories.shutil.copystat() method in Python is used to copy the permission bits, last access time, last modification time, and flags value from the given source path to given destination path. The shutil.copystat() method does not affect the file content and owner and group information. On Linux, this method also try to copy some extended attributes in addition to permission bits, last access time, last modification time, and flags value. Syntax: shutil.copystat(source, destination, *, follow_symlinks = True)Parameter: source: A string representing the path of the source file. destination: A string representing the path of the destination file. follow_symlinks (optional) : The default value of this parameter is True. If it is False and source and destination both refers to a symbolic link then the shutil.copystat() method will operate on the symbolic links themselves rather than the files the symbolic links refer to.Note: The ‘*’ in parameter list indicates that all following parameters (Here in our case ‘follow_symlinks’) are keyword-only parameters and they can be provided using their name, not as positional parameter.Return Type: This method does not return any value. Code: Use of shutil.copystat() method to copy metadata from source to destination path Python3 # Python program to explain shutil.copystat() method # importing os moduleimport os # importing shutil moduleimport shutil # importing time moduleimport time # Source file pathsrc = "/home/ihritik/Desktop/sam3.pl" # Destination file pathdest = "/home/ihritik/Desktop/encry.py" # Print the permission bits# last access time, last modification time# and flags value of source and destination filesprint("Before using shutil.copystat() method:")print("Source metadata:")print("Permission bits:", oct(os.stat(src).st_mode)[-3:])print("Last access time:", time.ctime(os.stat(src).st_atime))print("Last modification time:", time.ctime(os.stat(src).st_mtime))# print("User defined Flags:", os.stat(src).st_flags) # Note: st_flags attribute is platform dependent# and is subject to availability print("\nDestination metadata:")print("Permission bits:", oct(os.stat(dest).st_mode)[-3:])print("Last access time:", time.ctime(os.stat(dest).st_atime))print("Last modification time:", time.ctime(os.stat(dest).st_mtime))# print("User defined Flags:", os.stat(dest).st_flags) # Copy the permission bits# last access time, last modification time# and flags value from source to destinationshutil.copystat(src, dest) # Print the permission bits# last access time, last modification time# and flags value of destinationprint("\nAfter using shutil.copystat() method:")print("Destination metadata:")print("Permission bits:", oct(os.stat(dest).st_mode)[-3:])print("Last access time:", time.ctime(os.stat(dest).st_atime))print("Last modification time:", time.ctime(os.stat(dest).st_mtime))# print("User defined Flags:", os.stat(dest).st_flags) print("Permission bits, last access time and last modification time\n\copied from source to destination successfully") Before using shutil.copystat() method: Source metadata: Permission bits: 664 Last access time: Mon Jun 10 00:37:16 2019 Last modification time: Thu Dec 27 00:15:23 2018 Destination metadata: Permission bits: 777 Last access time: Fri Apr 12 01:13:25 2019 Last modification time: Thu Apr 11 02:03:45 2019 After using shutil.copystat() method: Destination metadata: Permission bits: 664 Last access time: Mon Jun 10 00:37:16 2019 Last modification time: Thu Dec 27 00:15:23 2018 Permission bits, last access time and last modification time copied from source to destination successfully Reference: https://docs.python.org/3/library/shutil.html surindertarika1234 surinderdawra388 python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Enumerate() in Python Read a file line by line in Python Defaultdict in Python Different ways to create Pandas Dataframe sum() function in Python Iterate over a list in Python Deque in Python How to Install PIP on Windows ? Python String | replace()
[ { "code": null, "e": 24009, "s": 23981, "text": "\n07 Jul, 2021" }, { "code": null, "e": 24690, "s": 24009, "text": "Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This ...
What are the differences between npm and npx ?
31 May, 2022 NPM: The npm stands for Node Package Manager and it is the default package manager for Node.js. It is written entirely in JavaScript, developed by Isaac Z. Schlueter, it was initially released on January 12, 2010. The npm manages all the packages and modules for node.js and consists of command-line client npm. It gets installed into the system with the installation of node.js. The required packages and modules in the Node project are installed using npm. A package contains all the files needed for a module and modules are the JavaScript libraries that can be included in the Node project according to the requirement of the project. Execute package with npm: By typing the local path: You have to write down the local path of your package like below: ./node_modules/.bin/your-package-name Locally installed: You have to open the package.json file and write down the below scripts: { "name": "Your app", "version": "1.0.0", "scripts": { "your-package": "your-package-name" } } To run package: After that, you can run your package by running the below command: npm run your-package-name NPX: The npx stands for Node Package Execute and it comes with the npm, when you installed npm above 5.2.0 version then automatically npx will installed. It is an npm package runner that can execute any package that you want from the npm registry without even installing that package. The npx is useful during a single time use package. If you have installed npm below 5.2.0 then npx is not installed in your system. You can check npx is installed or not by running the following command: npx -v If npx is not installed you can install that separately by running the below command. npm install -g npx Execute package with npx: Directly runnable: You can execute your package without installation, to do so run the following command. npx your-package-name Differences between npm and npx: npm npx simranarora5sos robinmckenzie2 Node.js-Misc Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between promise and async await in Node.js Mongoose | findByIdAndUpdate() Function JWT Authentication with Node.js Installation of Node.js on Windows Node.js forEach() function 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 ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 52, "s": 24, "text": "\n31 May, 2022" }, { "code": null, "e": 692, "s": 52, "text": "NPM: The npm stands for Node Package Manager and it is the default package manager for Node.js. It is written entirely in JavaScript, developed by Isaac Z. Schlueter, it was...
Make Array Strictly Increasing in C++
Suppose we have two arrays arr1 and arr2, these can store integer numbers. We have to find the minimum number of operations needed to make arr1 strictly increasing. Here, we can choose two indices 0 <= i < n and 0 <= j < m and do the assignment arr1[i] = arr2[j] (n and m are the size of arr1 and arr2 respectively) If we caPending-3nnot make the array arr1 strictly increasing, then return -1. So, if the input is like arr1 = [1,5,3,7,8], arr2 = [1,3,2,5], then the output will be 1, as we can replace 5 with 2, then the array will be [1,2,3,7,8]. To solve this, we will follow these steps − Define a function solve(), this will take an array arr1, an array arr2, i, j, prev, one 2D array dp, Define a function solve(), this will take an array arr1, an array arr2, i, j, prev, one 2D array dp, if i >= size of arr1, then −return 1 if i >= size of arr1, then − return 1 return 1 j = first element of the subarray of arr2 from arr2[j] and upper j = first element of the subarray of arr2 from arr2[j] and upper if dp[i, j] is not equal to -1, then −return dp[i, j] if dp[i, j] is not equal to -1, then − return dp[i, j] return dp[i, j] ret := size of arr2 + 1 ret := size of arr2 + 1 if prev < arr1[i], then −ret := minimum of ret and solve(arr1, arr2, i + 1, j, arr1[i], dp) if prev < arr1[i], then − ret := minimum of ret and solve(arr1, arr2, i + 1, j, arr1[i], dp) ret := minimum of ret and solve(arr1, arr2, i + 1, j, arr1[i], dp) if j < size of arr2, then −ret := minimum of ret and 1 + solve(arr1, arr2, i + 1, j, arr2[j], dp) if j < size of arr2, then − ret := minimum of ret and 1 + solve(arr1, arr2, i + 1, j, arr2[j], dp) ret := minimum of ret and 1 + solve(arr1, arr2, i + 1, j, arr2[j], dp) return dp[i, j] = ret return dp[i, j] = ret From the main method, do the following − From the main method, do the following − sort the array arr2 sort the array arr2 n := size of arr1 n := size of arr1 m := size of arr2 m := size of arr2 Define one 2D array dp of size 2005 x 2005 and fill this with -1 Define one 2D array dp of size 2005 x 2005 and fill this with -1 ret := solve(arr1, arr2, 0, 0, -inf, dp) ret := solve(arr1, arr2, 0, 0, -inf, dp) return (if ret > size of arr2, then -1, otherwise ret - 1) return (if ret > size of arr2, then -1, otherwise ret - 1) Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: int solve(vector<int>& arr1, vector<int>& arr2, int i, int j, int prev, vector<vector<int> >& dp){ if (i >= arr1.size()) return 1; j = upper_bound(arr2.begin() + j, arr2.end(), prev) - arr2.begin(); if (dp[i][j] != -1) return dp[i][j]; int ret = arr2.size() + 1; if (prev < arr1[i]) { ret = min(ret, solve(arr1, arr2, i + 1, j, arr1[i], dp)); } if (j < arr2.size()) { ret = min(ret, 1 + solve(arr1, arr2, i + 1, j, arr2[j], dp)); } return dp[i][j] = ret; } int makeArrayIncreasing(vector<int>& arr1, vector<int>& arr2){ sort(arr2.begin(), arr2.end()); int n = arr1.size(); int m = arr2.size(); vector<vector<int> > dp(2005, vector<int>(2005, -1)); int ret = solve(arr1, arr2, 0, 0, INT_MIN, dp); return ret > arr2.size() ? -1 : ret - 1; } }; main(){ Solution ob; vector<int> v = {1,5,3,7,8}, v1 = {1,3,2,5}; cout << (ob.makeArrayIncreasing(v,v1)); } {1,5,3,7,8}, {1,3,2,5} 1
[ { "code": null, "e": 1503, "s": 1187, "text": "Suppose we have two arrays arr1 and arr2, these can store integer numbers. We have to find the minimum number of operations needed to make arr1 strictly increasing. Here, we can choose two indices 0 <= i < n and 0 <= j < m and do the assignment arr1[i] ...
How to update a Python/tkinter label widget?
Tkinter comes with a handy built-in functionality to handle common text and images related objects. A label widget annotates the user interface with text and images. We can provide any text or images to the label widget so that it displays in the application window. Let us suppose that for a particular application, we need to update the label widget. A label widget is a container that can have either text of image. In the following example, we will update the label image by configuring a button. #Import the required library from tkinter import * from PIL import Image,ImageTk from tkinter import ttk #Create an instance of tkinter frame win= Tk() #Define geometry of the window win.geometry("750x450") #Define a Function to update to Image def update_img(): img2=ImageTk.PhotoImage(Image.open("logo.png")) label.configure(image=img2) label.image=img2 #Load the Image img1= ImageTk.PhotoImage(Image.open("logo1.png")) #Create a Label widget label= Label(win,image= img1) label.pack() #Create a Button to handle the update Image event button= ttk.Button(win, text= "Update", command= update_img) button.pack(pady=15) win.bind("<Return>", update_img) win.mainloop() Running the above code will display a window that contains a label with an image. The Label image will get updated when we click on the “update” button. Now, click the "Update" button to update the label widget and its object.
[ { "code": null, "e": 1454, "s": 1187, "text": "Tkinter comes with a handy built-in functionality to handle common text and images related objects. A label widget annotates the user interface with text and images. We can provide any text or images to the label widget so that it displays in the applic...
Python – Extract Keys with specific Value Type
11 Oct, 2020 Given a dictionary, extract all the keys, whose values are of given type. Input : test_dict = {‘gfg’ : 2, ‘is’ : ‘hello’, ‘for’ : {‘1’ : 3}, ‘geeks’ : 4}, targ_type = int Output : [‘gfg’, ‘geeks’] Explanation : gfg and geeks have integer values. Input : test_dict = {‘gfg’ : 2, ‘is’ : ‘hello’, ‘for’ : {‘1’ : 3}, ‘geeks’ : 4}, targ_type = str Output : [‘is’] Explanation : is has string value. Method #1 : Using loop + isinstance() In this, we check for data type using isinstance(), and iterate for all the values using loop. Python3 # Python3 code to demonstrate working of# Extract Keys with specific Value Type# Using loop + isinstance() # initializing dictionarytest_dict = {'gfg': 2, 'is': 'hello', 'best': 2, 'for': {'1': 3}, 'geeks': 4} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing typetarg_type = int res = []for key, val in test_dict.items(): # checking for values datatype if isinstance(val, targ_type): res.append(key) # printing resultprint("The extracted keys : " + str(res)) Output: The original dictionary is : {‘gfg’: 2, ‘is’: ‘hello’, ‘best’: 2, ‘for’: {‘1’: 3}, ‘geeks’: 4}The extracted keys : [‘gfg’, ‘best’, ‘geeks’] Method #2 : Using list comprehension + isinstance() Similar to above method, one-liner shorthand to solve this problem using list comprehension. Python3 # Python3 code to demonstrate working of# Extract Keys with specific Value Type# Using list comprehension + isinstance() # initializing dictionarytest_dict = {'gfg': 2, 'is': 'hello', 'best': 2, 'for': {'1': 3}, 'geeks': 4} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing typetarg_type = int # one-liner to solve the problemres = [key for key, val in test_dict.items() if isinstance(val, targ_type)] # printing resultprint("The extracted keys : " + str(res)) Output: The original dictionary is : {‘gfg’: 2, ‘is’: ‘hello’, ‘best’: 2, ‘for’: {‘1’: 3}, ‘geeks’: 4}The extracted keys : [‘gfg’, ‘best’, ‘geeks’] Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Oct, 2020" }, { "code": null, "e": 102, "s": 28, "text": "Given a dictionary, extract all the keys, whose values are of given type." }, { "code": null, "e": 274, "s": 102, "text": "Input : test_dict = {‘gfg’ : 2, ...
MySQL | DROP USER
03 Mar, 2018 The DROP USER statement in MySQL can be used to remove a user account along with its privileges from the MySQL completely.But before using the drop user statement, the privileges of the user should be revoked or in other words, if a user has no privileges then the drop user statement can be used to remove a user from the Mysql database server. Syntax: DROP USER 'user'@'host'; Parameters:1. User:It is the user name of the user account you want to drop.2. Host:It is the host server name of the user account.The user name should be in the following format‘user_name’@’host_name’. Suppose there are 4 users in the MySQL database server as listed below: We can drop a single user account as well as multiple user accounts using a single DROP USER statement as shown below: Dropping a single user using the DROP USER statement: To drop the user account with the username “gfguser1”, the drop user statement should be executed as follows:Syntax:Output:Table after execution of the drop user statement will be as follows: Syntax:Output:Table after execution of the drop user statement will be as follows: Dropping multiple users using the DROP USER statement: The Drop User statement can be used to drop multiple user accounts at once. To drop two user account “gfguser2” and “gfguser1” from the table mentioned above,the drop user statement should be executed as follows:Syntax:Output:Table after execution of the above drop user statement will be as follows: Syntax:Output:Table after execution of the above drop user statement will be as follows: Note: In case the DROP USER statement is executed for an user account when the session for this account is active then it will not effect that account until it’s session gets closed. The user account will be dropped after its session gets closed and will not be able to login any more. References: https://dev.mysql.com/doc/refman/5.7/en/drop-user.html mysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? SQL Interview Questions Difference between DELETE, DROP and TRUNCATE Difference between SQL and NoSQL MySQL | Group_CONCAT() Function Difference between DDL and DML in DBMS Window functions in SQL SQL Correlated Subqueries Difference between DELETE and TRUNCATE
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Mar, 2018" }, { "code": null, "e": 374, "s": 28, "text": "The DROP USER statement in MySQL can be used to remove a user account along with its privileges from the MySQL completely.But before using the drop user statement, the privile...
Nashorn JavaScript Engine in Java with Examples
22 Jan, 2020 Nashorn: Nashorn is a JavaScript engine which is introduced in JDK 8. With the help of Nashorn, we can execute JavaScript code at Java Virtual Machine. Nashorn is introduced in JDK 8 to replace existing JavaScript engine i.e. Rhino. Nashorn is far better than Rhino in term of performance. The uses of invoking dynamic feature, conversion of JavaScript code into the bytecode directly into the memory etc makes the Nashorn more famous in JDK 8. We can execute JavaScript code by using the command-line tool and by embedding the JavaScript code into Java source code. Executing JavaScript code by using console: For Nashorn engine, Java 8 introduced one new command-line tool i.e.jjl. We have to follow the below steps to execute JavaScript code through the console: Create one file named with geeks.js. Open geeks.js and write following code into the file and save it.var gfg= function(){ print("Welcome to Geeksforgeeks!!!"); }; gfg(); var gfg= function(){ print("Welcome to Geeksforgeeks!!!"); }; gfg(); Open CMD, write jjl geeks.js and press enter. It will generate the below output:Welcome to Geeksforgeeks!!! Welcome to Geeksforgeeks!!! Executing JavaScript file by embedding JavaScript file into Java code: We can execute JavaScript file by embedding JavaScript file into Java code with the help of ScriptEngine class. ScriptEngine class is introduced in JDK 6. By the help of the ScriptEngine class, we can create a JavaScript engine and with the JavaScript engine, we can execute the javaScript file. Example 1: // Program to illustrate embedding// of JavaScript file into Java code import javax.script.*;import java.io.*; public class Geeksforgeeks { public static void main(String[] args) throws Exception { // Here we are generating Nashorn JavaScript Engine ScriptEngine ee = new ScriptEngineManager() .getEngineByName("Nashorn"); // Reading JavaScript file create in first approach ee.eval(new FileReader("geeks.js")); }} Output: Welcome to Geeksforgeeks!!! Example 2: // Program to illustrate embedding// of JavaScript code into Java code import javax.script.*;import java.io.*; public class Geeksforgeeks { public static void main(String[] args) throws Exception { // Here we are generating Nashorn JavaScript Engine ScriptEngine ee = new ScriptEngineManager() .getEngineByName("Nashorn"); // Instead of reading JavaScript code from a file. // We can directly paste the JavaScript // code inside Java Code ee.eval("print('Welcome to Geeksforgeeks!!!" + " Executing JavaScript code with the" + " help of Nashorn engine');"); }} Output: Welcome to Geeksforgeeks!!! Executing JavaScript code with the help of Nashorn engine Apart from above, with the help of Nashorn JavaScript Engine, we can perform multiple operations like: Providing JavaScript variable from Java Code: Suppose we have one JavaScript file name with geeks.js and geeks.js requires one variable during execution. With the help of Nashorn, we can pass the variable to JavaScript file from java code.Example 1: geeks.js file, which needs name variable to get executed// JavaScript file name with geeks.jsprint("Welcome to Geeksforgeeks!!! Mr. "+name); Example 2: Java code providing name variable to the JS file// Program to illustrate passing of variable// from java code to javascript file import javax.script.*;import java.io.*; public class Geeksforgeeks { public static void main(String[] args) throws Exception { ScriptEngine ee = new ScriptEngineManager() .getEngineByName("Nashorn"); Bindings bind = ee.getBindings( ScriptContext.ENGINE_SCOPE); bind.put("name", "Bishal Kumar Dubey"); ee.eval(new FileReader("geeks.js")); }}Output:Welcome to Geeksforgeeks!!! Mr. Bishal Kumar Dubey Calling JavaScript function from Java code: We can call JavaScript function from Java code with the help of Nashorn. Suppose we create one file name with geeks.js and the file contains two functions like below:// JavaScript file name with geeks.js var func1 = function(){ print("Simple JavaScript function!!!"); } var func2 = function(reader){ print("Hello "+reader); } // Program to illustrate calling of// JavaScript function from Java code import javax.script.*;import java.io.*; public class Geeksforgeeks { public static void main(String[] args) throws Exception { ScriptEngine ee = new ScriptEngineManager() .getEngineByName("Nashorn"); ee.eval(new FileReader("geeks.js")); Invocable invocable = (Invocable)ee; // Here we are calling func1 invocable.invokeFunction("func1"); // Here we are calling func2 // as well as passing argument invocable.invokeFunction("func2", "Bishal Kumar Dubey"); }}Output:Simple JavaScript function!!! Hello Bishal Kumar Dubey Providing JavaScript variable from Java Code: Suppose we have one JavaScript file name with geeks.js and geeks.js requires one variable during execution. With the help of Nashorn, we can pass the variable to JavaScript file from java code.Example 1: geeks.js file, which needs name variable to get executed// JavaScript file name with geeks.jsprint("Welcome to Geeksforgeeks!!! Mr. "+name); Example 2: Java code providing name variable to the JS file// Program to illustrate passing of variable// from java code to javascript file import javax.script.*;import java.io.*; public class Geeksforgeeks { public static void main(String[] args) throws Exception { ScriptEngine ee = new ScriptEngineManager() .getEngineByName("Nashorn"); Bindings bind = ee.getBindings( ScriptContext.ENGINE_SCOPE); bind.put("name", "Bishal Kumar Dubey"); ee.eval(new FileReader("geeks.js")); }}Output:Welcome to Geeksforgeeks!!! Mr. Bishal Kumar Dubey Example 1: geeks.js file, which needs name variable to get executed // JavaScript file name with geeks.jsprint("Welcome to Geeksforgeeks!!! Mr. "+name); Example 2: Java code providing name variable to the JS file // Program to illustrate passing of variable// from java code to javascript file import javax.script.*;import java.io.*; public class Geeksforgeeks { public static void main(String[] args) throws Exception { ScriptEngine ee = new ScriptEngineManager() .getEngineByName("Nashorn"); Bindings bind = ee.getBindings( ScriptContext.ENGINE_SCOPE); bind.put("name", "Bishal Kumar Dubey"); ee.eval(new FileReader("geeks.js")); }} Output: Welcome to Geeksforgeeks!!! Mr. Bishal Kumar Dubey Calling JavaScript function from Java code: We can call JavaScript function from Java code with the help of Nashorn. Suppose we create one file name with geeks.js and the file contains two functions like below:// JavaScript file name with geeks.js var func1 = function(){ print("Simple JavaScript function!!!"); } var func2 = function(reader){ print("Hello "+reader); } // Program to illustrate calling of// JavaScript function from Java code import javax.script.*;import java.io.*; public class Geeksforgeeks { public static void main(String[] args) throws Exception { ScriptEngine ee = new ScriptEngineManager() .getEngineByName("Nashorn"); ee.eval(new FileReader("geeks.js")); Invocable invocable = (Invocable)ee; // Here we are calling func1 invocable.invokeFunction("func1"); // Here we are calling func2 // as well as passing argument invocable.invokeFunction("func2", "Bishal Kumar Dubey"); }}Output:Simple JavaScript function!!! Hello Bishal Kumar Dubey // JavaScript file name with geeks.js var func1 = function(){ print("Simple JavaScript function!!!"); } var func2 = function(reader){ print("Hello "+reader); } // Program to illustrate calling of// JavaScript function from Java code import javax.script.*;import java.io.*; public class Geeksforgeeks { public static void main(String[] args) throws Exception { ScriptEngine ee = new ScriptEngineManager() .getEngineByName("Nashorn"); ee.eval(new FileReader("geeks.js")); Invocable invocable = (Invocable)ee; // Here we are calling func1 invocable.invokeFunction("func1"); // Here we are calling func2 // as well as passing argument invocable.invokeFunction("func2", "Bishal Kumar Dubey"); }} Output: Simple JavaScript function!!! Hello Bishal Kumar Dubey javaScript Technical Scripter 2019 Java JavaScript Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jan, 2020" }, { "code": null, "e": 595, "s": 28, "text": "Nashorn: Nashorn is a JavaScript engine which is introduced in JDK 8. With the help of Nashorn, we can execute JavaScript code at Java Virtual Machine. Nashorn is introduced i...
MANOVA Test in R Programming
25 Aug, 2020 Multivariate analysis of variance (MANOVA) is simply an ANOVA (Analysis of variance) with several dependent variables. It is a continuation of the ANOVA. In an ANOVA, we test for statistical differences on one continuous dependent variable by an independent grouping variable. The MANOVA continues this analysis by taking multiple continuous dependent variables and bundles them collectively into a weighted linear composite variable. The MANOVA compares whether or not the newly created combination varies by the different levels, or groups, of the independent variable. One can perform this MANOVA test in R programming very easily.For example, let’s conduct an experiment where we give two treatments to two groups of rats, and we are taken the weight and height of rats. In that case, the weight and height of rats are two dependent variables, and the hypothesis is that both collectively are affected by the difference in treatment. A multivariate analysis of variance could be used to test this hypothesis. If the global multivariate test is important then assume that the corresponding effect is important. In this case, the subsequent issue is to decide if the treatment affects only the heights, only the weight or both. In other words, we want to distinguish the particular dependent variables that contributed to the significant global effect. And to clarify this question, use one-way ANOVA to test separately each dependent variable. MANOVA can be used in specific conditions: The dependent variables should be normally distributed within groups. Homogeneity of variances across the range of predictors. Linearity between all pairs of covariates, all pairs of dependent variables, and all dependent variable-covariate pairs in every cell. R provides a method manova() to perform the MANOVA test. The class “manova” differs from class “aov” in selecting a different summary method. The function manova() calls aov and then add class “manova” to the result object for each stratum. Syntax: manova(formula, data = NULL, projections = FALSE, qr = TRUE, contrasts = NULL, ...) Parameters: formula: A formula specifying the model. data: A data frame in which the variables specified in the formula will be found. If missing, the variables are searched for in the standard way. projections: Logical flag qr: Logical flag contrasts: A list of contrasts to be used for some of the factors in the formula. ...: Arguments to be passed to lm, such as subset or na.action Example: To perform MANOVA test in R let’s take iris data set. R # R program to illustrate# MANOVA test # Import required librarylibrary(dplyr) # Taking iris data setmyData = iris # Show a random sampleset.seed(1234)dplyr::sample_n(myData, 10) Output: Sepal.Length Sepal.Width Petal.Length Petal.Width Species 1 5.5 2.5 4.0 1.3 versicolor 2 5.6 2.5 3.9 1.1 versicolor 3 6.0 2.9 4.5 1.5 versicolor 4 6.4 3.2 5.3 2.3 virginica 5 4.3 3.0 1.1 0.1 setosa 6 7.2 3.2 6.0 1.8 virginica 7 5.9 3.0 4.2 1.5 versicolor 8 4.6 3.1 1.5 0.2 setosa 9 7.9 3.8 6.4 2.0 virginica 10 5.1 3.4 1.5 0.2 setosa To know if there is any important difference, in sepal and petal length, between the different species then perform MANOVA test. Hence the function manova() can be used as follows. R # Taking two dependent variablesepal = iris$Sepal.Lengthpetal = iris$Petal.Length # MANOVA testresult = manova(cbind(Sepal.Length, Petal.Length) ~ Species, data = iris)summary(result) Output: Df Pillai approx F num Df den Df Pr(>F) Species 2 0.9885 71.829 4 294 < 2.2e-16 *** Residuals 147 --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 From the output above, it can be seen that the two variables are highly significantly different among Species. R-Statistics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 Change Axis Scales in R Plots? R - if statement Logistic Regression in R Programming How to filter R DataFrame by values in a column? Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Aug, 2020" }, { "code": null, "e": 1041, "s": 28, "text": "Multivariate analysis of variance (MANOVA) is simply an ANOVA (Analysis of variance) with several dependent variables. It is a continuation of the ANOVA. In an ANOVA, we test...
Higher Order Functions in C++
07 Jul, 2021 Higher-order functions are functions that take functions as an argument. It is used in functional languages which is not used in C++ are, although this is slowly changing since C++11 gave us lambdas and ‘std::function’... and frequently people don’t realize that ‘std::function’ is not a tool that fills all use cases. In this article, we will explain how to pass a function as an argument to a different calling function. Syntax: return_type function_name(function<return_type fun_name(argument_list), other function arguments) Parameters: In the above function_name takes a function named as fun_name as an argument. Both the function_name and fun_name can have some additional arguments. Below is the illustration of the same: C++14 // C++ program to illustrate the higher// order function in C++#include <bits/stdc++.h>using namespace std; // Function that will be passed as an// arguments to calling functionbool Parser(string x){ // Check if string start // with alphabet 'R' return x[0] == 'R';} // Function that takes function as// an argumentsvector<string> Parse(vector<string> a, function<bool(string)> Parser){ vector<string> ans; // Traverse the vector a for (auto str : a) { if (Parser(str)) { ans.push_back(str); } } // Return the resultant vector return ans;} // Driver Codeint main(){ vector<string> dict = { "geeks", "Rxop", "Rka", "for" }; // Function Call for Higher // Order Functions vector<string> ans = Parse(dict, Parser); // Print the results for (auto str : ans) { cout << str << " "; } return 0;} Rxop Rka Advantages of Higher Order Functions: By the use of the higher-order function, many problems can be solved. For Example, to build a function that takes a list and another function as its input applies that function to each element of that list, and returns the new list. In Haskell, this could be done really easily using the inbuilt higher order function called map. Definition of the map is: map :: (a -> b) -> [a] -> [b] map _ [ ] = [ ] map f (x : xs) = f x : map f xs Here, The first line is the function initialization. The elements symbol stands for “is of the type”. [a] represents a list of similar elements, the entity has written after last -> is always the return type of the function.A function in Haskell always returns only one entity. (a->b) defines a function from ‘a’ to ‘b’. We used recurrence to define map, [] denotes an empty list and _ denotes “anything”. Second-line depicts that if the empty list and any function is input then the output will be empty list. x: xs is used to take out elements one by one from the list, x is the first element (head) and xs is remaining list (tail). : sign stands for concatenation. So in a nutshell, the third line is taking each element from the list and applying function ‘f’ on them, and concatenating it with the remaining list. anikakapoor simmytarika5 Functions STL Articles C++ C++ Programs STL Functions CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction Time complexities of different data structures SQL | DROP, TRUNCATE Difference Between Object And Class Implementation of LinkedList in Javascript Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) std::sort() in C++ STL Bitwise Operators in C/C++
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jul, 2021" }, { "code": null, "e": 475, "s": 52, "text": "Higher-order functions are functions that take functions as an argument. It is used in functional languages which is not used in C++ are, although this is slowly changing sin...
Maximum binomial coefficient term value
28 Nov, 2021 Given a positive integer n. The task is to find the maximum coefficient term in all binomial coefficient. The binomial coefficient series is nC0, nC1, nC2, ...., nCr, ...., nCn-2, nCn-1, nCn the task is to find maximum value of nCr. Examples: Input : n = 4 Output : 6 4C0 = 1 4C1 = 4 4C2 = 6 4C3 = 1 4C4 = 1 So, maximum coefficient value is 6. Input : n = 3 Output : 3 Method 1: (Brute Force) The idea is to find all the value of binomial coefficient series and find the maximum value in the series. Below is the implementation of this approach: C++ Java Python3 C# PHP Javascript // CPP Program to find maximum binomial coefficient// term#include<bits/stdc++.h>using namespace std; // Return maximum binomial coefficient term value.int maxcoefficientvalue(int n){ int C[n+1][n+1]; // Calculate value of Binomial Coefficient in // bottom up manner for (int i = 0; i <= n; i++) { for (int j = 0; j <= min(i, n); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i-1][j-1] + C[i-1][j]; } } // finding the maximum value. int maxvalue = 0; for (int i = 0; i <= n; i++) maxvalue = max(maxvalue, C[n][i]); return maxvalue;} // Driven Programint main(){ int n = 4; cout << maxcoefficientvalue(n) << endl; return 0;} // Java Program to find// maximum binomial // coefficient termimport java.io.*; class GFG {// Return maximum binomial // coefficient term value.static int maxcoefficientvalue(int n){ int [][]C = new int[n + 1][n + 1]; // Calculate value of // Binomial Coefficient // in bottom up manner for (int i = 0; i <= n; i++) { for (int j = 0; j <= Math.min(i, n); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value // using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } // finding the // maximum value. int maxvalue = 0; for (int i = 0; i <= n; i++) maxvalue = Math.max(maxvalue, C[n][i]); return maxvalue;} // Driver Codepublic static void main (String[] args) { int n = 4; System.out.println(maxcoefficientvalue(n));}} // This code is contributed by ajit # Python3 Program to find # maximum binomial # coefficient term # Return maximum binomial # coefficient term value.def maxcoefficientvalue(n): C = [[0 for x in range(n + 1)] for y in range(n + 1)]; # Calculate value of # Binomial Coefficient in # bottom up manner for i in range(n + 1): for j in range(min(i, n) + 1): # Base Cases if (j == 0 or j == i): C[i][j] = 1; # Calculate value # using previously # stored values else: C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]); # finding the maximum value. maxvalue = 0; for i in range(n + 1): maxvalue = max(maxvalue, C[n][i]); return maxvalue; # Driver Coden = 4;print(maxcoefficientvalue(n)); # This code is contributed by mits // C# Program to find maximum binomial coefficient// termusing System; public class GFG { // Return maximum binomial coefficient term value. static int maxcoefficientvalue(int n) { int [,]C = new int[n+1,n+1]; // Calculate value of Binomial Coefficient in // bottom up manner for (int i = 0; i <= n; i++) { for (int j = 0; j <= Math.Min(i, n); j++) { // Base Cases if (j == 0 || j == i) C[i,j] = 1; // Calculate value using previously // stored values else C[i,j] = C[i-1,j-1] + C[i-1,j]; } } // finding the maximum value. int maxvalue = 0; for (int i = 0; i <= n; i++) maxvalue = Math.Max(maxvalue, C[n,i]); return maxvalue; } // Driven Program static public void Main () { int n = 4; Console.WriteLine(maxcoefficientvalue(n)); }} // This code is contributed by vt_m. <?php// PHP Program to find // maximum binomial // coefficient term // Return maximum binomial // coefficient term value.function maxcoefficientvalue($n){ // Calculate value of // Binomial Coefficient in // bottom up manner for ($i = 0; $i <= $n; $i++) { for ($j = 0; $j <= min($i, $n); $j++) { // Base Cases if ($j == 0 || $j == $i) $C[$i][$j] = 1; // Calculate value // using previously // stored values else $C[$i][$j] = $C[$i - 1][$j - 1] + $C[$i - 1][$j]; } } // finding the maximum value. $maxvalue = 0; for ($i = 0; $i <= $n; $i++) $maxvalue = max($maxvalue, $C[$n][$i]); return $maxvalue;} // Driver Code $n = 4; echo maxcoefficientvalue($n), "\n"; // This code is contributed by aj_36?> <script> // JavaScript Program to find // maximum binomial // coefficient term // Returns value of // Binomial Coefficient // C(n, k) function binomialCoeff(n, k) { let C = new Array(n+1); // Loop to create 2D array using 1D array for (let i = 0; i < C.length; i++) { C[i] = new Array(2); } // Calculate value of // Binomial Coefficient // in bottom up manner for (let i = 0; i <= n; i++) { for (let j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using // previously stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k]; } // Return maximum // binomial coefficient // term value. function maxcoefficientvalue(n) { // if n is even if (n % 2 == 0) return binomialCoeff(n, n / 2); // if n is odd else return binomialCoeff(n, (n + 1) / 2); } // Driver Code let n = 4; document.write(maxcoefficientvalue(n)); // This code is contributed by avijitmondal1998..</script> Output: 6 Method 2: (Using formula) Proof, Expansion of (x + y)n are: nC0 xn y0, nC1 xn-1 y1, nC2 xn-2 y2, ...., nCr xn-r yr, ...., nCn-2 x2 yn-2, nCn-1 x1 yn-1, nCn x0 ynSo, putting x = 1 and y = 1, we get binomial coefficient, nC0, nC1, nC2, ...., nCr, ...., nCn-2, nCn-1, nCnLet term ti+1 contains the greatest value in (x + y)n. Therefore, tr+1 >= tr nCr xn-r yr >= nCr-1 xn-r+1 yr-1Putting x = 1 and y = 1, nCr >= nCr-1 nCr/nCr-1 >= 1 (using nCr/nCr-1 = (n-r+1)/r) (n-r+1)/r >= 1 (n+1)/r – 1 >= 1 (n+1)/r >= 2 (n+1)/2 >= rTherefore, r should be less than equal to (n+1)/2. And r should be integer. So, we get maximum coefficient for r equals to: (1) n/2, when n is even. (2) (n+1)/2 or (n-1)/2, when n is odd. C++ Java Python3 C# PHP Javascript // CPP Program to find maximum binomial coefficient term#include<bits/stdc++.h>using namespace std; // Returns value of Binomial Coefficient C(n, k)int binomialCoeff(int n, int k){ int C[n+1][k+1]; // Calculate value of Binomial Coefficient // in bottom up manner for (int i = 0; i <= n; i++) { for (int j = 0; j <= min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i-1][j-1] + C[i-1][j]; } } return C[n][k];} // Return maximum binomial coefficient term value.int maxcoefficientvalue(int n){ // if n is even if (n%2 == 0) return binomialCoeff(n, n/2); // if n is odd else return binomialCoeff(n, (n+1)/2);} // Driven Programint main(){ int n = 4; cout << maxcoefficientvalue(n) << endl; return 0;} // Java Program to find // maximum binomial // coefficient termimport java.io.*; class GFG { // Returns value of // Binomial Coefficient // C(n, k) static int binomialCoeff(int n, int k) { int [][]C = new int[n + 1][k + 1]; // Calculate value of // Binomial Coefficient // in bottom up manner for (int i = 0; i <= n; i++) { for (int j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using // previously stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k]; } // Return maximum // binomial coefficient // term value. static int maxcoefficientvalue(int n) { // if n is even if (n % 2 == 0) return binomialCoeff(n, n / 2); // if n is odd else return binomialCoeff(n, (n + 1) / 2); } // Driver Code public static void main(String[] args) { int n = 4; System.out.println(maxcoefficientvalue(n)); }} // This code is contributed// by akt_mit # Python3 Program to find# maximum binomial# coefficient term# Returns value of # Binomial Coefficient C(n, k)def binomialCoeff(n, k): C=[[0 for x in range(k+1)] for y in range(n+1)] # Calculate value of # Binomial Coefficient # in bottom up manner for i in range(n+1): for j in range(min(i,k)+1): # Base Cases if (j == 0 or j == i): C[i][j] = 1; # Calculate value # using previously # stored values else: C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; return C[n][k]; # Return maximum binomial# coefficient term value.def maxcoefficientvalue(n): # if n is even if (n % 2 == 0): return binomialCoeff(n, int(n / 2)); # if n is odd else: return binomialCoeff(n, int((n + 1) / 2)); # Driver Codeif __name__=='__main__': n = 4; print(maxcoefficientvalue(n)); # This code is contributed by mits // C# Program to find maximum binomial // coefficient termusing System; public class GFG { // Returns value of Binomial Coefficient // C(n, k) static int binomialCoeff(int n, int k) { int [,]C = new int[n+1,k+1]; // Calculate value of Binomial // Coefficient in bottom up manner for (int i = 0; i <= n; i++) { for (int j = 0; j <= Math.Min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i,j] = 1; // Calculate value using // previously stored values else C[i,j] = C[i-1,j-1] + C[i-1,j]; } } return C[n,k]; } // Return maximum binomial coefficient // term value. static int maxcoefficientvalue(int n) { // if n is even if (n % 2 == 0) return binomialCoeff(n, n/2); // if n is odd else return binomialCoeff(n, (n + 1) / 2); } // Driven Program static public void Main () { int n = 4; Console.WriteLine(maxcoefficientvalue(n)); }} // This code is contributed by vt_m. <?php// PHP Program to find// maximum binomial// coefficient term// Returns value of // Binomial Coefficient C(n, k)function binomialCoeff($n, $k){ $C[$n + 1][$k + 1] = array(0); // Calculate value of // Binomial Coefficient // in bottom up manner for ($i = 0; $i <= $n; $i++) { for ($j = 0; $j <= min($i, $k); $j++) { // Base Cases if ($j == 0 || $j == $i) $C[$i][$j] = 1; // Calculate value // using previously // stored values else $C[$i][$j] = $C[$i - 1][$j - 1] + $C[$i - 1][$j]; } } return $C[$n][$k];} // Return maximum binomial// coefficient term value.function maxcoefficientvalue($n){ // if n is even if ($n % 2 == 0) return binomialCoeff($n, $n / 2); // if n is odd else return binomialCoeff($n, ($n + 1) / 2);} // Driver Code$n = 4;echo maxcoefficientvalue($n), "\n"; // This code is contributed by m_kit?> <script> // Javascript Program to find// maximum binomial// coefficient term // Returns value of// Binomial Coefficient// C(n, k)function binomialCoeff(n, k){ let C = new Array(n + 1); for(let i = 0; i <= n; i++) { C[i] = new Array(k + 1); } // Calculate value of // Binomial Coefficient // in bottom up manner for(let i = 0; i <= n; i++) { for(let j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using // previously stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k];} // Return maximum// binomial coefficient// term value.function maxcoefficientvalue(n){ // If n is even if (n % 2 == 0) return binomialCoeff(n, n / 2); // If n is odd else return binomialCoeff(n, (n + 1) / 2);} // Driver Codelet n = 4; document.write(maxcoefficientvalue(n)); // This code is contributed by suresh07 </script> Output: 6 jit_t Mithun Kumar avijitmondal1998 suresh07 binomial coefficient Combinatorial Mathematical Mathematical Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Nov, 2021" }, { "code": null, "e": 261, "s": 28, "text": "Given a positive integer n. The task is to find the maximum coefficient term in all binomial coefficient. The binomial coefficient series is nC0, nC1, nC2, ...., nCr, ...., nC...
Divide the given linked list in two lists of size ratio p:q
02 Nov, 2021 Given a linked list and two integers p and q, the task is to divide the linked list in the ratio p:q i.e. the first list contains first p nodes from the original list and the second list contains the rest of the q nodes. If the original list cannot be split in the given ratio then print -1.Examples: Input: 1 -> 3 -> 5 -> 6 -> 7 -> 2 -> NULL p = 2, q = 4 Output: 1 3 5 6 7 2Input: 1 -> 2 -> 4 -> 9 -> NULL p = 3, q = 2 Output: -1 Approach: First find the length of the linked list. If the total ratio sum exceeds the actual length then dividing the list is not possible so print -1. If it is possible to divide the list then simply traverse the list up to length p and break it into the ratio p:q. Next node will be the head of the second list then print both the lists.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; struct Node{ int data; Node *next; Node(int data) { this->data = data; this->next = NULL; }}; void printList(Node *); // Function to split the given linked list// into ratio of p and qvoid splitAndPrint(Node *head, int p, int q){ int n = 0; Node *temp; temp = head; // Find the length of the list while (temp != NULL) { n += 1; temp = temp->next; } // If ration exceeds the actual length if (p + q > n) { cout << "-1" << endl; return; } temp = head; while (p > 1) { temp = temp->next; p -= 1; } // second head node after splitting Node *head2 = temp->next; temp->next = NULL; // Print first linked list printList(head); cout << endl; // Print second linked list printList(head2);} // Function to print the nodes// of the linked listvoid printList(Node* head){ if (head == NULL) return; cout << head->data << " "; printList(head->next);} // Driver codeint main(){ Node* head = new Node(1); head->next = new Node(3); head->next->next = new Node(5); head->next->next->next = new Node(6); head->next->next->next->next = new Node(7); head->next->next->next->next->next = new Node(2); int p = 2, q = 4; splitAndPrint(head, p, q);} // This code is contributed by rutvik_56. // Java implementation of the approachclass GFG{ // Nodestatic class Node{ int data; Node next; Node(int data) { this.data = data; }} // Function to split the given linked list// into ratio of p and qstatic void splitAndPrint(Node head,int p,int q){ int n = 0; Node temp; temp = head; // Find the length of the list while(temp!=null) { n += 1; temp = temp.next; } // If ration exceeds the actual length if (p + q > n) { System.out.println("-1"); return; } temp = head; while(p > 1) { temp = temp.next; p-= 1; } // second head node after splitting Node head2 = temp.next; temp.next = null; // Print first linked list printList(head); System.out.println(); // Print second linked list printList(head2);} // Function to print the nodes// of the linked liststatic void printList(Node head){ if( head == null) return; System.out.print(head.data+" , "); printList(head.next);} // Driver codepublic static void main(String args[]){ Node head = new Node(1); head.next = new Node(3); head.next.next = new Node(5); head.next.next.next = new Node(6); head.next.next.next.next = new Node(7); head.next.next.next.next.next = new Node(2); int p =2,q= 4; splitAndPrint(head, p, q);}} // This code is contributed by Arnab Kundu # Python3 implementation of the approach # Linked List nodeclass Node: def __init__(self, data): self.data = data self.next = None # Function to split the given linked list# into ratio of p and qdef splitAndPrint(head, p, q): n, temp = 0, head # Find the length of the list while(temp): n += 1 temp = temp.next # If ration exceeds the actual length if p + q>n: print("-1") return temp = head while(p>1): temp = temp.next p-= 1 # second head node after splitting head2 = temp.next temp.next = None # Print first linked list printList(head) print() # Print second linked list printList(head2) # Function to print the nodes# of the linked listdef printList(head): if not head: return print("{} ".format(head.data), end ="") printList(head.next) # Driver codehead = Node(1)head.next = Node(3)head.next.next = Node(5)head.next.next.next = Node(6)head.next.next.next.next = Node(7)head.next.next.next.next.next = Node(2) p, q = 2, 4splitAndPrint(head, p, q) // C# implementation of the approachusing System; class GFG{ public class Node{ public int data; public Node next; public Node(int data) { this.data = data; }} // Function to split the given linked list// into ratio of p and qstatic void splitAndPrint(Node head,int p,int q){ int n = 0; Node temp; temp = head; // Find the length of the list while(temp != null) { n += 1; temp = temp.next; } // If ration exceeds the actual length if (p + q > n) { Console.WriteLine("-1"); return; } temp = head; while(p > 1) { temp = temp.next; p-= 1; } // second head node after splitting Node head2 = temp.next; temp.next = null; // Print first linked list printList(head); Console.WriteLine(); // Print second linked list printList(head2);} // Function to print the nodes// of the linked liststatic void printList(Node head){ if( head == null) return; Console.Write(head.data+" "); printList(head.next);} // Driver codepublic static void Main(String []args){ Node head = new Node(1); head.next = new Node(3); head.next.next = new Node(5); head.next.next.next = new Node(6); head.next.next.next.next = new Node(7); head.next.next.next.next.next = new Node(2); int p = 2, q = 4; splitAndPrint(head, p, q);}} /* This code contributed by PrinciRaj1992 */ <script> // Javascript implementation of the approach // Nodeclass Node{ constructor(data) { this.data = data; }} // Function to split the given linked list// into ratio of p and qfunction splitAndPrint( head, p, q){ var n = 0; var temp; temp = head; // Find the length of the list while(temp!=null) { n += 1; temp = temp.next; } // If ration exceeds the actual length if (p + q > n) { document.write("-1"); return; } temp = head; while(p > 1) { temp = temp.next; p-= 1; } // second head node after splitting var head2 = temp.next; temp.next = null; // Print first linked list printList(head); document.write("</br>"); // Print second linked list printList(head2);} // Function to print the nodes// of the linked listfunction printList(head){ if( head == null) return; document.write(head.data + " "); printList(head.next);} // Driver Code let head = new Node(1); head.next = new Node(3); head.next.next = new Node(5); head.next.next.next = new Node(6); head.next.next.next.next = new Node(7); head.next.next.next.next.next = new Node(2); let p = 2, q = 4; splitAndPrint(head, p, q); // This code is contributed by jana_sayantan.</script> 1 3 5 6 7 2 Time Complexity: O(N)Auxiliary Space: O(1) andrew1234 princiraj1992 rutvik_56 jana_sayantan pankajsharmagfg amartyaghoshgfg Data Structures Linked List Data Structures Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Nov, 2021" }, { "code": null, "e": 331, "s": 28, "text": "Given a linked list and two integers p and q, the task is to divide the linked list in the ratio p:q i.e. the first list contains first p nodes from the original list and the ...
Placeholder in Tkinter
24 Jan, 2021 Prerequisite: Python GUI – tkinter Bind – Tkinter Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. What is a placeholder and how can it be implemented using tkinter: In programming, a placeholder may be a character, word, or string of characters that briefly takes the place of the final data. For instance, an applied scientist might recognize that she desires a precise range of values or variables, however does not however recognize what to input. The Placeholder attribute is used to give hint that tells what input is expected by input field, or we can say it will give the short hint that is displayed within the input field before the user enters a value. In Tkinter there is no in-built method or property for placeholder but it can still be executed using the modules’ inbuilt functions. Approach: Import module Create Normal Tkinter Window Add Entry box Syntax: Entry(Object Name, **attr) Add placeholder, here it is done using insert() and then the same is bonded to the box Syntax: insert(index) Execute code Program: Python3 # Import Modulefrom tkinter import * # Create Tkinter Objectroot = Tk() # Set geometryroot.geometry('400x400') # call function when we click on entry boxdef click(*args): playlist_url.delete(0, 'end') # call function when we leave entry boxdef leave(*args): playlist_url.delete(0, 'end') playlist_url.insert(0, 'Enter Text:- ') root.focus() # Add Entry Boxplaylist_url = Entry(root, width=60) # Add text in Entry boxplaylist_url.insert(0, 'Enter Text:- ')playlist_url.pack(pady=10) # Use bind methodplaylist_url.bind("<Button-1>", click)playlist_url.bind("<Leave>", leave) # Execute Tkinterroot.mainloop() Output: Python-tkinter 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 Python | os.path.join() method 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 Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jan, 2021" }, { "code": null, "e": 43, "s": 28, "text": "Prerequisite: " }, { "code": null, "e": 64, "s": 43, "text": "Python GUI – tkinter" }, { "code": null, "e": 79, "s": 64, "text": "Bind –...
Reflection in Java
31 May, 2022 Reflection is an API that is used to examine or modify the behavior of methods, classes, and interfaces at runtime. The required classes for reflection are provided under java.lang.reflect package which is essential in order to understand reflection. So we are illustrating the package with visual aids to have a better understanding as follows: Reflection gives us information about the class to which an object belongs and also the methods of that class that can be executed by using the object. Through reflection, we can invoke methods at runtime irrespective of the access specifier used with them. Reflection can be used to get information about class, constructors, and methods as depicted below in tabular format as shown: We can invoke a method through reflection if we know its name and parameter types. We use two methods for this purpose as described below before moving ahead as follows: getDeclaredMethod()invoke() getDeclaredMethod() invoke() Method 1: getDeclaredMethod(): It creates an object of the method to be invoked. Syntax: The syntax for this method Class.getDeclaredMethod(name, parametertype) Parameters: Name of a method whose object is to be created An array of Class objects Method 2: invoke(): It invokes a method of the class at runtime we use the following method. Syntax: Method.invoke(Object, parameter) Tip: If the method of the class doesn’t accept any parameter then null is passed as an argument. Note: Through reflection, we can access the private variables and methods of a class with the help of its class object and invoke the method by using the object as discussed above. We use below two methods for this purpose. Method 3: Class.getDeclaredField(FieldName): Used to get the private field. Returns an object of type Field for the specified field name. Method 4: Field.setAccessible(true): Allows to access the field irrespective of the access modifier used with the field. Extensibility Features: An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names. Debugging and testing tools: Debuggers use the property of reflection to examine private members of classes. Performance Overhead: Reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code that are called frequently in performance-sensitive applications. Exposure of Internals: Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform. Example Java // Java Program to demonstrate the Use of Reflection // Importing required classesimport java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.Method; // Class 1// Of Whose object is to be createdclass Test { // creating a private field private String s; // Constructor of this class // Constructor 1 // Public constructor public Test() { s = "GeeksforGeeks"; } // Constructor 2 // no arguments public void method1() { System.out.println("The string is " + s); } // Constructor 3 // int as argument public void method2(int n) { System.out.println("The number is " + n); } // Constructor 4 // Private method private void method3() { System.out.println("Private method invoked"); }} // Class 2// Main classclass GFG { // Main driver method public static void main(String args[]) throws Exception { // Creating object whose property is to be checked // Creating an object of class 1 inside main() // method Test obj = new Test(); // Creating class object from the object using // getClass() method Class cls = obj.getClass(); // Printing the name of class // using getName() method System.out.println("The name of class is " + cls.getName()); // Getting the constructor of the class through the // object of the class Constructor constructor = cls.getConstructor(); // Printing the name of constructor // using getName() method System.out.println("The name of constructor is " + constructor.getName()); // Display message only System.out.println( "The public methods of class are : "); // Getting methods of the class through the object // of the class by using getMethods Method[] methods = cls.getMethods(); // Printing method names for (Method method : methods) System.out.println(method.getName()); // Creates object of desired method by // providing the method name and parameter class as // arguments to the getDeclaredMethod() method Method methodcall1 = cls.getDeclaredMethod("method2", int.class); // Invoking the method at runtime methodcall1.invoke(obj, 19); // Creates object of the desired field by // providing the name of field as argument to the // getDeclaredField() method Field field = cls.getDeclaredField("s"); // Allows the object to access the field // irrespective of the access specifier used with // the field field.setAccessible(true); // Takes object and the new value to be assigned // to the field as arguments field.set(obj, "JAVA"); // Creates object of desired method by providing the // method name as argument to the // getDeclaredMethod() Method methodcall2 = cls.getDeclaredMethod("method1"); // Invokes the method at runtime methodcall2.invoke(obj); // Creates object of the desired method by providing // the name of method as argument to the // getDeclaredMethod() method Method methodcall3 = cls.getDeclaredMethod("method3"); // Allows the object to access the method // irrespective of the access specifier used with // the method methodcall3.setAccessible(true); // Invoking the method at runtime methodcall3.invoke(obj); }} Output: Start your programming journey the easy way! Learn Java basics and go from basics to advance with our Java Programming Foundation – Self Paced Course. This course covers topics like Variables and Data types, Operators, Loops, Functions in Java and a lot more, curated by leading industry experts having years of expertise. Get yourself enrolled and become an expert in JAVA! solankimayank Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n31 May, 2022" }, { "code": null, "e": 401, "s": 54, "text": "Reflection is an API that is used to examine or modify the behavior of methods, classes, and interfaces at runtime. The required classes for reflection are provided under jav...
PyQt5 QCheckBox
17 Sep, 2019 Check Box is one of the PyQt5 widgets used to select one or more choices from multiple options. It is a small box which gets checked when selected, else remains blank. For adding Check boxe in application QCheckBox class is used. Example: A window asking the user to select all the programming languages user knows. After each selection or deselection by the user, the message gets updated which contains the list of all the languages selected by him/her like: “You know c, c++ ...”. Below is the code: import sysfrom PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.resize(476, 308) self.centralwidget = QtWidgets.QWidget(MainWindow) # Languages are not selected initially hence initialised to zero. self.langs ={'c':0, 'cpp':0, 'java':0, 'python':0} # For showing message self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(140, 80, 191, 20)) self.checkBox_c = QtWidgets.QCheckBox(self.centralwidget) self.checkBox_c.setGeometry(QtCore.QRect(170, 120, 81, 20)) self.checkBox_c.stateChanged.connect(self.checkedc) self.checkBox_cpp = QtWidgets.QCheckBox(self.centralwidget) self.checkBox_cpp.setGeometry(QtCore.QRect(170, 140, 81, 20)) self.checkBox_cpp.stateChanged.connect(self.checkedcpp) self.checkBox_java = QtWidgets.QCheckBox(self.centralwidget) self.checkBox_java.setGeometry(QtCore.QRect(170, 160, 81, 20)) self.checkBox_java.stateChanged.connect(self.checkedjava) self.checkBox_py = QtWidgets.QCheckBox(self.centralwidget) self.checkBox_py.setGeometry(QtCore.QRect(170, 180, 81, 20)) self.checkBox_py.stateChanged.connect(self.checkedpy) MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def checkedc(self, checked): if checked: self.langs['c']= 1 else: self.langs['c']= 0 self.show() def checkedcpp(self, checked): if checked: self.langs['cpp']= 1 else: self.langs['cpp']= 0 self.show() def checkedjava(self, checked): if checked: self.langs['java']= 1 else: self.langs['java']= 0 self.show() def checkedpy(self, checked): if checked: self.langs['python']= 1 else: self.langs['python']= 0 self.show() # For showing updated list of all selected languages. def show(self): checkedlangs =', '.join([key for key in self.langs.keys() if self.langs[key]== 1]) # Updates message having list of all selected languages. self.label.setText("You know "+checkedlangs) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.label.setText(_translate("MainWindow", "Select your preferred language")) self.checkBox_c.setText(_translate("MainWindow", "C")) self.checkBox_cpp.setText(_translate("MainWindow", "C++")) self.checkBox_java.setText(_translate("MainWindow", "Java")) self.checkBox_py.setText(_translate("MainWindow", "Python")) if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_()) Output: Message showing user’s selected languages. Message will get updated after each selection or deselection by the user. Python-gui Python-PyQt 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": "\n17 Sep, 2019" }, { "code": null, "e": 258, "s": 28, "text": "Check Box is one of the PyQt5 widgets used to select one or more choices from multiple options. It is a small box which gets checked when selected, else remains blank. For add...
Slices in Golang
08 Jan, 2021 In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. Slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. It is just like an array having an index value and length, but the size of the slice is resized they are not in fixed-size just like an array. Internally, slice and an array are connected with each other, a slice is a reference to an underlying array. It is allowed to store duplicate elements in the slice. The first index position in a slice is always 0 and the last one will be (length of slice – 1). A slice is declared just like an array, but it doesn’t contain the size of the slice. So it can grow or shrink according to the requirement. Syntax: []T or []T{} or []T{value1, value2, value3, ...value n} Here, T is the type of the elements. For example: var my_slice[]int A slice contains three components: Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Pointer: The pointer is used to points to the first element of the array that is accessible through the slice. Here, it is not necessary that the pointed element is the first element of the array. Length: The length is the total number of elements present in the array. Capacity: The capacity represents the maximum size upto which it can expand. Let us discuss all these components with the help of an example: Example: Go // Golang program to illustrate// the working of the slice componentspackage main import "fmt" func main() { // Creating an array arr := [7]string{"This", "is", "the", "tutorial", "of", "Go", "language"} // Display array fmt.Println("Array:", arr) // Creating a slice myslice := arr[1:6] // Display slice fmt.Println("Slice:", myslice) // Display length of the slice fmt.Printf("Length of the slice: %d", len(myslice)) // Display the capacity of the slice fmt.Printf("\nCapacity of the slice: %d", cap(myslice))} Output: Array: [This is the tutorial of Go language] Slice: [is the tutorial of Go] Length of the slice: 5 Capacity of the slice: 6 Explanation: In the above example, we create a slice from the given array. Here the pointer of the slice pointed to index 1 because the lower bound of the slice is set to one so it starts accessing elements from index 1. The length of the slice is 5, which means the total number of elements present in the slice is 5 and the capacity of the slice 6 means it can store a maximum of 6 elements in it. In Go language, a slice can be created and initialized using the following ways: Using slice literal: You can create a slice using the slice literal. The creation of slice literal is just like an array literal, but with one difference you are not allowed to specify the size of the slice in the square braces[]. As shown in the below example, the right-hand side of this expression is the slice literal. var my_slice_1 = []string{"Geeks", "for", "Geeks"} Note: Always remember when you create a slice using a string literal, then it first creates an array and after that return a slice reference to it. Example: Go // Golang program to illustrate how// to create a slice using a slice// literalpackage main import "fmt" func main() { // Creating a slice // using the var keyword var my_slice_1 = []string{"Geeks", "for", "Geeks"} fmt.Println("My Slice 1:", my_slice_1) // Creating a slice //using shorthand declaration my_slice_2 := []int{12, 45, 67, 56, 43, 34, 45} fmt.Println("My Slice 2:", my_slice_2)} Output: My Slice 1: [Geeks for Geeks] My Slice 2: [12 45 67 56 43 34 45] Using an Array: As we already know that the slice is the reference of the array so you can create a slice from the given array. For creating a slice from the given array first you need to specify the lower and upper bound, which means slice can take elements from the array starting from the lower bound to the upper bound. It does not include the elements above from the upper bound. As shown in the below example:Syntax: array_name[low:high] This syntax will return a new slice. Note: The default value of the lower bound is 0 and the default value of the upper bound is the total number of the elements present in the given array. Example: Go // Golang program to illustrate how to// create slices from the arraypackage main import "fmt" func main() { // Creating an array arr := [4]string{"Geeks", "for", "Geeks", "GFG"} // Creating slices from the given array var my_slice_1 = arr[1:2] my_slice_2 := arr[0:] my_slice_3 := arr[:2] my_slice_4 := arr[:] // Display the result fmt.Println("My Array: ", arr) fmt.Println("My Slice 1: ", my_slice_1) fmt.Println("My Slice 2: ", my_slice_2) fmt.Println("My Slice 3: ", my_slice_3) fmt.Println("My Slice 4: ", my_slice_4)} Output: My Array: [Geeks for Geeks GFG] My Slice 1: [for] My Slice 2: [Geeks for Geeks GFG] My Slice 3: [Geeks for] My Slice 4: [Geeks for Geeks GFG] Using already Existing Slice: It is also be allowed to create a slice from the given slice. For creating a slice from the given slice first you need to specify the lower and upper bound, which means slice can take elements from the given slice starting from the lower bound to the upper bound. It does not include the elements above from the upper bound. As shown in the below example:Syntax: slice_name[low:high] This syntax will return a new slice. Note: The default value of the lower bound is 0 and the default value of the upper bound is the total number of the elements present in the given slice. Example: Go // Golang program to illustrate how to// create slices from the slicepackage main import "fmt" func main() { // Creating s slice oRignAl_slice := []int{90, 60, 40, 50, 34, 49, 30} // Creating slices from the given slice var my_slice_1 = oRignAl_slice[1:5] my_slice_2 := oRignAl_slice[0:] my_slice_3 := oRignAl_slice[:6] my_slice_4 := oRignAl_slice[:] my_slice_5 := my_slice_3[2:4] // Display the result fmt.Println("Original Slice:", oRignAl_slice) fmt.Println("New Slice 1:", my_slice_1) fmt.Println("New Slice 2:", my_slice_2) fmt.Println("New Slice 3:", my_slice_3) fmt.Println("New Slice 4:", my_slice_4) fmt.Println("New Slice 5:", my_slice_5)} Output: Original Slice: [90 60 40 50 34 49 30] New Slice 1: [60 40 50 34] New Slice 2: [90 60 40 50 34 49 30] New Slice 3: [90 60 40 50 34 49] New Slice 4: [90 60 40 50 34 49 30] New Slice 5: [40 50] Using make() function: You can also create a slice using the make() function which is provided by the go library. This function takes three parameters, i.e, type, length, and capacity. Here, capacity value is optional. It assigns an underlying array with a size that is equal to the given capacity and returns a slice which refers to the underlying array. Generally, make() function is used to create an empty slice. Here, empty slices are those slices that contain an empty array reference.Syntax: func make([]T, len, cap) []T Example: Go // Go program to illustrate how to create slices// Using make functionpackage main import "fmt" func main() { // Creating an array of size 7 // and slice this array till 4 // and return the reference of the slice // Using make function var my_slice_1 = make([]int, 4, 7) fmt.Printf("Slice 1 = %v, \nlength = %d, \ncapacity = %d\n", my_slice_1, len(my_slice_1), cap(my_slice_1)) // Creating another array of size 7 // and return the reference of the slice // Using make function var my_slice_2 = make([]int, 7) fmt.Printf("Slice 2 = %v, \nlength = %d, \ncapacity = %d\n", my_slice_2, len(my_slice_2), cap(my_slice_2)) } Output: Slice 1 = [0 0 0 0], length = 4, capacity = 7 Slice 2 = [0 0 0 0 0 0 0], length = 7, capacity = 7 You can iterate over slice using the following ways: Using for loop: It is the simplest way to iterate slice as shown in the below example:Example: Go // Golang program to illustrate the// iterating over a slice using// for looppackage main import "fmt" func main() { // Creating a slice myslice := []string{"This", "is", "the", "tutorial", "of", "Go", "language"} // Iterate using for loop for e := 0; e < len(myslice); e++ { fmt.Println(myslice[e]) }} Output: This is the tutorial of Go language Using range in for loop: It is allowed to iterate over a slice using range in the for loop. Using range in the for loop, you can get the index and the element value as shown in the example:Example: Go // Golang program to illustrate the iterating// over a slice using range in for looppackage main import "fmt" func main() { // Creating a slice myslice := []string{"This", "is", "the", "tutorial", "of", "Go", "language"} // Iterate slice // using range in for loop for index, ele := range myslice { fmt.Printf("Index = %d and element = %s\n", index+3, ele) }} Output: Index = 3 and element = This Index = 4 and element = is Index = 5 and element = the Index = 6 and element = tutorial Index = 7 and element = of Index = 8 and element = Go Index = 9 and element = language Using a blank identifier in for loop: In the range for loop, if you don’t want to get the index value of the elements then you can use blank space(_) in place of index variable as shown in the below example:Example: Go // Golang program to illustrate the iterating over// a slice using range in for loop without an indexpackage main import "fmt" func main() { // Creating a slice myslice := []string{"This", "is", "the", "tutorial", "of", "Go", "language"} // Iterate slice // using range in for loop // without index for _, ele := range myslice { fmt.Printf("Element = %s\n", ele) }} Output: Element = This Element = is Element = the Element = tutorial Element = of Element = Go Element = language Zero value slice: In Go language, you are allowed to create a nil slice that does not contain any element in it. So the capacity and the length of this slice is 0. Nil slice does not contain an array reference as shown in the below example:Example: Go // Go program to illustrate a zero value slicepackage main import "fmt" func main() { // Creating a zero value slice var myslice []string fmt.Printf("Length = %d\n", len(myslice)) fmt.Printf("Capacity = %d ", cap(myslice)) } Output: Length = 0 Capacity = 0 Modifying Slice: As we already know that slice is a reference type it can refer an underlying array. So if we change some elements in the slice, then the changes should also take place in the referenced array. Or in other words, if you made any changes in the slice, then it will also reflect in the array as shown in the below example:Example: Go // Golang program to illustrate// how to modify the slicepackage main import "fmt" func main() { // Creating a zero value slice arr := [6]int{55, 66, 77, 88, 99, 22} slc := arr[0:4] // Before modifying fmt.Println("Original_Array: ", arr) fmt.Println("Original_Slice: ", slc) // After modification slc[0] = 100 slc[1] = 1000 slc[2] = 1000 fmt.Println("\nNew_Array: ", arr) fmt.Println("New_Slice: ", slc)} Output: Original_Array: [55 66 77 88 99 22] Original_Slice: [55 66 77 88] New_Array: [100 1000 1000 88 99 22] New_Slice: [100 1000 1000 88] Comparison of Slice: In Slice, you can only use == operator to check the given slice is nill or not. If you try to compare two slices with the help of == operator then it will give you an error as shown in the below example:Example: Go // Golang program to check if// the slice is nil or notpackage main import "fmt" func main() { // creating slices s1 := []int{12, 34, 56} var s2 []int // If you try to run this commented // code compiler will give an error /*s3:= []int{23, 45, 66} fmt.Println(s1==s3) */ // Checking if the given slice is nil or not fmt.Println(s1 == nil) fmt.Println(s2 == nil)} Output: false true Note: If you want to compare two slices, then use range for loop to match each element or you can use DeepEqual function. Multi-Dimensional Slice: Multi-dimensional slice are just like the multidimensional array, except that slice does not contain the size. Example: Go // Go program to illustrate the multi-dimensional slicepackage main import "fmt" func main() { // Creating multi-dimensional slice s1 := [][]int{{12, 34}, {56, 47}, {29, 40}, {46, 78}, } // Accessing multi-dimensional slice fmt.Println("Slice 1 : ", s1) // Creating multi-dimensional slice s2 := [][]string{ []string{"Geeks", "for"}, []string{"Geeks", "GFG"}, []string{"gfg", "geek"}, } // Accessing multi-dimensional slice fmt.Println("Slice 2 : ", s2) } Output: Slice 1 : [[12 34] [56 47] [29 40] [46 78]] Slice 2 : [[Geeks for] [Geeks GFG] [gfg geek]] Sorting of Slice: In Go language, you are allowed to sort the elements present in the slice. The standard library of Go language provides the sort package which contains different types of sorting methods for sorting the slice of ints, float64s, and strings. These functions always sort the elements available is slice in ascending order.Example: Go // Go program to illustrate how to sort// the elements present in the slicepackage main import ( "fmt" "sort") func main() { // Creating Slice slc1 := []string{"Python", "Java", "C#", "Go", "Ruby"} slc2 := []int{45, 67, 23, 90, 33, 21, 56, 78, 89} fmt.Println("Before sorting:") fmt.Println("Slice 1: ", slc1) fmt.Println("Slice 2: ", slc2) // Performing sort operation on the // slice using sort function sort.Strings(slc1) sort.Ints(slc2) fmt.Println("\nAfter sorting:") fmt.Println("Slice 1: ", slc1) fmt.Println("Slice 2: ", slc2) } Output: Before sorting: Slice 1: [Python Java C# Go Ruby] Slice 2: [45 67 23 90 33 21 56 78 89] After sorting: Slice 1: [C# Go Java Python Ruby] Slice 2: [21 23 33 45 56 67 78 89 90] Akanksha_Rai rajdeep0309241 Golang Golang-Slices Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n08 Jan, 2021" }, { "code": null, "e": 721, "s": 53, "text": "In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. Slice is a variable-length sequence which stores elements of a...
Drop a list of rows from a Pandas DataFrame
30 Nov, 2021 Let us see how to drop a list of rows in a Pandas DataFrame. We can do this using the drop() function. We will also pass inplace = True as it makes sure that the changes we make in the instance are stored in that instance without doing any assignmentOver here is the code implementation of how to drop list of rows from the table : Example 1 : Python3 # import the moduleimport pandas as pd # creating a DataFramedictionary = {'Names':['Simon', 'Josh', 'Amen', 'Habby', 'Jonathan', 'Nick'], 'Countries':['AUSTRIA', 'BELGIUM', 'BRAZIL', 'FRANCE', 'INDIA', 'GERMANY']}table = pd.DataFrame(dictionary, columns = ['Names', 'Countries'], index = ['a', 'b', 'c', 'd', 'e', 'f']) display(table) # gives the table with the dropped rowsdisplay("Table with the dropped rows")display(table.drop(['a', 'd'])) # gives the table with the dropped rows# shows the reduced table for the given command onlydisplay("Reduced table for the given command only")display(table.drop(table.index[[1, 3]])) # it gives none but it makes changes in the tabledisplay(table.drop(['a', 'd'], inplace = True)) # final tableprint("Final Table")display(table) # table after removing range of rows from 0 to 2(not included)table.drop(table.index[:2], inplace = True) display(table) Output : Example 2 : Python3 # creating a DataFrame data = {'Name' : ['Jai', 'Princi', 'Gaurav', 'Anuj'], 'Age' : [27, 24, 22, 32], 'Address' : ['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'], 'Qualification' : ['Msc', 'MA', 'MCA', 'Phd']}table = pd.DataFrame(data) # original DataFramedisplay("Original DataFrame")display(table) # drop 2nd rowdisplay("Dropped 2nd row")display(table.drop(1)) Output : saurabh1990aror singghakshay Python pandas-dataFrame Python-pandas 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 How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Nov, 2021" }, { "code": null, "e": 360, "s": 28, "text": "Let us see how to drop a list of rows in a Pandas DataFrame. We can do this using the drop() function. We will also pass inplace = True as it makes sure that the changes we ma...
How to create a review carousel using JavaScript ?
12 Aug, 2021 In this article, we have created a review carousel using JavaScript. We have also used basic HTMM and CSS for styling. A carousel is basically a type of slideshow used to display images, text, or both in a cyclic manner. Review Carousel is used to display the reviews. Approach: In the body tag, create a nested div tag with class name containing the reviewer image, name, and text. Add previous and next buttons to check previous and next reviews, respectively. For styling, add some CSS properties in the style tag like alignment, font size, padding, margin, etc. Create a function using JavaScript in the script tag to display only one review at a time. Example: Create a review carousel using the above approach. HTML Code: As in the first two steps, we will create a nested div tag and two buttons in the body tag. index.html <div class="review"> <div class="review__items"> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" /> <h1>GeeksforGeeks</h1> <p> Let's learn to create a review carousel using JavaScript. </p> </div> <div class="review__items"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20210101144014/gfglogo.png" /> <h1>Geek Here</h1> <p> Very useful site to learn cool stuff. Improve your skills </p> </div> <div class="review__items"> <img src="https://media.geeksforgeeks.org/img-practice/courses/GfG_Logo.png" /> <h1>Hello there!</h1> <p> Have a nice day, Please visit us again. Nice to meet you. </p> </div> <div class="review__button"> <button id="prev" onclick="previousReview()"> PREV </button> <button id="next" onclick="nextReview()"> NEXT </button> </div></div> Note: In the button tag, we have specified an attribute onclick. The onclick event attribute works when the user clicks the button. It will execute the function when the button is clicked. CSS code: For styling, we have used CSS properties. style.css .review { background: rgb(145, 226, 188); height: auto; width: 270px; border-radius: 15px; margin: auto; padding: 10px; margin-top: 30px; box-shadow: 5px 5px 5px #32917d; align-items: center;} .review__items { align-items: center; justify-content: space-evenly; width: 250px; padding: 10px; align-items: center;} .review__items img { height: 250px; width: 250px; border-radius: 5px; box-shadow: rgba(0, 0, 0, 0.35) 0px 4px 15px;} .review__items h1 { font-family: Verdana, Geneva, Tahoma, sans-serif; font-size: 20px;} .review__items p { font-family: Verdana, Geneva, Tahoma, sans-serif; font-size: 14px;} .review__button { text-align: center; padding: 10px;} .review__button button { color: rgb(192, 229, 192); background: green; font-weight: bold;} .review__items { display: none;} Note: We can also create another file for styling or we can add them in the same HTML file under the style tag. Now, to display only one review at a time we will create some functions in JavaScript. Carousel function: This function gets all the elements using the specified class name as an object with the help of the getElementsByClassName() method. These objects can be accessed by the index of the elements. This function receives a parameter, which is the index of the element it will display. function carousel(review) { let reviews = document.getElementsByClassName("review__items"); if(review>=reviews.length){ review=0; rev=0; } if(review<0){ review=reviews.length-1; rev=reviews.length-1; } for (let i = 0; i < reviews.length; i++) { reviews[i].style.display = "none"; } reviews[review].style.display="block"; } To display the specified index, first, it will hide all reviews by setting their display to none using a simple for loop, and for a specific index, it will display information by setting its display to block. Note: Conditional statements are responsible for the cyclic way of the carousel, if the parameter is negative it will set the parameter to the last index, and if the parameter is greater than or equal to the last index it will set the parameter to the first index. perviousReview function: This function will be executed when the previous button is clicked, it decreases the variable by 1, then it will be passed to the carousel function. function previousReview() { rev = rev - 1; carousel(rev); } nextReview function: This function will be executed when the next button is clicked, it increases the variable by 1, then it will be passed to the carousel function. function nextReview() { rev = rev + 1; carousel(rev); } Complete Code: HTML <!DOCTYPE html><html lang="en"> <head> <title>Review Carousel</title> <style> .review { background: rgb(145, 226, 188); height: auto; width: 270px; border-radius: 15px; margin: auto; padding: 10px; margin-top: 30px; box-shadow: 5px 5px 5px #32917d; align-items: center; } .review__items { align-items: center; justify-content: space-evenly; width: 250px; padding: 10px; align-items: center; } .review__items img { height: 250px; width: 250px; border-radius: 5px; box-shadow: rgba(0, 0, 0, 0.35) 0px 4px 15px; } .review__items h1 { font-family: Verdana, Geneva, Tahoma, sans-serif; font-size: 20px; } .review__items p { font-family: Verdana, Geneva, Tahoma, sans-serif; font-size: 14px; } .review__button { text-align: center; padding: 10px; } .review__button button { color: rgb(192, 229, 192); background: green; font-weight: bold; } .review__items { display: none; } </style></head> <body> <div class="review"> <div class="review__items"> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" /> <h1>GeeksforGeeks</h1> <p> Let's learn to create a review carousel using JavaScript. </p> </div> <div class="review__items"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20210101144014/gfglogo.png" /> <h1>Geek Here</h1> <p> Very useful site to learn cool stuff. Improve your skills. </p> </div> <div class="review__items"> <img src="https://media.geeksforgeeks.org/img-practice/courses/GfG_Logo.png" /> <h1>Hello there!</h1> <p> Have a nice day, Please visit us again. Nice to meet you <p> </div> <div class="review__button"> <button id="prev" onclick="previousReview()"> PREV </button> <button id="next" onclick="nextReview()"> NEXT </button> </div> </div> <script> let rev = 0; carousel(rev); function previousReview() { rev = rev - 1; carousel(rev); } function nextReview() { rev = rev + 1; carousel(rev); } function carousel(review) { let reviews = document .getElementsByClassName("review__items"); if (review >= reviews.length) { review = 0; rev = 0; } if (review < 0) { review = reviews.length - 1; rev = reviews.length - 1; } for (let i = 0; i < reviews.length; i++) { reviews[i].style.display = "none"; } reviews[review].style.display = "block"; } </script></body> </html> Output: CSS-Properties CSS-Questions HTML-Questions javascript-functions JavaScript-Questions Picked CSS HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Design a web page using HTML and CSS Form validation using jQuery REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 54, "s": 26, "text": "\n12 Aug, 2021" }, { "code": null, "e": 323, "s": 54, "text": "In this article, we have created a review carousel using JavaScript. We have also used basic HTMM and CSS for styling. A carousel is basically a type of slideshow used to dis...
SWING - ActionListener Interface
The class which processes the ActionEvent should implement this interface. The object of that class must be registered with a component. The object can be registered using the addActionListener() method. When the action event occurs, that object's actionPerformed method is invoked. Following is the declaration for java.awt.event.ActionListener interface − public interface ActionListener extends EventListener void actionPerformed(ActionEvent e) Invoked when an action occurs. This interface inherits methods from the following interfaces − java.awt.EventListener Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui > SwingListenerDemo.java package com.tutorialspoint.gui; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SwingListenerDemo { private JFrame mainFrame; private JLabel headerLabel; private JLabel statusLabel; private JPanel controlPanel; public SwingListenerDemo(){ prepareGUI(); } public static void main(String[] args){ SwingListenerDemo swingListenerDemo = new SwingListenerDemo(); swingListenerDemo.showActionListenerDemo(); } private void prepareGUI(){ mainFrame = new JFrame("Java SWING Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); headerLabel = new JLabel("",JLabel.CENTER ); statusLabel = new JLabel("",JLabel.CENTER); statusLabel.setSize(350,100); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); controlPanel = new JPanel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showActionListenerDemo(){ headerLabel.setText("Listener in action: ActionListener"); JPanel panel = new JPanel(); panel.setBackground(Color.magenta); JButton okButton = new JButton("OK"); okButton.addActionListener(new CustomActionListener()); panel.add(okButton); controlPanel.add(panel); mainFrame.setVisible(true); } class CustomActionListener implements ActionListener{ public void actionPerformed(ActionEvent e) { statusLabel.setText("Ok Button Clicked."); } } } Compile the program using the command prompt. Go to D:/ > SWING and type the following command. D:\SWING>javac com\tutorialspoint\gui\SwingListenerDemo.java If no error occurs, it means the compilation is successful. Run the program using the following command. D:\SWING>java com.tutorialspoint.gui.SwingListenerDemo Verify the following output.
[ { "code": null, "e": 2180, "s": 1897, "text": "The class which processes the ActionEvent should implement this interface. The object of that class must be registered with a component. The object can be registered using the addActionListener() method. When the action event occurs, that object's actio...
Reverse the Words of a String using Stack
30 Jun, 2021 Given string str consisting of multiple words, the task is to reverse the entire string word by word.Examples: Input: str = “I Love To Code” Output: Code To Love IInput: str = “data structures and algorithms” Output: algorithms and structures data Approach: This problem can be solved not only with the help of the strtok() but also it can be solved by using Stack Container Class in STL C++ by following the given steps: Create an empty stack.Traverse the entire string, while traversing add the characters of the string into a temporary variable until you get a space(‘ ‘) and push that temporary variable into the stack.Repeat the above step until the end of the string.Pop the words from the stack until the stack is not empty which will be in reverse order. Create an empty stack. Traverse the entire string, while traversing add the characters of the string into a temporary variable until you get a space(‘ ‘) and push that temporary variable into the stack. Repeat the above step until the end of the string. Pop the words from the stack until the stack is not empty which will be in reverse order. Below is the implementation of the above approach: C++ Java Python3 C# Javascript //C++ implementation of the above approach#include<bits/stdc++.h>using namespace std; //function to reverse the words//of the given string without using strtok().void reverse(string s){ //create an empty string stack stack<string> stc; //create an empty temporary string string temp=""; //traversing the entire string for(int i=0;i<s.length();i++) { if(s[i]==' ') { //push the temporary variable into the stack stc.push(temp); //assigning temporary variable as empty temp=""; } else { temp=temp+s[i]; } } //for the last word of the string stc.push(temp); while(!stc.empty()) { // Get the words in reverse order temp=stc.top(); cout<<temp<<" "; stc.pop(); } cout<<endl;} //Driver codeint main(){ string s="I Love To Code"; reverse(s); return 0;}// This code is contributed by Konderu Hrishikesh. //Java implementation of// the above approachimport java.util.*;class GFG{ // Function to reverse the words// of the given String without// using strtok().static void reverse(String s){ // Create an empty String stack Stack<String> stc = new Stack<>(); // Create an empty temporary String String temp = ""; // Traversing the entire String for(int i = 0; i < s.length(); i++) { if(s.charAt(i) == ' ') { // Push the temporary // variable into the stack stc.add(temp); // Assigning temporary // variable as empty temp = ""; } else { temp = temp + s.charAt(i); } } // For the last word // of the String stc.add(temp); while(!stc.isEmpty()) { // Get the words in // reverse order temp = stc.peek(); System.out.print(temp + " "); stc.pop(); } System.out.println();} //Driver codepublic static void main(String[] args){ String s = "I Love To Code"; reverse(s);}} // This code is contributed by gauravrajput1 # Python3 implementation of# the above approach # function to reverse the# words of the given string# without using strtok().def reverse(s): # create an empty string # stack stc = [] # create an empty temporary # string temp = "" # traversing the entire string for i in range(len(s)): if s[i] == ' ': # push the temporary variable # into the stack stc.append(temp) # assigning temporary variable # as empty temp = "" else: temp = temp + s[i] # for the last word of the string stc.append(temp) while len(stc) != 0: # Get the words in reverse order temp = stc[len(stc) - 1] print(temp, end = " ") stc.pop() print() # Driver codes = "I Love To Code"reverse(s) # This code is contributed by divyeshrabadiya07 // C# implementation of// the above approachusing System;using System.Collections; class GFG{ // Function to reverse the words // of the given String without // using strtok(). static void reverse(string s) { // Create an empty String stack Stack stc = new Stack(); // Create an empty temporary String string temp = ""; // Traversing the entire String for(int i = 0; i < s.Length; i++) { if(s[i] == ' ') { // Push the temporary // variable into the stack stc.Push(temp); // Assigning temporary // variable as empty temp = ""; } else { temp = temp + s[i]; } } // For the last word // of the String stc.Push(temp); while(stc.Count != 0) { // Get the words in // reverse order temp = (string)stc.Peek(); Console.Write(temp + " "); stc.Pop(); } Console.WriteLine(); } // Driver code static void Main() { string s = "I Love To Code"; reverse(s); }} // This code is contributed by divyesh072019 <script> // Javascript implementation of // the above approach // Function to reverse the words // of the given String without // using strtok(). function reverse(s) { // Create an empty String stack let stc = []; // Create an empty temporary String let temp = ""; // Traversing the entire String for(let i = 0; i < s.length; i++) { if(s[i] == ' ') { // Push the temporary // variable into the stack stc.push(temp); // Assigning temporary // variable as empty temp = ""; } else { temp = temp + s[i]; } } // For the last word // of the String stc.push(temp); while(stc.length != 0) { // Get the words in // reverse order temp = stc[stc.length - 1]; document.write(temp + " "); stc.pop(); } } let s = "I Love To Code"; reverse(s); </script> Code To Love I Time Complexity: O(N) Another Approach: An approach without using stack is discussed here. This problem can also be solved using stack by following the below steps: Create an empty stack.Tokenize the input string into words using spaces as separator with the help of strtok()Push the words into the stack.Pop the words from the stack until the stack is not empty which will be in reverse order. Create an empty stack. Tokenize the input string into words using spaces as separator with the help of strtok() Push the words into the stack. Pop the words from the stack until the stack is not empty which will be in reverse order. 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; // Function to reverse the words// of the given sentencevoid reverse(char k[]){ // Create an empty character array stack stack<char*> s; char* token = strtok(k, " "); // Push words into the stack while (token != NULL) { s.push(token); token = strtok(NULL, " "); } while (!s.empty()) { // Get the words in reverse order cout << s.top() << " "; s.pop(); }} // Driver codeint main(){ char k[] = "geeks for geeks"; reverse(k); return 0;} // Java implementation of the approachimport java.util.Arrays;import java.util.Stack; class GFG { // Function to reverse the words // of the given sentence static void reverse(String k) { // Create an empty character array stack Stack<String> s = new Stack<>(); String[] token = k.split(" "); // Push words into the stack for (int i = 0; i < token.length; i++) { s.push(token[i]); } while (!s.empty()) { // Get the words in reverse order System.out.print(s.peek() + " "); s.pop(); } } // Driver code public static void main(String[] args) { String k = "geeks for geeks"; reverse(k); }} // This code is contributed by Rajput-Ji # Python3 implementation of the approach # Function to reverse the words# of the given sentencedef reverse(k): # Create an empty character array stack s = [] token = k.split() # Push words into the stack for word in token : s.append(word); while (len(s)) : # Get the words in reverse order print(s.pop(), end = " "); # Driver codeif __name__ == "__main__" : k = "geeks for geeks"; reverse(k); # This code is contributed by AnkitRai01 // C# implementation of the approachusing System;using System.Collections.Generic; class GFG { // Function to reverse the words // of the given sentence static void reverse(String k) { // Create an empty character array stack Stack<String> s = new Stack<String>(); String[] token = k.Split(' '); // Push words into the stack for (int i = 0; i < token.Length; i++) { s.Push(token[i]); } while (s.Count != 0) { // Get the words in reverse order Console.Write(s.Peek() + " "); s.Pop(); } } // Driver code public static void Main(String[] args) { String k = "geeks for geeks"; reverse(k); }} // This code is contributed by PrinciRaj1992 <script> // JavaScript implementation of the approach // Function to reverse the words // of the given sentence function reverse(k) { // Create an empty character array stack let s = []; let token = k.split(" "); // Push words into the stack for (let i = 0; i < token.length; i++) { s.push(token[i]); } while (s.length > 0) { // Get the words in reverse order document.write(s[s.length - 1] + " "); s.pop(); } } // Driver code let k = "geeks for geeks"; reverse(k); </script> geeks for geeks Time Complexity: O(N) Rajput-Ji ankthon princiraj1992 hrishikeshkonderu GauravRajput1 divyeshrabadiya07 divyesh072019 mukesh07 vaibhavrabadiya117 Stack Strings Strings Stack 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 Design a stack with operations on middle element How to efficiently implement k stacks in a single array? Next Smaller Element 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 Different Methods to Reverse a String in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n30 Jun, 2021" }, { "code": null, "e": 167, "s": 54, "text": "Given string str consisting of multiple words, the task is to reverse the entire string word by word.Examples: " }, { "code": null, "e": 306, "s": 167, "...
ML | Logistic Regression using Python
09 Jun, 2022 User Database – This dataset contains information about users from a company’s database. It contains information about UserID, Gender, Age, EstimatedSalary, and Purchased. We are using this dataset for predicting whether a user will purchase the company’s newly launched product or not. Prerequisite: Understanding Logistic Regression Do refer to the below table from where data is being fetched from the dataset. Let us make the Logistic Regression model, predicting whether a user will purchase the product or not. Inputting Libraries. import pandas as pd import numpy as np import matplotlib.pyplot as plt Python3 dataset = pd.read_csv("User_Data.csv") Now, to predict whether a user will purchase the product or not, one needs to find out the relationship between Age and Estimated Salary. Here User ID and Gender are not important factors for finding out this. Python3 # inputx = dataset.iloc[:, [2, 3]].values # outputy = dataset.iloc[:, 4].values Splitting the dataset to train and test. 75% of data is used for training the model and 25% of it is used to test the performance of our model. Python3 from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(x, y, test_size = 0.25, random_state = 0) Now, it is very important to perform feature scaling here because Age and Estimated Salary values lie in different ranges. If we don’t scale the features then the Estimated Salary feature will dominate the Age feature when the model finds the nearest neighbor to a data point in the data space. Python3 from sklearn.preprocessing import StandardScalersc_x = StandardScaler()xtrain = sc_x.fit_transform(xtrain)xtest = sc_x.transform(xtest) print (xtrain[0:10, :]) Output: [[ 0.58164944 -0.88670699] [-0.60673761 1.46173768] [-0.01254409 -0.5677824 ] [-0.60673761 1.89663484] [ 1.37390747 -1.40858358] [ 1.47293972 0.99784738] [ 0.08648817 -0.79972756] [-0.01254409 -0.24885782] [-0.21060859 -0.5677824 ] [-0.21060859 -0.19087153]] Here once see that Age and Estimated salary features values are scaled and now there in the -1 to 1. Hence, each feature will contribute equally to decision making i.e. finalizing the hypothesis. Finally, we are training our Logistic Regression model. Python3 from sklearn.linear_model import LogisticRegressionclassifier = LogisticRegression(random_state = 0)classifier.fit(xtrain, ytrain) After training the model, it is time to use it to do predictions on testing data. Python3 y_pred = classifier.predict(xtest) Let’s test the performance of our model – Confusion Matrix Metrics are used to check the model performance on predicted values and actual values. Python3 from sklearn.metrics import confusion_matrixcm = confusion_matrix(ytest, y_pred) print ("Confusion Matrix : \n", cm) Output: Confusion Matrix : [[65 3] [ 8 24]] Out of 100 : True Positive + True Negative = 65 + 24 False Positive + False Negative = 3 + 8Performance measure – Accuracy Example Python3 from sklearn.metrics import accuracy_scoreprint ("Accuracy : ", accuracy_score(ytest, y_pred)) Output: Accuracy : 0.89 Python3 from matplotlib.colors import ListedColormapX_set, y_set = xtest, ytestX1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01), np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01)) plt.contourf(X1, X2, classifier.predict( np.array([X1.ravel(), X2.ravel()]).T).reshape( X1.shape), alpha = 0.75, cmap = ListedColormap(('red', 'green'))) plt.xlim(X1.min(), X1.max())plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c = ListedColormap(('red', 'green'))(i), label = j) plt.title('Classifier (Test set)')plt.xlabel('Age')plt.ylabel('Estimated Salary')plt.legend()plt.show() Output: Analyzing the performance measures – accuracy and confusion matrix and the graph, we can clearly say that our model is performing really well. anshumankvkanshu76 ramankumar41 jaintarun Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Information Retrieval? Support Vector Machine Algorithm Random Forest Regression in Python Elbow Method for optimal value of k in KMeans Introduction to Recurrent Neural Network Iterate over a list in Python How to iterate through Excel rows in Python? Read JSON file using Python Python map() function Enumerate() in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Jun, 2022" }, { "code": null, "e": 339, "s": 52, "text": "User Database – This dataset contains information about users from a company’s database. It contains information about UserID, Gender, Age, EstimatedSalary, and Purchased. We...
How to concatenate two JavaScript objects with plain JavaScript ?
Suppose we have two objects defined like this − const obj1 = { id1: 21, name1: "Kailash" }; const obj2 = { id2: 20, name2: "Shankar" }; We are required to write a JavaScript function that takes in two such objects and merges into a single object. In other words, we are required to more or less implement the functionality of Object.assign() function. The code for this will be − const obj1 = { id1: 21, name1: "Kailash" }; const obj2 = { id2: 20, name2: "Shankar" }; const concatObjects = (...sources) => { const target = {}; sources.forEach(el => { Object.keys(el).forEach(key => { target[key] = el[key]; }); }); return target; } console.log(concatObjects(obj1, obj2)); And the output in the console will be − { id1: 21, name1: 'Kailash', id2: 20, name2: 'Shankar' }
[ { "code": null, "e": 1235, "s": 1187, "text": "Suppose we have two objects defined like this −" }, { "code": null, "e": 1335, "s": 1235, "text": "const obj1 = {\n id1: 21,\n name1: \"Kailash\"\n};\nconst obj2 = {\n id2: 20,\n name2: \"Shankar\"\n};" }, { "code": n...
List equals() Method in Java with Examples
02 Jan, 2019 This method is used to compare two lists. It compares the lists as, both lists should have the same size, and all corresponding pairs of elements in the two lists are equal. Syntax: boolean equals(Object o) Parameters: This function has a single parameter which is object to be compared for equality. Returns: This method returns True if lists are equal. Below programs show the implementation of this method. Program 1: // Java code to show the implementation of// addAll method in list interfaceimport java.util.*;public class GfG { // Driver code public static void main(String[] args) { // Initializing a list of type Linkedlist List<Integer> l = new LinkedList<>(); l.add(10); l.add(15); l.add(20); System.out.println(l); // Initializing another list List<Integer> l2 = new ArrayList<Integer>(); l2.add(100); l2.add(200); l2.add(300); System.out.println(l2); if (l.equals(l2)) System.out.println("Equal"); else System.out.println("Not equal"); }} [10, 15, 20] [100, 200, 300] Not equal Program 2: Below is the code to show implementation of list.addAll() using Linkedlist. // Java code to show the implementation of// addAll method in list interfaceimport java.util.*;public class GfG { // Driver code public static void main(String[] args) { // Initializing a list of type Linkedlist List<Integer> l = new LinkedList<>(); l.add(10); l.add(15); l.add(20); System.out.println(l); // Initializing another list List<Integer> l2 = new ArrayList<Integer>(); l2.add(10); l2.add(15); l2.add(20); System.out.println(l2); if (l.equals(l2)) System.out.println("Equal"); else System.out.println("Not equal"); }} [10, 15, 20] [10, 15, 20] Equal Reference:Oracle Docs Java - util package Java-Collections Java-Functions java-list Java Java Java-Collections 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": "\n02 Jan, 2019" }, { "code": null, "e": 202, "s": 28, "text": "This method is used to compare two lists. It compares the lists as, both lists should have the same size, and all corresponding pairs of elements in the two lists are equal." ...
A Space Optimized Solution of LCS
01 Jul, 2022 Given two strings, find the length of the longest subsequence present in both of them. Examples: LCS for input Sequences “ABCDGH” and “AEDFHR” is “ADH” of length 3. LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4. We have discussed a typical dynamic programming-based solution for LCS. We can optimize the space used by LCS problem. We know the recurrence relationship of the LCS problem is CPP Java C# Javascript /* Returns length of LCS for X[0..m-1], Y[0..n-1] */int lcs(string &X, string &Y){ int m = X.length(), n = Y.length(); int L[m+1][n+1]; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (int i=0; i<=m; i++) { for (int j=0; j<=n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i-1] == Y[j-1]) L[i][j] = L[i-1][j-1] + 1; else L[i][j] = max(L[i-1][j], L[i][j-1]); } } /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ return L[m][n];} class GFG { // Returns length of LCS for X[0..m-1], Y[0..n-1] public static int lcs(String X, String Y) { // Find lengths of two strings int m = X.length(), n = Y.length(); int L[][] = new int[m + 1][n + 1]; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i - 1] == Y[j - 1]) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = max(L[i - 1][j], L[i][j - 1]); } } /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ return L[m][n]; }} // This code is contributed by rajsanghavi9. // C# program to implement// the above approachusing System; class GFG{ // Returns length of LCS for X[0..m-1], Y[0..n-1] public static int lcs(string X, string Y) { // Find lengths of two strings int m = X.Length, n = Y.Length; int[,] L = new int[m + 1, n + 1]; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i, j] = 0; else if (X[i - 1] == Y[j - 1]) L[i, j] = L[i - 1, j - 1] + 1; else L[i, j] = Math.Max(L[i - 1, j], L[i, j - 1]); } } /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ return L[m, n]; } } // this code is contributed by code_hunt. <script> // Dynamic Programming Java implementation of LCS problem // Utility function to get max of 2 integersfunction max(a, b){ if (a > b) return a; else return b;} // Returns length of LCS for X[0..m-1], Y[0..n-1]function lcs(X, Y, m, n){ var L = new Array(m + 1); for(var i = 0; i < L.length; i++) { L[i] = new Array(n + 1); } var i, j; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for(i = 0; i <= m; i++) { for(j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i - 1] == Y[j - 1]) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = max(L[i - 1][j], L[i][j - 1]); } } /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ return L[m][n];} // This code is contributed by akshitsaxenaa09.</script> How to find the length of LCS is O(n) auxiliary space? We strongly recommend that you click here and practice it, before moving on to the solution.One important observation in the above simple implementation is, in each iteration of the outer loop we only need values from all columns of the previous row. So there is no need to store all rows in our DP matrix, we can just store two rows at a time and use them. In that way, used space will be reduced from L[m+1][n+1] to L[2][n+1]. Below is the implementation of the above idea. C++ Java Python3 C# PHP Javascript // Space optimized C++ implementation// of LCS problem#include<bits/stdc++.h>using namespace std; // Returns length of LCS// for X[0..m-1], Y[0..n-1]int lcs(string &X, string &Y){ // Find lengths of two strings int m = X.length(), n = Y.length(); int L[2][n + 1]; // Binary index, used to // index current row and // previous row. bool bi; for (int i = 0; i <= m; i++) { // Compute current // binary index bi = i & 1; for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) L[bi][j] = 0; else if (X[i-1] == Y[j-1]) L[bi][j] = L[1 - bi][j - 1] + 1; else L[bi][j] = max(L[1 - bi][j], L[bi][j - 1]); } } // Last filled entry contains // length of LCS // for X[0..n-1] and Y[0..m-1] return L[bi][n];} // Driver codeint main(){ string X = "AGGTAB"; string Y = "GXTXAYB"; printf("Length of LCS is %d\n", lcs(X, Y)); return 0;} // Java Code for A Space Optimized// Solution of LCS class GFG { // Returns length of LCS // for X[0..m - 1], // Y[0..n - 1] public static int lcs(String X, String Y) { // Find lengths of two strings int m = X.length(), n = Y.length(); int L[][] = new int[2][n+1]; // Binary index, used to index // current row and previous row. int bi=0; for (int i = 0; i <= m; i++) { // Compute current binary index bi = i & 1; for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) L[bi][j] = 0; else if (X.charAt(i - 1) == Y.charAt(j - 1)) L[bi][j] = L[1 - bi][j - 1] + 1; else L[bi][j] = Math.max(L[1 - bi][j], L[bi][j - 1]); } } // Last filled entry contains length of // LCS for X[0..n-1] and Y[0..m-1] return L[bi][n]; } // Driver Code public static void main(String[] args) { String X = "AGGTAB"; String Y = "GXTXAYB"; System.out.println("Length of LCS is " + lcs(X, Y)); }} // This code is contributed by Arnav Kr. Mandal. # Space optimized Python# implementation of LCS problem # Returns length of LCS for# X[0..m-1], Y[0..n-1]def lcs(X, Y): # Find lengths of two strings m = len(X) n = len(Y) L = [[0 for i in range(n+1)] for j in range(2)] # Binary index, used to index current row and # previous row. bi = bool for i in range(m): # Compute current binary index bi = i&1 for j in range(n+1): if (i == 0 or j == 0): L[bi][j] = 0 elif (X[i] == Y[j - 1]): L[bi][j] = L[1 - bi][j - 1] + 1 else: L[bi][j] = max(L[1 - bi][j], L[bi][j - 1]) # Last filled entry contains length of LCS # for X[0..n-1] and Y[0..m-1] return L[bi][n] # Driver CodeX = "AGGTAB"Y = "GXTXAYB" print("Length of LCS is", lcs(X, Y)) # This code is contributed by Soumen Ghosh. // C# Code for A Space// Optimized Solution of LCSusing System; class GFG{ // Returns length of LCS // for X[0..m - 1], // Y[0..n - 1] public static int lcs(string X, string Y) { // Find lengths of // two strings int m = X.Length, n = Y.Length; int [,]L = new int[2, n + 1]; // Binary index, used to // index current row and // previous row. int bi = 0; for (int i = 0; i <= m; i++) { // Compute current // binary index bi = i & 1; for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) L[bi, j] = 0; else if (X[i - 1] == Y[j - 1]) L[bi, j] = L[1 - bi, j - 1] + 1; else L[bi, j] = Math.Max(L[1 - bi, j], L[bi, j - 1]); } } // Last filled entry contains // length of LCS for X[0..n-1] // and Y[0..m-1] return L[bi, n]; } // Driver Code public static void Main() { string X = "AGGTAB"; string Y = "GXTXAYB"; Console.Write("Length of LCS is " + lcs(X, Y)); }} // This code is contributed// by shiv_bhakt. <?php// Space optimized PHP implementation// of LCS problem // Returns length of LCS// for X[0..m-1], Y[0..n-1]function lcs($X, $Y){ // Find lengths of two strings $m = strlen($X); $n = strlen($Y); $L = array(array()); // Binary index, used to index // current row and previous row. for ($i = 0; $i <= $m; $i++) { // Compute current binary index $bi = $i & 1; for ($j = 0; $j <= $n; $j++) { if ($i == 0 || $j == 0) $L[$bi][$j] = 0; else if ($X[$i - 1] == $Y[$j - 1]) $L[$bi][$j] = $L[1 - $bi][$j - 1] + 1; else $L[$bi][$j] = max($L[1 - $bi][$j], $L[$bi][$j - 1]); } } // Last filled entry contains // length of LCS // for X[0..n-1] and Y[0..m-1] return $L[$bi][$n];} // Driver code$X = "AGGTAB";$Y = "GXTXAYB"; echo "Length of LCS is : ", lcs($X, $Y); // This code is contributed by Ryuga?> <script> // Javascript Code for A Space Optimized Solution of LCS // Returns length of LCS // for X[0..m - 1], // Y[0..n - 1] function lcs(X, Y) { // Find lengths of two strings let m = X.length, n = Y.length; let L = new Array(2); for (let i = 0; i < 2; i++) { L[i] = new Array(n + 1); for (let j = 0; j < n + 1; j++) { L[i][j] = 0; } } // Binary index, used to index // current row and previous row. let bi=0; for (let i = 0; i <= m; i++) { // Compute current binary index bi = i & 1; for (let j = 0; j <= n; j++) { if (i == 0 || j == 0) L[bi][j] = 0; else if (X[i - 1] == Y[j - 1]) L[bi][j] = L[1 - bi][j - 1] + 1; else L[bi][j] = Math.max(L[1 - bi][j], L[bi][j - 1]); } } // Last filled entry contains length of // LCS for X[0..n-1] and Y[0..m-1] return L[bi][n]; } let X = "AGGTAB"; let Y = "GXTXAYB"; document.write("Length of LCS is " + lcs(X, Y)); </script> Length of LCS is 4 Time Complexity : O(m*n) Auxiliary Space : O(n) This article is contributed Shivam Mittal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. We can further improve the space complexity of above program Python3 Java def lcs(text1, text2): m, n = len(text1), len(text2) if m > n : text1, text2 = text2, text1 dp = [0] * (n + 1) for c in text1: prev = 0 for i, d in enumerate(text2): prev, dp[i + 1] = dp[i + 1], prev + 1 if c == d else max(dp[i], dp[i + 1]) return dp[-1]X = "AGGTAB"Y = "GXTXAYB" print("Length of LCS is", lcs(X, Y)) /*package whatever //do not write package name here */class GFG { public static int lcs(String text1, String text2) { int[] dp = new int[text2.length()+1]; for(int i = 0; i< text1.length(); i++){ int prev = dp[0]; for(int j = 1; j < dp.length; j++){ int temp = dp[j]; if(text1.charAt(i) != text2.charAt(j-1)){ dp[j] = Math.max(dp[j-1], dp[j]); }else{ dp[j] = prev +1; } prev = temp; } } return dp[dp.length-1]; } public static void main(String[] args) { String X = "AGGTAB"; String Y = "GXTXAYB"; System.out.println("Length of LCS is " + lcs(X, Y)); }} Length of LCS is 4 Vishal_Khoda ankthon divyeshrabadiya07 rajsanghavi9 akshitsaxenaa09 code_hunt tusharkhera1 LCS subsequence Dynamic Programming Dynamic Programming LCS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Find if there is a path between two vertices in an undirected graph Count number of binary strings without consecutive 1's Optimal Substructure Property in Dynamic Programming | DP-2 Find if a string is interleaved of two other strings | DP-33 Maximum sum such that no two elements are adjacent How to solve a Dynamic Programming Problem ? Word Break Problem | DP-32 Maximum profit by buying and selling a share at most twice Unique paths in a Grid with Obstacles Palindrome Partitioning | DP-17
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Jul, 2022" }, { "code": null, "e": 143, "s": 54, "text": "Given two strings, find the length of the longest subsequence present in both of them. " }, { "code": null, "e": 154, "s": 143, "text": "Examples: " },...
info command in Linux with Examples
22 May, 2019 infocommand reads documentation in the info format. It will give detailed information for a command when compared with the man page. The pages are made using the texinfo tools because of which it can link with other pages, create menus and easy navigation. Syntax: info [OPTION]... [MENU-ITEM...] Options: -a, –all: It use all matching manuals. -k, –apropos=STRING: It look up STRING in all indices of all manuals. -d, –directory=DIR: It add DIR to INFOPATH. -f, –file=MANUAL: It specify Info manual to visit. -h, –help: It display this help and exit. -n, –node=NODENAME: It specify nodes in first visited Info file. -o, –output=FILE: It output selected nodes to FILE. -O, –show-options, –usage: It go to command-line options node. -v, –variable VAR=VALUE: It assign VALUE to Info variable VAR. –version: It display version information and exit. -w, –where, –location: It print physical location of Info file. Examples: -a : It use all matching manuals and display them for a particular command. info -a cvs info -a cvs -k : It look up STRING in all indices of all manuals and then display the same. info -k cvs info -k cvs -d : It adds DIR to INFOPATH and also display the same. info -d cvs info -d cvs -O : It go to command-line options node for a particular command and display the same. info -O cvs info -O cvs -w Command : It print physical location of Info file. info -w cvs info -w cvs Note: To check for the manual page of info command, use the following command:man info man info To check the help page of info command, use the following command:info --help info --help linux-command Linux-system-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ZIP command in Linux with examples tar command in Linux with examples curl command in Linux with Examples Conditional Statements | Shell Script Tail command in Linux with examples TCP Server-Client implementation in C Docker - COPY Instruction scp command in Linux with Examples UDP Server-Client implementation in C echo command in Linux with Examples
[ { "code": null, "e": 28, "s": 0, "text": "\n22 May, 2019" }, { "code": null, "e": 285, "s": 28, "text": "infocommand reads documentation in the info format. It will give detailed information for a command when compared with the man page. The pages are made using the texinfo tools...
How to validate Hexadecimal Color Code using Regular Expression
04 Feb, 2021 Given string str, the task is to check whether the string is valid hexadecimal colour code or not by using Regular Expression. The valid hexadecimal color code must satisfy the following conditions. It should start from ‘#’ symbol.It should be followed by the letters from a-f, A-F and/or digits from 0-9.The length of the hexadecimal color code should be either 6 or 3, excluding ‘#’ symbol. It should start from ‘#’ symbol. It should be followed by the letters from a-f, A-F and/or digits from 0-9. The length of the hexadecimal color code should be either 6 or 3, excluding ‘#’ symbol. For example: #abc, #ABC, #000, #FFF, #000000, #FF0000, #00FF00, #0000FF, #FFFFFF are all valid Hexadecimal color codes.Examples: Input: str = “#1AFFa1”; Output: true Explanation: The given string satisfies all the above mentioned conditions.Input: str = “#F00”; Output: true Explanation: The given string satisfies all the above mentioned conditions.Input: str = “123456”; Output: false Explanation: The given string doesn’t start with a ‘#’ symbol, therefore it is not a valid hexadecimal color code.Input: str = “#123abce”; Output: false Explanation: The given string has length 7, the valid hexadecimal color code length should be either 6 or 3. Therefore it is not a valid hexadecimal color code.Input: str = “#afafah”; Output: false Explanation: The given string contains ‘h’, the valid hexadecimal color code should be followed by the letter from a-f, A-F. Therefore it is not a valid hexadecimal color code. Approach: This problem can be solved by using Regular Expression. Get the string. Create a regular expression to check valid hexadecimal color code as mentioned below: regex = "^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$"; Where: ^ represents the starting of the string.# represents the hexadecimal color code must start with a ‘#’ symbol.( represents the start of the group.[A-Fa-f0-9]{6} represents the letter from a-f, A-F, or digit from 0-9 with a length of 6.| represents the or.[A-Fa-f0-9]{3} represents the letter from a-f, A-F, or digit from 0-9 with a length of 3.) represents the end of the group.$ represents the ending of the string. ^ represents the starting of the string. # represents the hexadecimal color code must start with a ‘#’ symbol. ( represents the start of the group. [A-Fa-f0-9]{6} represents the letter from a-f, A-F, or digit from 0-9 with a length of 6. | represents the or. [A-Fa-f0-9]{3} represents the letter from a-f, A-F, or digit from 0-9 with a length of 3. ) represents the end of the group. $ represents the ending of the string. Match the given string with the regex, in Java, this can be done by using Pattern.matcher(). Return true if the string matches with the given regex, else return false. Below is the implementation of the above approach: C++ Java Python3 // C++ program to validate the// hexadecimal color code using Regular Expression#include <iostream>#include <regex>using namespace std; // Function to validate the hexadecimal color code.bool isValidHexaCode(string str){ // Regex to check valid hexadecimal color code. const regex pattern("^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$"); // If the hexadecimal color code // is empty return false if (str.empty()) { return false; } // Return true if the hexadecimal color code // matched the ReGex if(regex_match(str, pattern)) { return true; } else { return false; }} // Driver Codeint main(){ // Test Case 1: string str1 = "#1AFFa1"; cout << str1 + ": " << isValidHexaCode(str1) << endl; // Test Case 2: string str2 = "#F00"; cout << str2 + ": " << isValidHexaCode(str2) << endl; // Test Case 3: string str3 = "123456"; cout << str3 + ": " << isValidHexaCode(str3) << endl; // Test Case 4: string str4 = "#123abce"; cout << str4 + ": " << isValidHexaCode(str4) << endl; // Test Case 5: string str5 = "#afafah"; cout << str5 + ": " << isValidHexaCode(str5) << endl; return 0;} // This code is contributed by yuvraj_chandra // Java program to validate hexadecimal// colour code using Regular Expression import java.util.regex.*; class GFG { // Function to validate hexadecimal color code . public static boolean isValidHexaCode(String str) { // Regex to check valid hexadecimal color code. String regex = "^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$"; // 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 matching between 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 = "#1AFFa1"; System.out.println( str1 + ": " + isValidHexaCode(str1)); // Test Case 2: String str2 = "#F00"; System.out.println( str2 + ": " + isValidHexaCode(str2)); // Test Case 3: String str3 = "123456"; System.out.println( str3 + ": " + isValidHexaCode(str3)); // Test Case 4: String str4 = "#123abce"; System.out.println( str4 + ": " + isValidHexaCode(str4)); // Test Case 5: String str5 = "#afafah"; System.out.println( str5 + ": " + isValidHexaCode(str5)); }} # Python3 program to validate# hexadecimal colour code using# Regular Expressionimport re # Function to validate# hexadecimal color code .def isValidHexaCode(str): # Regex to check valid # hexadecimal color code. regex = "^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$" # 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 = "#1AFFa1"print(str1, ":", isValidHexaCode(str1)) # Test Case 2:str2 = "#F00"print(str2, ":", isValidHexaCode(str2)) # Test Case 3:str3 = "123456"print(str3, ":", isValidHexaCode(str3)) # Test Case 4:str4 = "#123abce"print(str4, ":", isValidHexaCode(str4)) # Test Case 5:str5 = "#afafah"print(str5, ":", isValidHexaCode(str5)) # This code is contributed by avanitrachhadiya2155 #1AFFa1: true #F00: true 123456: false #123abce: false #afafah: false avanitrachhadiya2155 yuvraj_chandra CPP-regex java-regular-expression Pattern Searching Strings Strings Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Feb, 2021" }, { "code": null, "e": 155, "s": 28, "text": "Given string str, the task is to check whether the string is valid hexadecimal colour code or not by using Regular Expression." }, { "code": null, "e": 229, "s...
limits.conf File To Limit Users, Process In Linux With Examples
09 Nov, 2021 Linux gives full control over the system. In this article, we are going to learn about the file limits.conf. limits.conf is a configuration that is used to limit the resources to the user, groups. Now let’s understand the file structure of limits.conf and how can we use the limits.conf to limit resources to the user. Before moving further, note that to edit this file, you must have root permission. The complete path of the limits.config is : /etc/security/limits.conf pam_module is a module that uses ulimit command to apply limits from limits.conf file. The basic syntax of the limits.conf file is : <domain><type><item><value> Now let’s understand each field on by one In this field, we need to name whom we are going to limit. The following can be values of this field username group name * specifies all userid groupid In this field, we mention which type of limits we are going to apply to the mentioned domain. This field has two values, soft or hard Hard: The user can not cross the mentioned values. Soft: User can cross the mentioned value till previse Hard value. This field mentions which resource we are going to limit for the mentioned domain. Here are some values for this field core: limits the core file size in KB data: maximum data size in KB fsize: maximum file size in KB stack: maximum stack size in KB cpu: maximum CPU time is minuted To see all values of this field, please read the man of limits.conf This field stores the values for the mentioned limit. Now let’s see how we can limit the user by using the limits.conf file. We are going to understand this by taking an example. So to limit users, we need to mention username as a domain field. In this example, GFG is the user. After that we have to mention the type of limit, in this example, we set hard type. Now to set items first we are needed to choose any item from the available item so in this example, we have chosen to use CPU item. Now we have to mention value the value of item CPU is must be in minutes, so for this example let’s mention the value as 10 minutes. Here is our limit : gfg hard cpu 10 To limit the group we can use the same format and value used for value and item but instead of username mention the group name. Here is one example with employee group employee hard nproc 30 We had seen the one domain as the * (asterisk). To apply the limit to the whole system, we can use this wildcard domain. Here is an example with a wildcard to apply limited number of logins on the system. * - maxsyslogins 20 After applying this limit, the maximum number of logins to the system is 20. When we want to specify one limit to the multiple users, but the users do not belong to the same group, we can specify the range of the user for which the limit has to apply. When we mention the user ID range, then the mentioned limit is applied to user IDs that belong to that range. To specify the range, use : operation. Here is an example: 1000:1020 hard nproc 50 This limit will be applied to the user IDs in the range of 1000 to 1020. Same as for user IDs, when we have to apply the same limit to multiple group IDs we can specify the range of group IDs. Use the : operator to mention the range. @500:505 soft cpu 10000 This limit will be applied to Group IDs in the range between 500 and 505. Now let’s explore more items than mentioned above list. There is one item called nproc by using this option we can limit the number for the user or group ID. So limit the number of processes for user gfg use the following limit. gfg hard nproc 50 After applying this limit, the user gfg will maximum own 50 processes. There is another item called cpu which is used to limit the CPU time for the mentioned user or group. So to limit the CPU time 1000 cycle to user gfg uses the following limit: gfg soft cpu 0000 nofile is an item by using which we can limit the maximum number of files that can be opened by the user. So to limit the maximum 227 number of files that can be opened by user gfg use the following limit gfg hard nofile 227 By default, systems allow us to unlimited logins on the system, but it can create a security issue. So to avoid the security issue, we can limit the number of logins of the user or group of users. We can use maxlogins item to limit the number of logins of users of groups to the system. So to limit 10 logins by the user group gfg, we can use the following limit: @gfg - maxlogins 10 In the previous example, we see how we can limit the number of logins of the user group to the system. Now to limit the maximum number of logins to the whole system we can use maxsyslogins item. So to limit 50 maximum number of logins to the system use the following limit: * - maxsyslogins 50 This limit is applied to the whole system and not for any specific user and group of users. We can limit the file size of the file by using the fsize item. This limit can be useful to restrict temp or similar usage type files. So to limit gfg having a single file size of 4 GB we can use the following limit: @gfg - fsize 4000000 The file size is presented in the KB. Use the different domains and items to apply different limits on the user, system, and groups. Now to know the limits on the process we can use the cat command with process PID to know process PID use ps command. cat /proc/PID/limits Here is example The output is the same as the limits.conf file fields. To know more about the limits.conf file setting use man command man limits.conf kashishsoda Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples chown command in Linux with Examples SED command in Linux | Set 2 mv command in Linux with examples nohup Command in Linux with Examples chmod command in Linux with examples Introduction to Linux Operating System Array Basics in Shell Scripting | Set 1 Basic Operators in Shell Scripting
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Nov, 2021" }, { "code": null, "e": 454, "s": 52, "text": "Linux gives full control over the system. In this article, we are going to learn about the file limits.conf. limits.conf is a configuration that is used to limit the resource...
Decorator Method – Python Design Patterns
24 Jan, 2022 Decorator Method is a Structural Design Pattern which allows you to dynamically attach new behaviors to objects without changing their implementation by placing these objects inside the wrapper objects that contains the behaviors. It is much easier to implement Decorator Method in Python because of its built-in feature. It is not equivalent to the Inheritance because the new feature is added only to that particular object, not to the entire subclass. Imagine We are working with a formatting tool that provides features likes Bold the text and Underlines the text. But after some time, our formatting tools got famous among the targeted audience and on taking the feedback we got that our audience wants more features in the application such as making the text Italic and many other features. Looks Simple? It’s not the easy task to implement this or to extend our classes to add more functionalities without disturbing the existing client code because we have to maintain the Single Responsibility Principle. Now let’s look at the solution that we have to avoid such conditions. Initially, we have only WrittenText but we have to apply filters like BOLD, ITALIC, UNDERLINE. So, we will create separate wrapper classes for each function like BoldWrapperClass, ItalicWrapperClass, and UnderlineWrapperclass. Decorator-Written-Text First, we will call BoldWrapperclass over the Written text which ultimately converts the text into BOLD letters Decorator-Wrapper Then we will apply the ItalicWrapperClass and UnderlineWrapperClass over the Bold text which will give us the result what we want. Decorator-Underline Following Code is written using Decorator Method: Python3 class WrittenText: """Represents a Written text """ def __init__(self, text): self._text = text def render(self): return self._text class UnderlineWrapper(WrittenText): """Wraps a tag in <u>""" def __init__(self, wrapped): self._wrapped = wrapped def render(self): return "<u>{}</u>".format(self._wrapped.render()) class ItalicWrapper(WrittenText): """Wraps a tag in <i>""" def __init__(self, wrapped): self._wrapped = wrapped def render(self): return "<i>{}</i>".format(self._wrapped.render()) class BoldWrapper(WrittenText): """Wraps a tag in <b>""" def __init__(self, wrapped): self._wrapped = wrapped def render(self): return "<b>{}</b>".format(self._wrapped.render()) """ main method """ if __name__ == '__main__': before_gfg = WrittenText("GeeksforGeeks") after_gfg = ItalicWrapper(UnderlineWrapper(BoldWrapper(before_gfg))) print("before :", before_gfg.render()) print("after :", after_gfg.render()) Following is the class diagram for Decorator Method: Decorator-Class-Diagram Single Responsibility Principle: It is easy to divide a monolithic class which implements many possible variants of behavior into several classes using the Decorator method. Runtime Responsibilities: We can easily add or remove the responsibilities from an object at runtime. SubClassing: The decorator pattern is an alternative to subclassing. Subclassing adds behavior at compile time, and the change affects all instances of the original class; decorating can provide new behavior at runtime for individual objects. removing Wrapper: It is very hard to remove a particular wrapper from the wrappers stack.Complicated Decorators: It can be complicated to have decorators keep track of other decorators, because to look back into multiple layers of the decorator chain starts to push the decorator pattern beyond its true intent.Ugly Configuration: Large number of code of layers might make the configurations ugly. removing Wrapper: It is very hard to remove a particular wrapper from the wrappers stack. Complicated Decorators: It can be complicated to have decorators keep track of other decorators, because to look back into multiple layers of the decorator chain starts to push the decorator pattern beyond its true intent. Ugly Configuration: Large number of code of layers might make the configurations ugly. Incapable Inheritance: Generally, Decorator method is used when it is not possible to extend the behavior of an object using the Inheritance.Runtime Assignment: One of the most important feature of Decorator method is to assign different and unique behaviors to the object at the Runtime. Incapable Inheritance: Generally, Decorator method is used when it is not possible to extend the behavior of an object using the Inheritance. Runtime Assignment: One of the most important feature of Decorator method is to assign different and unique behaviors to the object at the Runtime. Further Read – Decorator Design Pattern in Java avtarkumar719 as5853535 python-design-pattern Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jan, 2022" }, { "code": null, "e": 484, "s": 28, "text": "Decorator Method is a Structural Design Pattern which allows you to dynamically attach new behaviors to objects without changing their implementation by placing these objects ...
NumberFormat getIntegerInstance() method in Java with Examples
01 Apr, 2019 The getIntegerInstance() method is a built-in method of the java.text.NumberFormat returns an integer number format for the current default FORMAT locale.Syntax:public static final NumberFormat getIntegerInstance()Parameters: The function does not accepts any parameter.Return Value: The function returns the NumberFormat instance for general purpose formatting for integer values.Below is the implementation of the above function:Program 1:// Java program to implement// the above functionimport java.text.NumberFormat;import java.util.Locale;import java.util.Currency;public class Main { public static void main(String[] args) throws Exception { // Get the integer instance NumberFormat nF = NumberFormat.getIntegerInstance(); // 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 integer instance NumberFormat nF = NumberFormat .getIntegerInstance(); // 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#getIntegerInstance()The getIntegerIntegerInstance(Locale inLocale) method is a built-in method of the java.text.NumberFormat returns a integer number format for any specified locale.Syntax:public static NumberFormat getIntegerInstance(Locale inLocale)Parameters: The function accepts a single mandatory parameter inLocale which describes the locale which is to specified.Return Value: The function returns the NumberFormat instance for Integer 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 integer instance NumberFormat nF = NumberFormat .getIntegerInstance( 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 getIntegerInstance() method is a built-in method of the java.text.NumberFormat returns an integer number format for the current default FORMAT locale.Syntax:public static final NumberFormat getIntegerInstance()Parameters: The function does not accepts any parameter.Return Value: The function returns the NumberFormat instance for general purpose formatting for integer values.Below is the implementation of the above function:Program 1:// Java program to implement// the above functionimport java.text.NumberFormat;import java.util.Locale;import java.util.Currency;public class Main { public static void main(String[] args) throws Exception { // Get the integer instance NumberFormat nF = NumberFormat.getIntegerInstance(); // 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 integer instance NumberFormat nF = NumberFormat .getIntegerInstance(); // 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#getIntegerInstance() Syntax: public static final NumberFormat getIntegerInstance() Parameters: The function does not accepts any parameter. Return Value: The function returns the NumberFormat instance for general purpose formatting for integer values. Below is the implementation of the above function: Program 1: // Java program to implement// the above functionimport java.text.NumberFormat;import java.util.Locale;import java.util.Currency;public class Main { public static void main(String[] args) throws Exception { // Get the integer instance NumberFormat nF = NumberFormat.getIntegerInstance(); // 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 integer instance NumberFormat nF = NumberFormat .getIntegerInstance(); // 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#getIntegerInstance() The getIntegerIntegerInstance(Locale inLocale) method is a built-in method of the java.text.NumberFormat returns a integer number format for any specified locale.Syntax:public static NumberFormat getIntegerInstance(Locale inLocale)Parameters: The function accepts a single mandatory parameter inLocale which describes the locale which is to specified.Return Value: The function returns the NumberFormat instance for Integer 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 integer instance NumberFormat nF = NumberFormat .getIntegerInstance( 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 specified. Return Value: The function returns the NumberFormat instance for Integer 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 integer instance NumberFormat nF = NumberFormat .getIntegerInstance( 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.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Apr, 2019" }, { "code": null, "e": 2975, "s": 28, "text": "The getIntegerInstance() method is a built-in method of the java.text.NumberFormat returns an integer number format for the current default FORMAT locale.Syntax:public static...
How to send message on WhatsApp in Android - GeeksforGeeks
10 Jul, 2020 Whatsapp is the one of most popular messaging App. Many android applications need the functionality to share some messages directly from their app to WhatsApp. For example, if a user wants to share the app or share a message from the app then this functionality comes in use. Either user can send a text or a predefined text can also be sent through this. This article demonstrates how an android application can send messages on WhatsApp. Whatsapp must be installed on the user’s device. Approach Step 1:Open the activity_main.xml file and add the layout code. A message input container as EditText and a Button to send this message is added. activity_main.xml <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:orientation="vertical"> <!-- EditText to take message input from user--> <EditText android:id="@+id/message" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="16dp" android:hint="Enter you message here" android:lines="8" android:inputType="textMultiLine" android:gravity="left|top" /> <!-- Button to send message on Whatsapp--> <Button android:id="@+id/submit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="Submit" android:background="@color/colorPrimary" android:textColor="@android:color/white"/> </LinearLayout> Step 2: Take the reference of EditText and Button in Java file. References are taken using the ids with the help of findViewById() method. Taking reference to EditTextEditText messageEditText = findViewById(R.id.message); EditText messageEditText = findViewById(R.id.message); Taking reference to ButtonButton submit = findViewById(R.id.submit); Button submit = findViewById(R.id.submit); Step 3: Write function to send message to whatsapp. Create an intent with ACTION_SEND and specify the whatsapp package name to this so that it opens whatsapp directly. com.whatsapp is the package name for official whatsapp application. private void sendMessage(String message){ // Creating new intent Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.setPackage("com.whatsapp"); // Give your message here intent.putExtra( Intent.EXTRA_TEXT, message); // Checking whether Whatsapp // is installed or not if (intent .resolveActivity( getPackageManager()) == null) { Toast.makeText( this, "Please install whatsapp first.", Toast.LENGTH_SHORT) .show(); return; } // Starting Whatsapp startActivity(intent);} Step 4: Set onClickListener to the button. It takes the text entered by the user and calls the function sendMessage in which the text message is sent as a parameter. submit.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { // Getting the text // from edit text String message = messageEditText .getText() .toString(); // Calling the function // to send message sendMessage(message); } }); Below is the complete MainActivity.java file: MainActivity.java package com.gfg; import androidx.appcompat .app.AppCompatActivity; import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Taking reference of Edit Text final EditText messageEditText = findViewById(R.id.message); // Taking reference to button Button submit = findViewById(R.id.submit); submit.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { // Getting the text // from edit text String message = messageEditText .getText() .toString(); // Calling the function // to send message sendMessage(message); } }); } private void sendMessage(String message) { // Creating new intent Intent intent = new Intent( Intent.ACTION_SEND); intent.setType("text/plain"); intent.setPackage("com.whatsapp"); // Give your message here intent.putExtra( Intent.EXTRA_TEXT, message); // Checking whether Whatsapp // is installed or not if (intent .resolveActivity( getPackageManager()) == null) { Toast.makeText( this, "Please install whatsapp first.", Toast.LENGTH_SHORT) .show(); return; } // Starting Whatsapp startActivity(intent); }} Output: android Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples How to iterate any Map in Java Initialize an ArrayList in Java Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Stack Class in Java Singleton Class in Java LinkedList in Java
[ { "code": null, "e": 24278, "s": 24250, "text": "\n10 Jul, 2020" }, { "code": null, "e": 24767, "s": 24278, "text": "Whatsapp is the one of most popular messaging App. Many android applications need the functionality to share some messages directly from their app to WhatsApp. For...
Training Tokenizer & Filtering Stopwords
This is very important question that if we have NLTK’s default sentence tokenizer then why do we need to train a sentence tokenizer? The answer to this question lies in the quality of NLTK’s default sentence tokenizer. The NLTK’s default tokenizer is basically a general-purpose tokenizer. Although it works very well but it may not be a good choice for nonstandard text, that perhaps our text is, or for a text that is having a unique formatting. To tokenize such text and get best results, we should train our own sentence tokenizer. For this example, we will be using the webtext corpus. The text file which we are going to use from this corpus is having the text formatted as dialogs shown below − Guy: How old are you? Hipster girl: You know, I never answer that question. Because to me, it's about how mature you are, you know? I mean, a fourteen year old could be more mature than a twenty-five year old, right? I'm sorry, I just never answer that question. Guy: But, uh, you're older than eighteen, right? Hipster girl: Oh, yeah. We have saved this text file with the name of training_tokenizer. NLTK provides a class named PunktSentenceTokenizer with the help of which we can train on raw text to produce a custom sentence tokenizer. We can get raw text either by reading in a file or from an NLTK corpus using the raw() method. Let us see the example below to get more insight into it − First, import PunktSentenceTokenizer class from nltk.tokenize package − from nltk.tokenize import PunktSentenceTokenizer Now, import webtext corpus from nltk.corpus package from nltk.corpus import webtext Next, by using raw() method, get the raw text from training_tokenizer.txt file as follows − text = webtext.raw('C://Users/Leekha/training_tokenizer.txt') Now, create an instance of PunktSentenceTokenizer and print the tokenize sentences from text file as follows − sent_tokenizer = PunktSentenceTokenizer(text) sents_1 = sent_tokenizer.tokenize(text) print(sents_1[0]) White guy: So, do you have any plans for this evening? print(sents_1[1]) Output: Asian girl: Yeah, being angry! print(sents_1[670]) Output: Guy: A hundred bucks? print(sents_1[675]) Output: Girl: But you already have a Big Mac... from nltk.tokenize import PunktSentenceTokenizer from nltk.corpus import webtext text = webtext.raw('C://Users/Leekha/training_tokenizer.txt') sent_tokenizer = PunktSentenceTokenizer(text) sents_1 = sent_tokenizer.tokenize(text) print(sents_1[0]) White guy: So, do you have any plans for this evening? To understand the difference between NLTK’s default sentence tokenizer and our own trained sentence tokenizer, let us tokenize the same file with default sentence tokenizer i.e. sent_tokenize(). from nltk.tokenize import sent_tokenize from nltk.corpus import webtext text = webtext.raw('C://Users/Leekha/training_tokenizer.txt') sents_2 = sent_tokenize(text) print(sents_2[0]) Output: White guy: So, do you have any plans for this evening? print(sents_2[675]) Output: Hobo: Y'know what I'd do if I was rich? With the help of difference in the output, we can understand the concept that why it is useful to train our own sentence tokenizer. Some common words that are present in text but do not contribute in the meaning of a sentence. Such words are not at all important for the purpose of information retrieval or natural language processing. The most common stopwords are ‘the’ and ‘a’. Actually, Natural Language Tool kit comes with a stopword corpus containing word lists for many languages. Let us understand its usage with the help of the following example − First, import the stopwords copus from nltk.corpus package − from nltk.corpus import stopwords Now, we will be using stopwords from English Languages english_stops = set(stopwords.words('english')) words = ['I', 'am', 'a', 'writer'] [word for word in words if word not in english_stops] ['I', 'writer'] from nltk.corpus import stopwords english_stops = set(stopwords.words('english')) words = ['I', 'am', 'a', 'writer'] [word for word in words if word not in english_stops] ['I', 'writer'] With the help of following Python script, we can also find the complete list of languages supported by NLTK stopwords corpus − from nltk.corpus import stopwords stopwords.fileids() [ 'arabic', 'azerbaijani', 'danish', 'dutch', 'english', 'finnish', 'french', 'german', 'greek', 'hungarian', 'indonesian', 'italian', 'kazakh', 'nepali', 'norwegian', 'portuguese', 'romanian', 'russian', 'slovene', 'spanish', 'swedish', 'tajik', 'turkish' ] 59 Lectures 2.5 hours Mike West 17 Lectures 1 hours Pranjal Srivastava 6 Lectures 1 hours Prabh Kirpa Classes 12 Lectures 1 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2920, "s": 2384, "text": "This is very important question that if we have NLTK’s default sentence tokenizer then why do we need to train a sentence tokenizer? The answer to this question lies in the quality of NLTK’s default sentence tokenizer. The NLTK’s default tokenizer is ba...
How to Improve Deep Learning Forecasts for Time Series — Part 2 | by Michael Berk | Towards Data Science
In the prior post we explained how clustering of time series data works. In this post we’re going to do a deep dive into the code itself. Everything will be written in python, but most libraries have an R version. We will try to stay relatively high level but the code will have some useful resources if you’re looking for more. Without further ado, let’s dive in. To help interpretation, let’s leverage a theoretical example: we’re trying to forecast gold prices by using information from local markets around the world. First, we develop a 1000 x 10 data frame. Each row corresponds to a unique time point, in our case a day, and each column corresponds to a different gold market. All values in our data frame are prices. # create datarng = pd.date_range('2000-01-01', freq='d', periods=n_rows)df = pd.DataFrame(np.random.rand(n_rows, n_cols), index=rng) The above code simplifies our example dramatically. One conceptual issue is that prices always take on a value between 0 and 1, however the lessons from the code still apply. With a synthetic data frame created, let’s make it dirty. # "unclean" datadf = df.apply(lambda x: make_outliers_on_col(x), axis='index')df = df.apply(lambda x: make_nan_on_col(x), axis='index') The functions above randomly input 10 outliers and 10 null values into our data frame. Our resulting data frame looks something like this... There are two major data cleaning steps: missing data imputation and outlier removal. Luckily, pandas has some simple built-in methods that can help us. # interpolate missing valuesdf = df.interpolate(method='spline', order=1, limit=10, limit_direction='both')# interpolate outliersdf = df.apply(lambda x: nullify_outliers(x), axis='index')df = df.interpolate(method='spline', order=1, limit=10, limit_direction='both') Our strategy here is very simple. We first impute all missing data using spline interpolation. We then replace all outliers with null values and again use spline interpolation. The paper suggested a variety of missing value imputation methods, some of which include interpolation (shown above), Singular Value Decomposition (SVD) Imputation, and K-Nearest-Neighbors (KNN) Imputation. If you care about speed, SVD or interpolation are your best options. KNN may provide better results, but it’s more computationally intensive. At the end of this step, we will have a data frame that looks like figure 2: With a clean dataset, we will now look to group gold markets that have similar characteristics. Our hypothesis is that similar markets will be more easily fit by a model, thereby leading to more accurate forecasts. The most effective type of classification cited in the paper involved leveraging features about each time series. We will look at two types: time series and signal processing features. # TS-specific featuresautocorrelation = df.apply(lambda x: acf(x, nlags=3), axis='index')partial_autocorrelation = df.apply(lambda x: pacf(x, nlags=3), axis='index')# Signal-processing-specific featuresfast_fourier_transform = df.apply(lambda x: np.fft.fft(x), axis='index')variance = df.apply(lambda x: np.var(x), axis='index') From here, we can perform k-means clustering on each pair of feature sets. We’re limiting to 2 features for simplicity, however the paper cites four potential features for both groups. import numpy as npfrom scipy.cluster.vq import kmeans2# setup ts and signal features for clusteringfeatures = [np.array([autocorrelation, partial_autocorrelation]), np.array([fast_fourier_transform, variance])]for f in features: # cluster out = kmeans2(f, 2) cluster_centers, labels = out # ... The above code groups each of our 10 gold markets into two distinct groups, as shown below in figure 3. Now that we have grouped our data into “similar” time series’, we’re ready to model each group. The paper cited a bi-directional LSTM as having the best accuracy. Despite the scary name, a bidirectional LSTM is just two LSTM’s. The first is trained forward to backward with regular inputs. The second is trained backward to forward with the input vectors reversed. By creating two learning structures in a single epoch, the model often converges faster and learns the structure in the data more completely. However, for simplicity, we will use a basic LSTM, but the concepts can be easily applied to more complex model structures. Before doing so, it’s important to note that we averaged our time series values in each cluster. Some models, such as DeepAR, fit multiple time series’ and output a single prediction. However, vanilla LSTMs require univariate data. from keras.models import Sequentialfrom keras.layers import Densefrom keras.layers import LSTM# fit basic LSTMmodel = Sequential()model.add(LSTM(4, input_shape=(1, look_back)))model.add(Dense(1))model.compile(loss='mean_squared_error', optimizer='adam')model.fit(trainX, trainY, epochs=n_epoch, batch_size=1, verbose=2) The above code was iteratively run on all 4 datasets and their accuracies are shown below in figure 4. Just by judging visually, there doesn’t appear to be much difference in our forecasts, so let’s take a look at the Root Mean Squared Error (RMSE) for each of our models. Figure 5 adds a bit more granularity to our evaluation. We can see that TS features performed better than signal features on cluster 1, but worse on cluster 2. Overall, the average RMSE between cluster 1 and 2 for each group is similar. Now you might be wondering why performance is so similar between groups. Well if you recall, our data generating mechanism was the same for all time series’. The purpose of clustering is to pick up on systematic differences in our time series models. We can then develop a specialized model for each. If the data have the same underlying data generating mechanism, clustering will not help predictive performance. The complete code for the above walkthrough can be seen here. However, for a modeling project with real world data, it’s advisable to try more. For instance, leveraging subject matter knowledge for how time series’ should be grouped can also be very informative. One example for our gold data could be to cluster time series’ at similar geographic locations. If you don’t have subject matter knowledge, here are some more ideas: Cluster on more features Cluster on both TS and signal-based features at the same time Use more complex deep learning structures Introduce static features (the paper discussed architectures for this) Thanks for reading! I’ll be writing 30 more posts that bring academic research to the DS industry. Check out my comment for links to the main source for this post and some useful resources.
[ { "code": null, "e": 310, "s": 172, "text": "In the prior post we explained how clustering of time series data works. In this post we’re going to do a deep dive into the code itself." }, { "code": null, "e": 501, "s": 310, "text": "Everything will be written in python, but most l...
C++ Program to Perform LU Decomposition of any Matrix
The LU decomposition of a matrix produces a matrix as a product of its lower triangular matrix and upper triangular matrix. The LU in LU Decomposition of a matrix stands for Lower Upper. An example of LU Decomposition of a matrix is given below − Given matrix is: 1 1 0 2 1 3 3 1 1 The L matrix is: 1 0 0 2 -1 0 3 -2 -5 The U matrix is: 1 1 0 0 1 -3 0 0 1 A program that performs LU Decomposition of a matrix is given below − #include<iostream> using namespace std; void LUdecomposition(float a[10][10], float l[10][10], float u[10][10], int n) { int i = 0, j = 0, k = 0; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { if (j < i) l[j][i] = 0; else { l[j][i] = a[j][i]; for (k = 0; k < i; k++) { l[j][i] = l[j][i] - l[j][k] * u[k][i]; } } } for (j = 0; j < n; j++) { if (j < i) u[i][j] = 0; else if (j == i) u[i][j] = 1; else { u[i][j] = a[i][j] / l[i][i]; for (k = 0; k < i; k++) { u[i][j] = u[i][j] - ((l[i][k] * u[k][j]) / l[i][i]); } } } } } int main() { float a[10][10], l[10][10], u[10][10]; int n = 0, i = 0, j = 0; cout << "Enter size of square matrix : "<<endl; cin >> n; cout<<"Enter matrix values: "<endl; for (i = 0; i < n; i++) for (j = 0; j < n; j++) cin >> a[i][j]; LUdecomposition(a, l, u, n); cout << "L Decomposition is as follows..."<<endl; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { cout<<l[i][j]<<" "; } cout << endl; } cout << "U Decomposition is as follows..."<<endl; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { cout<<u[i][j]<<" "; } cout << endl; } return 0; } The output of the above program is as follows Enter size of square matrix : 3 Enter matrix values: 1 1 0 2 1 3 3 1 1 L Decomposition is as follows... 1 0 0 2 -1 0 3 -2 -5 U Decomposition is as follows... 1 1 0 0 1 -3 0 0 1 In the above program, the function LU decomposition finds the L and U decompositions of the given matrices. This is done by using nested for loops that calculate the L and U decompositions and store them in l[][] and u[][] matrix from the matrix a[][]. The code snippet that demonstrates this is given as follows − for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { if (j < i) l[j][i] = 0; else { l[j][i] = a[j][i]; for (k = 0; k < i; k++) { l[j][i] = l[j][i] - l[j][k] * u[k][i]; } } } for (j = 0; j < n; j++) { if (j < i) u[i][j] = 0; else if (j == i) u[i][j] = 1; else { u[i][j] = a[i][j] / l[i][i]; for (k = 0; k < i; k++) { u[i][j] = u[i][j] - ((l[i][k] * u[k][j]) / l[i][i]); } } } } In the main() function, the size of the matrix and its elements are obtained from the user. This is given as follows − cout << "Enter size of square matrix : "<<endl; cin >> n; cout<<"Enter matrix values: "<endl; for (i = 0; i < n; i++) for (j = 0; j < n; j++) cin >> a[i][j]; Then the LU decomposition function is called and the L and U decomposition are displayed.This is given below − LUdecomposition(a, l, u, n); cout << "L Decomposition is as follows..."<<endl; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { cout<<l[i][j]<<" "; } cout << endl; } cout << "U Decomposition is as follows..."<<endl; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { cout<u[i][j]<<" "; } cout << endl; }
[ { "code": null, "e": 1249, "s": 1062, "text": "The LU decomposition of a matrix produces a matrix as a product of its lower triangular matrix and upper triangular matrix. The LU in LU Decomposition of a matrix stands for Lower Upper." }, { "code": null, "e": 1309, "s": 1249, "tex...
Java 8 - Optional Class
Optional is a container object used to contain not-null objects. Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as ‘available’ or ‘not available’ instead of checking null values. It is introduced in Java 8 and is similar to what Optional is in Guava. Following is the declaration for java.util.Optional<T> class − public final class Optional<T> extends Object static <T> Optional<T> empty() Returns an empty Optional instance. boolean equals(Object obj) Indicates whether some other object is "equal to" this Optional. Optional<T> filter(Predicate<? super <T> predicate) If a value is present and the value matches a given predicate, it returns an Optional describing the value, otherwise returns an empty Optional. <U> Optional<U> flatMap(Function<? super T,Optional<U>> mapper) If a value is present, it applies the provided Optional-bearing mapping function to it, returns that result, otherwise returns an empty Optional. T get() If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException. int hashCode() Returns the hash code value of the present value, if any, or 0 (zero) if no value is present. void ifPresent(Consumer<? super T> consumer) If a value is present, it invokes the specified consumer with the value, otherwise does nothing. boolean isPresent() Returns true if there is a value present, otherwise false. <U>Optional<U> map(Function<? super T,? extends U> mapper) If a value is present, applies the provided mapping function to it, and if the result is non-null, returns an Optional describing the result. static <T> Optional<T> of(T value) Returns an Optional with the specified present non-null value. static <T> Optional<T> ofNullable(T value) Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional. T orElse(T other) Returns the value if present, otherwise returns other. T orElseGet(Supplier<? extends T> other) Returns the value if present, otherwise invokes other and returns the result of that invocation. <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) Returns the contained value, if present, otherwise throws an exception to be created by the provided supplier. String toString() Returns a non-empty string representation of this Optional suitable for debugging. This class inherits methods from the following class − java.lang.Object Create the following Java program using any editor of your choice in, say, C:\> JAVA. import java.util.Optional; public class Java8Tester { public static void main(String args[]) { Java8Tester java8Tester = new Java8Tester(); Integer value1 = null; Integer value2 = new Integer(10); //Optional.ofNullable - allows passed parameter to be null. Optional<Integer> a = Optional.ofNullable(value1); //Optional.of - throws NullPointerException if passed parameter is null Optional<Integer> b = Optional.of(value2); System.out.println(java8Tester.sum(a,b)); } public Integer sum(Optional<Integer> a, Optional<Integer> b) { //Optional.isPresent - checks the value is present or not System.out.println("First parameter is present: " + a.isPresent()); System.out.println("Second parameter is present: " + b.isPresent()); //Optional.orElse - returns the value if present otherwise returns //the default value passed. Integer value1 = a.orElse(new Integer(0)); //Optional.get - gets the value, value should be present Integer value2 = b.get(); return value1 + value2; } } Compile the class using javac compiler as follows − C:\JAVA>javac Java8Tester.java Now run the Java8Tester as follows − C:\JAVA>java Java8Tester It should produce the following output − First parameter is present: false Second parameter is present: true 10 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2214, "s": 1874, "text": "Optional is a container object used to contain not-null objects. Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as ‘available’ or ‘not available’ instead of checkin...
Create your own Virtual Personal Assistant | by Kunal Dhariwal | Towards Data Science
You know about Cortana, Siri and Google Assistant, right? Have you ever imagined that you can make your own virtual personal assistant and customize it as you want? Today, we’ll be doing it here. We’ll be building a personal assistant from scratch in python. Oh, Before getting into it, let me tell you that by no means it’s an AI but just a powerful example of what AI can do, and how versatile and amazing python is. Also, you need to have some experience with python in order to get started with it. So, Let’s begin: First, We need to install some important packages: SpeechRecognition : Library for performing speech recognition, with support for several engines and APIs, online and offline. Pyttsx3 : Pyttsx is a good text to speech conversion library in python. Wikipedia : Wikipedia is a Python library that makes it easy to access and parse data from Wikipedia. Wolframalpha : Python Client built against the Wolfram|Alpha v2.0 API. PyAudio : Python Bindings for PortAudio. Make sure you have installed all these packages or else you might run into some errors and this is how you install it: pip install PackageName PyAudio Installation: You might run into some errors while installing Pyaudio, I’ve been through the same. You can make use of these steps to avoid the installation errors: find your Python version by python --version mine is 3.7.3 for example find the appropriate .whl file from here, for example mine is PyAudio‐0.2.11‐cp37‐cp37m‐win_amd64.whl, and download it. go to the folder where it is downloaded for example cd C:\Users\foobar\Downloads install the .whl file with pip for example in my case: pip install PyAudio-0.2.11-cp37-cp37m-win_amd64.whl Also, install this to avoid unnecessary errors: pip install pypiwin32 If you are done installing those packages then we can import them and get back to the code: import osimport sysimport datetimeimport pyttsx3import speech_recognition as srimport wikipediaimport wolframalphaimport webbrowserimport smtplibimport random Now, We’’ll be using ‘SAPI5’ as the TTS engine for pyttsx3 and getting the key for wolframaplha, and defining the client. engine = pyttsx3.init(‘sapi5’) client = wolframalpha.Client(‘Get your own key’) You can get your own key from wolframalpha.com -> Apps -> Key. Now, We’ll be initializing a variable and getting the necessary voice parameter we need. For female voice, you can set the value as -1 in the second line and -2 for male voice. Next, We’ll be creating a function talk with audio as the input parameter. voices = engine.getProperty(‘voices’)engine.setProperty(‘voice’, voices[len(voices) — 2].id)def talk(audio): print(‘KryptoKnite: ‘ + audio) engine.say(audio) engine.runAndWait() Next, let’s create another function greetMe and this will be used to greet the user when he runs the program. datetime.datetime.now().hour is being used to get the current time in terms of hour and give the output as per the time and the conditions written below. Talk fn will be used to give the output in terms of voice. def greetMe(): CurrentHour = int(datetime.datetime.now().hour) if CurrentHour >= 0 and CurrentHour < 12: talk('Good Morning!') elif CurrentHour >= 12 and CurrentHour < 18: talk('Good Afternoon!') elif CurrentHour >= 18 and CurrentHour != 0: talk('Good Evening!')greetMe()talk('Hey Buddy, It\'s your assistant KryptoKnite!')talk('tell me about today?') Next, we’ll be creating another function GivenCommand which is used to recognize the user input, it will define that microphone is used as the source of input and We’ll set the pause threshold as 1. Try except block is used and language to recognized will be set as English-India, and if the voice isn’t recognized or heard We’ll send the text input as a kind of error message. def GivenCommand(): k = sr.Recognizer() with sr.Microphone() as source: print("Listening...") k.pause_threshold = 1 audio = k.listen(source) try: Input = k.recognize_google(audio, language='en-in') print('Kunal Dhariwal: ' + Input + '\n') except sr.UnknownValueError: talk('Sorry! I didn\'t get that! Try typing it here!') Input = str(input('Command: ')) return Input Now, let’s start the main function: Here, We’ll be declaring some important functions and conditions which will enhance the functionality of our personal assistant and help him to deliver the output and receive the inputs from the user. if __name__ == '__main__': while True: Input = GivenCommand() Input = Input.lower() if 'open google' in Input: talk('sure') webbrowser.open('www.google.co.in') elif 'open youtube' in Input: talk('sure') webbrowser.open('www.youtube.com') elif "what\'s up" in Input or 'how are you' in Input: setReplies = ['Just doing some stuff!', 'I am good!', 'Nice!', 'I am amazing and full of power'] talk(random.choice(setReplies)) Similarly you can add up more elif with other functionalities like I’ve added one for sending the email. elif 'email' in Input: talk('Who is the recipient? ') recipient = GivenCommand() if 'me' in recipient: try: talk('What should I say? ') content = GivenCommand() server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login("Your_Username", 'Your_Password') server.sendmail('Your_Username', "Recipient_Username", content) server.close() talk('Email sent!') except: talk('Sorry ! I am unable to send your message at this moment!') Or may be play some music? elif 'play music' in Input: music_folder = 'Path music = ['song'] random_music = music_folder + random.choice(music) + '.mp3' os.system(random_music) talk('Okay, here is your music! Enjoy!') Next, We’ll be adding functionalities to use the input to make some searches on wikipedia, google and use wolframalpha. else: Input = Input talk('Searching...') try: try: res = client.Input(Input) outputs = next(res.outputs).text talk('Alpha says') talk('Gotcha') talk(outputs) except: outputs = wikipedia.summary(Input, sentences=3) talk('Gotcha') talk('Wikipedia says') talk(outputs) except: talk("searching on google for " + Input) say = Input.replace(' ', '+') webbrowser.open('https://www.google.co.in/search?q=' + Input)talk('Next Command! Please!') When all this is done, it is very important for the program to exit. Let’s write a condition for it here: elif 'nothing' in Input or 'abort' in Input or 'stop' in Input: talk('okay') talk('Bye, have a good day.') sys.exit()elif 'bye' in Input: talk('Bye, have a great day.') sys.exit() That’s it! You have created your own virtual personal assistant. You can now customize it as you like and set any conditions for it, Also you can add N number of functionalities to it and make it even more amazing. Complete code: https://bit.ly/2VaBsEU You can get the video demo here on my LinkedIn Post: https://bit.ly/2DW8qU0 If you encounter any error or need any help, you can always make a comment or ping me on LinkedIn. LinkedIn: https://bit.ly/2u4YPoF Github: https://bit.ly/2SQV7ss I hope that this has helped you to enhance your knowledge base :) Follow me for more! Thanks for your read and valuable time!
[ { "code": null, "e": 692, "s": 172, "text": "You know about Cortana, Siri and Google Assistant, right? Have you ever imagined that you can make your own virtual personal assistant and customize it as you want? Today, we’ll be doing it here. We’ll be building a personal assistant from scratch in pyth...
Stock prediction using recurrent neural networks | by Joshua Wyatt Smith | Towards Data Science
This type of post has been written quite a few times, yet many leave me unsatisfied. Recently, I read Using the latest advancements in deep learning to predict stock price movements, which, I think was overall a very interesting article. It covers many topics and even gave me some ideas (it also nudged me into writing my first article 🙂). But it doesn’t actually say how well the network performed. My gut feeling says “not well” given that this is usually the case, but maybe/hopefully I’m wrong! For some time now I’ve been developing my own trading algorithm, and so this article presents my (work-in-progress) approach, thoughts and some results. This covers: The challengeDataBuilding datasetsTrainingResultsFinal Remarks The challenge Data Building datasets Training Results Final Remarks The overall challenge is to determine the gradient difference between one Close price and the next. Not the actual stock price. Why? It’s easy to fool yourself into thinking you have a viable model when you are trying to predict something that could fluctuate marginally (|<0.01%|) and/or largely (|>5%|). The plot below gives an example of this. A basic model (nothing special) was trained to predict the (normalized) price of Goldman Sachs: The actual price of the stock is on the y-axis, while the predicted price is on the x-axis. There’s clearly a nice linear trend there. And maybe a trading strategy can be developed from this. But what happens if we plot the gradient between two consecutive points? Uh oh. For predicting whether the price will go up or down for the next candlestick (the definition of gradient here), our model is essentially no better then guessing. That’s a pretty large fundamental issue. The accuracy here (51.5%) is calculated by summing the values in the correct quadrants (top right and bottom left) and dividing by all points. Instead of telling you why this is a difficult problem (you probably already know), I’ll mention two personal struggles I faced here. The data. The quality of the data determines the outcome of your model. Obviously. Clean and process your data, understand it, play with it, plot it, cuddle it. Make sure you explore every aspect of it. For example; I use news stories. They get published in different time-zones. The stock price data comes from another time-zone. Make sure you are syncing correctly and not cheating yourself by using future information. That’s just one such example. Another one: For when asking for hourly candlesticks from my broker, the first bar is a 30min window. Without checks for catching this, you’re going to be scratching your head for a while.Building a naive estimator. By that I mean your model’s prediction is largely based on the previous point. This seems to be the most common problem in stock prediction. Building a model that mitigates this and remains accurate is essentially the key, and thus, the difficult part. The data. The quality of the data determines the outcome of your model. Obviously. Clean and process your data, understand it, play with it, plot it, cuddle it. Make sure you explore every aspect of it. For example; I use news stories. They get published in different time-zones. The stock price data comes from another time-zone. Make sure you are syncing correctly and not cheating yourself by using future information. That’s just one such example. Another one: For when asking for hourly candlesticks from my broker, the first bar is a 30min window. Without checks for catching this, you’re going to be scratching your head for a while. Building a naive estimator. By that I mean your model’s prediction is largely based on the previous point. This seems to be the most common problem in stock prediction. Building a model that mitigates this and remains accurate is essentially the key, and thus, the difficult part. Right, so in a nutshell: Can we train a model that accurately predicts the next gradient change, while mitigating the naive estimator effect? Spoiler alert: Yes, we can! (I think). Stock price information Most of the time spent on this project was making sure the data was in the correct format, or aligned properly, or not too sparse etc. (Well, that and the GUI I built around this tool, but that’s a different issue entirely 🙄). My data comes from Interactive Brokers (IB). After signing up and depositing some minimum amount, you can then subscribe to various feeds. At present I pay ~15 euros a month for live data. My function that makes use of their API to download stock prices can be seen in this gist. What’s important there: 1) Connect to IB 2) Create a “contract”3) Request historical bars using that contract. All of this is put on a patched async loop (hence the package nest_asyncio), due to my code already being on a thread. The Usage in the above gist gives an example of how one would call this function. I now have a pandas dataframe of 1 hour candlesticks. From there it’s easy to make plots: I use the pretty awesome Plotly library. The slightly more involved syntax is a sacrifice for interactive plots (although not interactive for this article). By zooming in on a section, the goal can be better highlighted: I will try predict the gradient from the latest Close price that I have, to the incoming Close price. This can be used to formulate strategies for trading. At a later stage the size of the gradient could also potentially be taken into account. News The hypothesis is that news has a very large impact on how stock prices evolve. There are a couple of sources for news out there, newsapi.org for one, IB also has some options, Thomson Reuters etc.As for my sources, I’m not quite ready to share them yet 🙂. I currently use news sentiment in the most basic form: I count the number of positive/negative and neutral stories for a given time period and use them as features. I use my own home-rolled semi-supervised news classifier, but one could also use BERT or any other pre-trained library. There are other ways to include sentiment, such as injecting the embeddings directly into the network for example. For each stock, I chose certain keywords and retrieve the associated news articles. One hyper-parameter is “lag”. A lag of 0 means that if I’m predicting the Close price at 2pm, only stories before 2pm on the same day are used. A lag of 1 means to include news for an extra day back, and so on. The question here is: how long does it take for news to propagate through society and trading algorithms, and how long does it’s effect have on the stock?Below shows the number of stories for Goldman Sachs for a given time period and a lag of 2 days. I believe the negative spike between April 15–18th has to do with the bank reporting mixed first quarter results. Variables and features One problem with predicting stock prices is that there really is just a finite amount of data. Also, I don’t want to go too far back as I believe the nature of trading has completely changed from say 2013 till now. I can train on many or few stocks concatenated together, with others used as features. By concatenating stocks I increase the number of data, as well as potentially learn new insights. The pseudocode for my dataset builder looks like this: # Specify stocks to concatenate and specify those to use as features. Training_assets=[...] # i.e. currencies, or other stocksFeature_assets[...] # i.e. related stocksFor stock in Training_assets: Download/update stock from IB Merge in News sentiments Add extra variables like MACD, Boilinger Bands, etc. Download Feature_assets and append to stock Normalize Concatenate with the previous training stock Normalization During training, I normalize each feature and save the parameters to a scalar file. Then, when inferring, I read the file and apply the parameters to the variable. This speeds up the process of inferring when I can just ask for the latest point from my broker. A gist of how to normalize can be seen here. An interesting parameter is the norm_window_size. This specifies how many points in the feature should be normalized together. A window that is too big means your resolution is not fine grained enough. A larger variety of external factors that haven’t been taken into account will play a bigger role. A window too small will essentially just look like noise. It’s an interesting parameter to play with. Correlations The correlations between each variable are shown below. Remember, in the most broad sense, two highly correlated variables means that if one increases, so will the other. For anti-correlation, if one variable decreases, the other will increase.Higher, positive correlations are darker colors, lighter for lower/negative correlations. Currently, I do use Open, High, Low as features. They are extremely highly correlated with the Close price, but I have all that information at inference time, so hey, why not. Future training might see me remove those to see what happens. In general, it’s not good to have “repetitive” variables.Other features that seem redundant are the indicators built with the Close price. But they give me an easy way to change the sequence length for just those variables so I left them in for now. But what “external” sources are there (i.e., not derived from the stock(s) we’re trying to infer on)? These are the most important variables.High correlations between features such as the currencies, the indexes and an anti-correlation with the VIX are very promising. Some currencies could be eliminated to reduce the overall network size (i.e., the USD and South African Rand don’t seem like they should influence each other, but who knows), and further trainings over different variables could eliminate some of them. It is important to remember that “...correlation is not the same thing as a trading prediction.” as pointed out by Daniel Shapiro in Data Science For Algorithmic Trading, i.e. correlation is not causation. And so one filtering technique on the to-do list is to look at how correlations evolve over time for individual variables vs the Close price of a given stock. This will allow us to remove variables and reduce the number of dimensions. Sliding window algorithm At this point pandas.head() gives: which shows 5 time steps, with 7 normalized features (for brevity). Then, we create the training, validation and testing datasets. Since this is a sequence prediction problem, we use a sliding window algorithm. The premise is shown in the figure below. X number of points (4 in the image) are used, with X+1 taken as the label and forming a new array. The window is then moved 1 point forward and the calculation repeated. This way you have a large array (X, which are your inputs) as well as your labels, Y. From here, and after splitting into train, validation and test sizes (80%,15%, 5%), the data can be fed into a neural network. I played around with a variety of architectures (including GANs), until finally settling on a simple recurrent neural network (RNN). And so Occam can rest in peace. In theory, an LSTM (a type of RNN) should be better, something I need to play with again.Christopher Olah provides a very nice article about RNN’s and LSTMs. My model in Tensorflow (1.12) looks a little something like this (namespaces and histograms etc. removed): def gru_cell(state_size): cell = tf.contrib.rnn.GRUCell(state_size) return cell# Inputsinputs = tf.placeholder(tf.float32, [None, seq_len, len(variables)])labels = tf.placeholder(tf.float32, [None ,n_outputs])# Placeholder for dropout to switch on and off for training/inferencekeep_prob = tf.placeholder(tf.float32)# Run the data through the RNN layersbatch_size = tf.shape(inputs)[0]initial_state = tf.zeros([batch_size, num_layers * size])cell = tf.contrib.rnn.MultiRNNCell([gru_cell(size) for _ in range(num_layers)], state_is_tuple=False)outputs, final_state = tf.nn.dynamic_rnn(cell, inputs, initial_state=initial_state) # Then feed into a dropout layerdense_layer = tf.contrib.layers.dropout(outputs[:,-1], keep_prob=keep_prob)# ... and a dense layerdense_layer = tf.layers.dense(dense_layer, dense_units, activation=tf.nn.selu)# ... followed by a single node dense layerfinal_predictions = tf.layers.dense(dense_layer,n_outputs,activation=tf.sigmoid) The graph looks like this: It’s a fairly simple network, where a multi-layer RNN (with GRU layers) is fed into a dense layer (which includes a dropout layer). The number of layers, activations, and dropout percentage all are optimized during training.The “Accuracy” node is long convoluted set of TF operations that convert a prediction from the dense network into a binary gradient movement. As an experiment, this accuracy is actually currently used in my cost function as: cost = (1-Accuracy) + tf.losses.mean_squared_error(labels, final_predictions) where the label is the normalized price, and final_predictions are the normalized actual price predictions. I use the AdamOptimiser with a cyclic function learning rate. Is this the optimal/best way to do it? I’m not entirely sure yet! 🙂 I too made use of Bayesian Optimization (BO) during the training stage. I think it’s a fantastic library, BUT, am I convinced that it works well for this type of problem and actually saves a huge amount of time? Not really. I’d like to create some plots to see how the training progresses and what the function(s) looks like. But with this many parameters it’s tough. However, maybe it provides a slightly biased random number generator. With that being said, the parameters used for the results in this article are: Here’s an interesting read on scaled exponential linear units (selus). The loss curve for train (orange) and validation (blue) data sets is shown below. The lines are very jumpy, and maybe using a larger batch size could help with that. There’s also a some difference between the two datasets. This is not too surprising. Remember, I’ve concatenated (and shuffled) multiple stocks with Goldman Sachs, and so what we’re actually training is a model for a given “sector”, or whatever you want to call it. In theory, it’s more generalizable, and so more difficult to train (the trade-off to get more data). Thus, it could hint at some over-training; something to be further checked. However, one can see a trend of the validation loss decreasing as time goes on (up until a certain point) 👍. How does this latest model perform? Below is the actual gradient vs the predicted gradient. 65% accuracy (with the same definition used before) isn’t too bad. The figure below shows a confusion matrix for the actual gradient vs the predicted gradient. It shows that 59% of the time we correctly predict a negative gradient, while 71% of the time we correctly predict a positive gradient. This imbalance could come from the nature of the dataset and the model, i.e., maybe three small positive gradients proceed a single negative gradient. The model learns this, and thus quoting accuracy can be a bit misleading. This will become very important when actually developing trading strategies. The cover plot is shown again, focusing on just the validation and test datasets. Let’s be honest, it’s not that sexy. But there are times when trends of gradient changes are indeed followed. To me, anytime a plot like this is shown with seemingly perfect overlap, an alarm bell should go off inside the reader’s head.Remember, the validation dataset is only used in the training steps to determine when to stop training (i.e. no improvement after x epochs, stop). The test dataset is not used anywhere. That means this plot shows around 600 hours of “semi-unseen” data, and just under 300 hours of completely unseen data. How stable was our result?In 114 training sessions the distribution of the accuracy for predicting the gradient is shown below (the histogram in green). The accuracy of each training session is plotted against run number in orange. This confirms my suspicion that BO isn’t working too well here, but maybe it just needs more iterations and/or parameters tweaked. It turns out there was actually a better result I could have used. Whoops 😀. (The better result has a more even distribution for up/up vs down/down in the confusion matrix, which is nice).The take-away from the green histogram is that we are learning something. Also, it’s good to see that there are some results that are no better than guessing, meaning we aren’t always learning something when playing with parameters. Some models just suck. And if no models sucked that would be an alarm bell. In this article I highlighted my means of building a RNN that is able to predict the correct gradient difference between 2 Close prices around 65% of the time. I believe with more playing around and some tweaking this number can be improved. Also, plenty more checks and studies can be performed.Will it actually make money when backtesting? How about when trading live?There is a huge amount to consider. From using the pretty cool backtrader library, to plugging it into the IB API, these will be topics for the next article. 🙂 I hope you found the article interesting... I had fun writing it! Joshua Wyatt Smith
[ { "code": null, "e": 825, "s": 172, "text": "This type of post has been written quite a few times, yet many leave me unsatisfied. Recently, I read Using the latest advancements in deep learning to predict stock price movements, which, I think was overall a very interesting article. It covers many to...
Elixir - Quick Guide
Elixir is a dynamic, functional language designed for building scalable and maintainable applications. It leverages the Erlang VM, known for running low-latency, distributed and fault-tolerant systems, while also being successfully used in web development and the embedded software domain. Elixir is a functional, dynamic language built on top of Erlang and the Erlang VM. Erlang is a language that was originally written in 1986 by Ericsson to help solve telephony problems like distribution, fault-tolerance, and concurrency. Elixir, written by José Valim, extends Erlang and provides a friendlier syntax into the Erlang VM. It does this while keeping the performance of the same level as Erlang. Let us now discuss a few important features of Elixir − Scalability − All Elixir code runs inside lightweight processes that are isolated and exchange information via messages. Scalability − All Elixir code runs inside lightweight processes that are isolated and exchange information via messages. Fault Tolerance − Elixir provides supervisors which describe how to restart parts of your system when things go wrong, going back to a known initial state that is guaranteed to work. This ensures your application/platform is never down. Fault Tolerance − Elixir provides supervisors which describe how to restart parts of your system when things go wrong, going back to a known initial state that is guaranteed to work. This ensures your application/platform is never down. Functional Programming − Functional programming promotes a coding style that helps developers write code that is short, fast, and maintainable. Functional Programming − Functional programming promotes a coding style that helps developers write code that is short, fast, and maintainable. Build tools − Elixir ships with a set of development tools. Mix is one such tool that makes it easy to create projects, manage tasks, run tests, etc. It also has its own package manager − Hex. Build tools − Elixir ships with a set of development tools. Mix is one such tool that makes it easy to create projects, manage tasks, run tests, etc. It also has its own package manager − Hex. Erlang Compatibility − Elixir runs on the Erlang VM giving developers complete access to Erlang’s ecosystem. Erlang Compatibility − Elixir runs on the Erlang VM giving developers complete access to Erlang’s ecosystem. In order to run Elixir, you need to set it up locally on your system. To install Elixir, you will first require Erlang. On some platforms, Elixir packages come with Erlang in them. Let us now understand the installation of Elixir in different Operating Systems. To install Elixir on windows, download installer from https://repo.hex.pm/elixirwebsetup.exe and simply click Next to proceed through all steps. You will have it on your local system. If you have any problems while installing it, you can check this page for more info. If you have Homebrew installed, make sure that it is the latest version. For updating, use the following command − brew update Now, install Elixir using the command given below − brew install elixir The steps to install Elixir in an Ubuntu/Debian setup is as follows − Add Erlang Solutions repo − wget https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb && sudo dpkg -i erlang-solutions_1.0_all.deb sudo apt-get update Install the Erlang/OTP platform and all of its applications − sudo apt-get install esl-erlang Install Elixir − sudo apt-get install elixir If you have any other Linux distribution, please visit this page to set up elixir on your local system. To test the Elixir setup on your system, open your terminal and enter iex in it. It will open the interactive elixir shell like the following − Erlang/OTP 19 [erts-8.0] [source-6dc93c1] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] Interactive Elixir (1.3.1) - press Ctrl+C to exit (type h() ENTER for help) iex(1)> Elixir is now successfully set up on your system. We will start with the customary 'Hello World' program. To start the Elixir interactive shell, enter the following command. iex After the shell starts, use the IO.puts function to "put" the string on the console output. Enter the following in your Elixir shell − IO.puts "Hello world" In this tutorial, we will use the Elixir script mode where we will keep the Elixir code in a file with the extension .ex. Let us now keep the above code in the test.ex file. In the succeeding step, we will execute it using elixirc− IO.puts "Hello world" Let us now try to run the above program as follows − $elixirc test.ex The above program generates the following result − Hello World Here we are calling a function IO.puts to generate a string to our console as output. This function can also be called the way we do in C, C++, Java, etc., providing arguments in parentheses following the function name − IO.puts("Hello world") Single line comments start with a '#' symbol. There's no multi-line comment, but you can stack multiple comments. For example − #This is a comment in Elixir There are no required line endings like ';' in Elixir. However, we can have multiple statements in the same line, using ';'. For example, IO.puts("Hello"); IO.puts("World!") The above program generates the following result − Hello World! Identifiers like variables, function names are used to identify a variable, function, etc. In Elixir, you can name your identifiers starting with a lower case alphabet with numbers, underscores and upper case letters thereafter. This naming convention is commonly known as snake_case. For example, following are some valid identifiers in Elixir − var1 variable_2 one_M0r3_variable Please note that variables can also be named with a leading underscore. A value that is not meant to be used must be assigned to _ or to a variable starting with underscore − _some_random_value = 42 Also elixir relies on underscores to make functions private to modules. If you name a function with a leading underscore in a module, and import that module, this function will not be imported. There are many more intricacies related to function naming in Elixir which we will discuss in coming chapters. Following words are reserved and cannot be used as variables, module or function names. after and catch do inbits inlist nil else end not or false fn in rescue true when xor __MODULE__ __FILE__ __DIR__ __ENV__ __CALLER__ For using any language, you need to understand the basic data types the language supports. In this chapter, we will discuss 7 basic data types supported by the elixir language: integers, floats, Booleans, atoms, strings, lists and tuples. Elixir, like any other programming language, supports both integers and floats. If you open your elixir shell and input any integer or float as input, it'll return its value. For example, 42 When the above program is run, it produces the following result − 42 You can also define numbers in octal, hex and binary bases. To define a number in octal base, prefix it with '0o'. For example, 0o52 in octal is equivalent to 42 in decimal. To define a number in decimal base, prefix it with '0x'. For example, 0xF1 in hex is equivalent to 241 in decimal. To define a number in binary base, prefix it with '0b'. For example, 0b1101 in binary is equivalent to 13 in decimal. Elixir supports 64bit double precision for floating point numbers. And they can also be defined using an exponentiation style. For example, 10145230000 can be written as 1.014523e10 Atoms are constants whose name is their value. They can be created using the color(:) symbol. For example, :hello Elixir supports true and false as Booleans. Both these values are in fact attached to atoms :true and :false respectively. Strings in Elixir are inserted between double quotes, and they are encoded in UTF-8. They can span multiple lines and contain interpolations. To define a string simply enter it in double quotes − "Hello world" To define multiline strings, we use a syntax similar to python with triple double quotes − """ Hello World! """ We'll learn about strings, binaries and char lists(similar to strings) in depth in the strings chapter. Binaries are sequences of bytes enclosed in << >> separated with a comma. For example, << 65, 68, 75>> Binaries are mostly used to handle bits and bytes related data, if you have any. They can, by default, store 0 to 255 in each value. This size limit can be increased by using the size function that says how many bits it should take to store that value. For example, <<65, 255, 289::size(15)>> Elixir uses square brackets to specify a list of values. Values can be of any type. For example, [1, "Hello", :an_atom, true] Lists come with inbuilt functions for head and tail of the list named hd and tl which return the head and tail of the list respectively. Sometimes when you create a list, it'll return a char list. This is because when elixir sees a list of printable ASCII characters, it prints it as a char list. Please note that strings and char lists are not equal. We'll discuss lists further in later chapters. Elixir uses curly brackets to define tuples. Like lists, tuples can hold any value. { 1, "Hello", :an_atom, true A question arises here, - why provide both lists and tuples when they both work in the same way? Well they have different implementations. Lists are actually stored as linked lists, so insertions, deletions are very fast in lists. Lists are actually stored as linked lists, so insertions, deletions are very fast in lists. Tuples on the other hand, are stored in contiguous memory block, which make accessing them faster but adds an additional cost on insertions and deletions. Tuples on the other hand, are stored in contiguous memory block, which make accessing them faster but adds an additional cost on insertions and deletions. A variable provides us with named storage that our programs can manipulate. Each variable in Elixir has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. Elixir supports the following basic types of variables. These are used for Integers. They are of size 32bit on a 32bit architecture and 64 bits on a 64-bit architecture. Integers are always signed in elixir. If an integer starts to expand in size above its limit, elixir convers it in a Big Integer which takes up memory in range 3 to n words whichever can fit it in memory. Floats have a 64-bit precision in elixir. They are also like integers in terms of memory. When defining a float, exponential notation can be used. They can take up 2 values which is either true or false. Strings are utf-8 encoded in elixir. They have a strings module which provides a lot of functionality to the programmer to manipulate strings. These are functions that can be defined and assigned to a variable, which can then be used to call this function. There are a lot of collection types available in Elixir. Some of them are Lists, Tuples, Maps, Binaries, etc. These will be discussed in subsequent chapters. A variable declaration tells the interpreter where and how much to create the storage for the variable. Elixir does not allow us to just declare a variable. A variable must be declared and assigned a value at the same time. For example, to create a variable named life and assign it a value 42, we do the following − life = 42 This will bind the variable life to value 42. If we want to reassign this variable a new value, we can do this by using the same syntax as above, i.e., life = "Hello world" Naming variables follow a snake_case convention in Elixir, i.e., all variables must start with a lowercase letter, followed by 0 or more letters(both upper and lower case), followed at the end by an optional '?' OR '!'. Variable names can also be started with a leading underscore but that must be used only when ignoring the variable, i.e., that variable will not be used again but is needed to be assigned to something. In the interactive shell, variables will print if you just enter the variable name. For example, if you create a variable − life = 42 And enter 'life' in your shell, you'll get the output as − 42 But if you want to output a variable to the console (When running an external script from a file), you need to provide the variable as input to IO.puts function − life = 42 IO.puts life or life = 42 IO.puts(life) This will give you the following output − 42 An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. There are a LOT of operators provided by elixir. They are divided in the following categories − Arithmetic operators Comparison operators Boolean operators Misc operators The following table shows all the arithmetic operators supported by Elixir language. Assume variable A holds 10 and variable B holds 20, then − Show Examples The comparison operators in Elixir are mostly common to those provided in most other languages. The following table sums up comparison operators in Elixir. Assume variable A holds 10 and variable B holds 20, then − Show Examples Elixir provides 6 logical operators: and, or, not, &&, || and !. The first three, and or not are strict Boolean operators, meaning that they expect their first argument to be a Boolean. Non Boolean argument will raise an error. While the next three, &&, || and ! are non strict, do not require us to have the first value strictly as a boolean. They work in the same way as their strict counterparts. Assume variable A holds true and variable B holds 20, then − Show Examples NOTE −and, or, && and || || are short circuit operators. This means that if the first argument of and is false, then it will not further check for the second one. And if the first argument of or is true, then it will not check for the second one. For example, false and raise("An error") #This won't raise an error as raise function wont get executed because of short #circuiting nature of and operator Bitwise operators work on bits and perform bit by bit operation. Elixir provides bitwise modules as part of the package Bitwise, so in order to use these, you need to use the bitwise module. To use it, enter the following command in your shell − use Bitwise Assume A to be 5 and B to be 6 for the following examples − Show Examples Other than the above operators, Elixir also provides a range of other operators like Concatenation Operator, Match Operator, Pin Operator, Pipe Operator, String Match Operator, Code Point Operator, Capture Operator, Ternary Operator that make it quite a powerful language. Show Examples Pattern matching is a technique which Elixir inherits form Erlang. It is a very powerful technique that allows us to extract simpler substructures from complicated data structures like lists, tuples, maps, etc. A match has 2 main parts, a left and a right side. The right side is a data structure of any kind. The left side attempts to match the data structure on the right side and bind any variables on the left to the respective substructure on the right. If a match is not found, the operator raises an error. The simplest match is a lone variable on the left and any data structure on the right. This variable will match anything. For example, x = 12 x = "Hello" IO.puts(x) You can place variables inside a structure so that you can capture a substructure. For example, [var_1, _unused_var, var_2] = [{"First variable"}, 25, "Second variable" ] IO.puts(var_1) IO.puts(var_2) This will store the values, {"First variable"} in var_1 and "Second variable" in var_2. There is also a special _ variable(or variables prefixed with '_') that works exactly like other variables but tells elixir, "Make sure something is here, but I don't care exactly what it is.". In the previous example, _unused_var was one such variable. We can match more complicated patterns using this technique. For example if you want to unwrap and get a number in a tuple which is inside a list which itself is in a list, you can use the following command − [_, [_, {a}]] = ["Random string", [:an_atom, {24}]] IO.puts(a) The above program generates the following result − 24 This will bind a to 24. Other values are ignored as we are using '_'. In pattern matching, if we use a variable on the right, its value is used. If you want to use the value of a variable on the left, you'll need to use the pin operator. For example, if you have a variable "a" having value 25 and you want to match it with another variable "b" having value 25, then you need to enter − a = 25 b = 25 ^a = b The last line matches the current value of a, instead of assigning it, to the value of b. If we have a non-matching set of left and right hand side, the match operator raises an error. For example, if we try to match a tuple with a list or a list of size 2 with a list of size 3, an error will be displayed. Decision making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Following is the general from of a typical decision making structure found in most of the programming language − Elixir provides if/else conditional constructs like many other programming languages. It also has a cond statement which calls the first true value it finds. Case is another control flow statement which uses pattern matching to control the flow of the program. Let's have a deep look at them. Elixir provides the following types of decision making statements. Click the following links to check their detail. An if statement consists of a Boolean expression followed by do, one or more executable statements and finally an end keyword. Code in if statement executes only if Boolean condition evaluates to true. An if statement can be followed by an optional else statement(within the do..end block), which executes when the Boolean expression is false. An unless statement has the same body as an if statement. The code within unless statement executes only when the condition specified is false. An unless..else statement has the same body as an if..else statement. The code within unless statement executes only when the condition specified is false. A cond statement is used where we want to execute code on basis of several conditions. It kind of works like an if...else if....else construct in several other programming languages. Case statement can be considered as a replacement for switch statement in imperative languages. Case takes a variable/literal and applies pattern matching to it with different cases. If any case matches, Elixir executes code associated with that case and exits case statement. Strings in Elixir are inserted between double quotes, and they are encoded in UTF-8. Unlike C and C++ where the default strings are ASCII encoded and only 256 different characters are possible, UTF-8 consists of 1,112,064 code points. This means that UTF-8 encoding consists of those many different possible characters. Since the strings use utf-8, we can also use symbols like: ö, ł, etc. To create a string variable, simply assign a string to a variable − str = "Hello world" To print this to your console, simply call the IO.puts function and pass it the variable str − str = str = "Hello world" IO.puts(str) The above program generates the following result − Hello World You can create an empty string using the string literal, "". For example, a = "" if String.length(a) === 0 do IO.puts("a is an empty string") end The above program generates the following result. a is an empty string String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions by including their values inside a string literal. Elixir supports string interpolation, to use a variable in a string, when writing it, wrap it with curly braces and prepend the curly braces with a '#' sign. For example, x = "Apocalypse" y = "X-men #{x}" IO.puts(y) This will take the value of x and substitute it in y. The above code will generate the following result − X-men Apocalypse We have already seen the use of String concatenation in previous chapters. The '<>' operator is used to concatenate strings in Elixir. To concatenate 2 strings, x = "Dark" y = "Knight" z = x <> " " <> y IO.puts(z) The above code generates the following result − Dark Knight To get the length of the string, we use the String.length function. Pass the string as a parameter and it will show you its size. For example, IO.puts(String.length("Hello")) When running above program, it produces following result − 5 To reverse a string, pass it to the String.reverse function. For example, IO.puts(String.reverse("Elixir")) The above program generates the following result − rixilE To compare 2 strings, we can use the == or the === operators. For example, var_1 = "Hello world" var_2 = "Hello Elixir" if var_1 === var_2 do IO.puts("#{var_1} and #{var_2} are the same") else IO.puts("#{var_1} and #{var_2} are not the same") end The above program generates the following result − Hello world and Hello elixir are not the same. We have already seen the use of the =~ string match operator. To check if a string matches a regex, we can also use the string match operator or the String.match? function. For example, IO.puts(String.match?("foo", ~r/foo/)) IO.puts(String.match?("bar", ~r/foo/)) The above program generates the following result − true false This same can also be achieved by using the =~ operator. For example, IO.puts("foo" =~ ~r/foo/) The above program generates the following result − true Elixir supports a large number of functions related to strings, some of the most used are listed in the following table. at(string, position) Returns the grapheme at the position of the given utf8 string. If position is greater than string length, then it returns nil capitalize(string) Converts the first character in the given string to uppercase and the remainder to lowercase contains?(string, contents) Checks if string contains any of the given contents downcase(string) Converts all characters in the given string to lowercase ends_with?(string, suffixes) Returns true if string ends with any of the suffixes given first(string) Returns the first grapheme from a utf8 string, nil if the string is empty last(string) Returns the last grapheme from a utf8 string, nil if the string is empty replace(subject, pattern, replacement, options \\ []) Returns a new string created by replacing occurrences of pattern in subject with replacement slice(string, start, len) Returns a substring starting at the offset start, and of length len split(string) Divides a string into substrings at each Unicode whitespace occurrence with leading and trailing whitespace ignored. Groups of whitespace are treated as a single occurrence. Divisions do not occur on non-breaking whitespace upcase(string) Converts all characters in the given string to uppercase A binary is just a sequence of bytes. Binaries are defined using << >>. For example: << 0, 1, 2, 3 >> Of course, those bytes can be organized in any way, even in a sequence that does not make them a valid string. For example, << 239, 191, 191 >> Strings are also binaries. And the string concatenation operator <> is actually a Binary concatenation operator: IO.puts(<< 0, 1 >> <> << 2, 3 >>) The above code generates the following result − << 0, 1, 2, 3 >> Note the ł character. Since this is utf-8 encoded, this character representation takes up 2 bytes. Since each number represented in a binary is meant to be a byte, when this value goes up from 255, it is truncated. To prevent this, we use size modifier to specify how many bits we want that number to take. For example − IO.puts(<< 256 >>) # truncated, it'll print << 0 >> IO.puts(<< 256 :: size(16) >>) #Takes 16 bits/2 bytes, will print << 1, 0 >> The above program will generate the following result − << 0 >> << 1, 0 >> We can also use the utf8 modifier, if a character is code point then, it will be produced in the output; else the bytes − IO.puts(<< 256 :: utf8 >>) The above program generates the following result − Ā We also have a function called is_binary that checks if a given variable is a binary. Note that only variables which are stored as multiples of 8bits are binaries. If we define a binary using the size modifier and pass it a value that is not a multiple of 8, we end up with a bitstring instead of a binary. For example, bs = << 1 :: size(1) >> IO.puts(bs) IO.puts(is_binary(bs)) IO.puts(is_bitstring(bs)) The above program generates the following result − << 1::size(1) >> false true This means that variable bs is not a binary but rather a bitstring. We can also say that a binary is a bitstring where the number of bits is divisible by 8. Pattern matching works on binaries as well as bitstrings in the same way. A char list is nothing more than a list of characters. Consider the following program to understand the same. IO.puts('Hello') IO.puts(is_list('Hello')) The above program generates the following result − Hello true Instead of containing bytes, a char list contains the code points of the characters between single-quotes. So while the double-quotes represent a string (i.e. a binary), singlequotes represent a char list (i.e. a list). Note that IEx will generate only code points as output if any of the chars is outside the ASCII range. Char lists are used mostly when interfacing with Erlang, in particular old libraries that do not accept binaries as arguments. You can convert a char list to a string and back by using the to_string(char_list) and to_char_list(string) functions − IO.puts(is_list(to_char_list("hełło"))) IO.puts(is_binary(to_string ('hełło'))) The above program generates the following result − true true NOTE − The functions to_string and to_char_list are polymorphic, i.e., they can take multiple types of input like atoms, integers and convert them to strings and char lists respectively. A linked list is a heterogeneous list of elements that are stored at different locations in memory and are kept track of by using references. Linked lists are data structures especially used in functional programming. Elixir uses square brackets to specify a list of values. Values can be of any type − [1, 2, true, 3] When Elixir sees a list of printable ASCII numbers, Elixir will print that as a char list (literally a list of characters). Whenever you see a value in IEx and you are not sure what it is, you can use the i function to retrieve information about it. IO.puts([104, 101, 108, 108, 111]) The above characters in the list are all printable. When the above program is run, it produces the following result − hello You can also define lists the other way round, using single quotes − IO.puts(is_list('Hello')) When the above program is run, it produces the following result − true Keep in mind single-quoted and double-quoted representations are not equivalent in Elixir as they are represented by different types. To find the length of a list, we use the length function as in the following program − IO.puts(length([1, 2, :true, "str"])) The above program generates the following result − 4 Two lists can be concatenated and subtracted using the ++ and -- operators. Consider the following example to understand the functions. IO.puts([1, 2, 3] ++ [4, 5, 6]) IO.puts([1, true, 2, false, 3, true] -- [true, false]) This will give you a concatenated string in the first case and a subtracted string in the second. The above program generates the following result − [1, 2, 3, 4, 5, 6] [1, 2, 3, true] The head is the first element of a list and the tail is the remainder of a list. They can be retrieved with the functions hd and tl. Let us assign a list to a variable and retrieve its head and tail. list = [1, 2, 3] IO.puts(hd(list)) IO.puts(tl(list)) This will give us the head and tail of the list as output. The above program generates the following result − 1 [2, 3] Note − Getting the head or the tail of an empty list is an error. Elixir standard library provides a whole lot of functions to deal with lists. We will have a look at some of those here. You can check out the rest here List. delete(list, item) Deletes the given item from the list. Returns a list without the item. If the item occurs more than once in the list, just the first occurrence is removed. delete_at(list, index) Produces a new list by removing the value at the specified index. Negative indices indicate an offset from the end of the list. If index is out of bounds, the original list is returned. first(list) Returns the first element in list or nil if list is empty. flatten(list) Flattens the given list of nested lists. insert_at(list, index, value) Returns a list with value inserted at the specified index. Note that index is capped at the list length. Negative indices indicate an offset from the end of the list. last(list) Returns the last element in list or nil if list is empty. Tuples are also data structures which store a number of other structures within them. Unlike lists, they store elements in a contiguous block of memory. This means accessing a tuple element per index or getting the tuple size is a fast operation. Indexes start from zero. Elixir uses curly brackets to define tuples. Like lists, tuples can hold any value − {:ok, "hello"} To get the length of a tuple, use the tuple_size function as in the following program − IO.puts(tuple_size({:ok, "hello"})) The above program generates the following result − 2 To append a value to the tuple, use the Tuple.append function − tuple = {:ok, "Hello"} Tuple.append(tuple, :world) This will create and return a new tuple: {:ok, "Hello", :world} To insert a value at a given position, we can either use the Tuple.insert_at function or the put_elem function. Consider the following example to understand the same − tuple = {:bar, :baz} new_tuple_1 = Tuple.insert_at(tuple, 0, :foo) new_tuple_2 = put_elem(tuple, 1, :foobar) Notice that put_elem and insert_at returned new tuples. The original tuple stored in the tuple variable was not modified because Elixir data types are immutable. By being immutable, Elixir code is easier to reason about as you never need to worry if a particular code is mutating your data structure in place. What is the difference between lists and tuples? Lists are stored in memory as linked lists, meaning that each element in a list holds its value and points to the following element until the end of the list is reached. We call each pair of value and pointer a cons cell. This means accessing the length of a list is a linear operation: we need to traverse the whole list in order to figure out its size. Updating a list is fast as long as we are prepending elements. Tuples, on the other hand, are stored contiguously in memory. This means getting the tuple size or accessing an element by index is fast. However, updating or adding elements to tuples is expensive because it requires copying the whole tuple in memory. So far, we have not discussed any associative data structures, i.e., data structures that can associate a certain value (or multiple values) to a key. Different languages call these features with different names like dictionaries, hashes, associative arrays, etc. In Elixir, we have two main associative data structures: keyword lists and maps. In this chapter, we will focus on Keyword lists. In many functional programming languages, it is common to use a list of 2-item tuples as the representation of an associative data structure. In Elixir, when we have a list of tuples and the first item of the tuple (i.e. the key) is an atom, we call it a keyword list. Consider the following example to understand the same − list = [{:a, 1}, {:b, 2}] Elixir supports a special syntax for defining such lists. We can place the colon at the end of each atom and get rid of the tuples entirely. For example, list_1 = [{:a, 1}, {:b, 2}] list_2 = [a: 1, b: 2] IO.puts(list_1 == list_2) The above program will generate the following result − true Both of these represent a keyword list. Since keyword lists are also lists, we can use all the operations we used on lists on them. To retrieve the value associated with an atom in the keyword list, pass the atom as to [] after the name of the list − list = [a: 1, b: 2] IO.puts(list[:a]) The above program generates the following result − 1 Keyword lists have three special characteristics − Keys must be atoms. Keys are ordered, as specified by the developer. Keys can be given more than once. In order to manipulate keyword lists, Elixir provides the Keyword module. Remember, though, keyword lists are simply lists, and as such they provide the same linear performance characteristics as lists. The longer the list, the longer it will take to find a key, to count the number of items, and so on. For this reason, keyword lists are used in Elixir mainly as options. If you need to store many items or guarantee one-key associates with a maximum one-value, you should use maps instead. To access values associated with a given key, we use the Keyword.get function. It returns the first value associated with the given key. To get all the values, we use the Keyword.get_values function. For example − kl = [a: 1, a: 2, b: 3] IO.puts(Keyword.get(kl, :a)) IO.puts(Keyword.get_values(kl)) The above program will generate the following result − 1 [1, 2] To add a new value, use Keyword.put_new. If the key already exists, its value remains unchanged − kl = [a: 1, a: 2, b: 3] kl_new = Keyword.put_new(kl, :c, 5) IO.puts(Keyword.get(kl_new, :c)) When the above program is run, it produces a new Keyword list with additional key, c and generates the following result − 5 If you want to delete all entries for a key, use Keyword.delete; to delete only the first entry for a key, use Keyword.delete_first. kl = [a: 1, a: 2, b: 3, c: 0] kl = Keyword.delete_first(kl, :b) kl = Keyword.delete(kl, :a) IO.puts(Keyword.get(kl, :a)) IO.puts(Keyword.get(kl, :b)) IO.puts(Keyword.get(kl, :c)) This will delete the first b in the List and all the a in the list. When the above program is run, it will generate the following result − 0 Keyword lists are a convenient way to address content stored in lists by key, but underneath, Elixir is still walking through the list. That might be suitable if you have other plans for that list requiring walking through all of it, but it can be an unnecessary overhead if you are planning to use keys as your only approach to the data. This is where maps come to your rescue. Whenever you need a key-value store, maps are the “go to” data structure in Elixir. A map is created using the %{} syntax − map = %{:a => 1, 2 => :b} Compared to the keyword lists, we can already see two differences − Maps allow any value as a key. Maps’ keys do not follow any ordering. In order to acces value associated with a key, Maps use the same syntax as Keyword lists − map = %{:a => 1, 2 => :b} IO.puts(map[:a]) IO.puts(map[2]) When the above program is run, it generates the following result − 1 b To insert a key in a map, we use the Dict.put_new function which takes the map, new key and new value as arguments − map = %{:a => 1, 2 => :b} new_map = Dict.put_new(map, :new_val, "value") IO.puts(new_map[:new_val]) This will insert the key-value pair :new_val - "value" in a new map. When the above program is run, it generates the following result − "value" To update a value already present in the map, you can use the following syntax − map = %{:a => 1, 2 => :b} new_map = %{ map | a: 25} IO.puts(new_map[:a]) When the above program is run, it generates the following result − 25 In contrast to keyword lists, maps are very useful with pattern matching. When a map is used in a pattern, it will always match on a subset of the given value − %{:a => a} = %{:a => 1, 2 => :b} IO.puts(a) The above program generates the following result − 1 This will match a with 1. And hence, it will generate the output as 1. As shown above, a map matches as long as the keys in the pattern exist in the given map. Therefore, an empty map matches all maps. Variables can be used when accessing, matching and adding map keys − n = 1 map = %{n => :one} %{^n => :one} = %{1 => :one, 2 => :two, 3 => :three} The Map module provides a very similar API to the Keyword module with convenience functions to manipulate maps. You can use functions such as the Map.get, Map.delete, to manipulate maps. Maps come with a few interesting properties. When all the keys in a map are atoms, you can use the keyword syntax for convenience − map = %{:a => 1, 2 => :b} IO.puts(map.a) Another interesting property of maps is that they provide their own syntax for updating and accessing atom keys − map = %{:a => 1, 2 => :b} IO.puts(map.a) The above program generates the following result − 1 Note that to access atom keys in this way, it should exist or the program will fail to work. In Elixir, we group several functions into modules. We have already used different modules in the previous chapters such as the String module, Bitwise module, Tuple module, etc. In order to create our own modules in Elixir, we use the defmodule macro. We use the def macro to define functions in that module − defmodule Math do def sum(a, b) do a + b end end In the following sections, our examples are going to get longer in size, and it can be tricky to type them all in the shell. We need to learn how to compile Elixir code and also how to run Elixir scripts. It is always convenient to write modules into files so they can be compiled and reused. Let us assume we have a file named math.ex with the following content − defmodule Math do def sum(a, b) do a + b end end We can compile the files using the command −elixirc : $ elixirc math.ex This will generate a file named Elixir.Math.beam containing the bytecode for the defined module. If we start iex again, our module definition will be available (provided that iex is started in the same directory the bytecode file is in). For example, IO.puts(Math.sum(1, 2)) The above program will generate the following result − 3 In addition to the Elixir file extension .ex, Elixir also supports .exs files for scripting. Elixir treats both files exactly the same way, the only difference is in the objective. .ex files are meant to be compiled while .exs files are used for scripting. When executed, both extensions compile and load their modules into memory, although only .ex files write their bytecode to disk in the format of .beam files. For example, if we wanted to run the Math.sum in the same file, we can use the .exs in following way − defmodule Math do def sum(a, b) do a + b end end IO.puts(Math.sum(1, 2)) We can run it using the Elixir command − $ elixir math.exs The above program will generate the following result − 3 The file will be compiled in memory and executed, printing “3” as the result. No bytecode file will be created. Modules can be nested in Elixir. This feature of the language helps us organize our code in a better way. To create nested modules, we use the following syntax − defmodule Foo do #Foo module code here defmodule Bar do #Bar module code here end end The example given above will define two modules: Foo and Foo.Bar. The second can be accessed as Bar inside Foo as long as they are in the same lexical scope. If, later, the Bar module is moved outside the Foo module definition, it must be referenced by its full name (Foo.Bar) or an alias must be set using the alias directive discussed in the alias chapter. Note − In Elixir, there is no need to define the Foo module in order to define the Foo.Bar module, as the language translates all module names to atoms. You can define arbitrarilynested modules without defining any module in the chain. For example, you can define Foo.Bar.Baz without defining Foo or Foo.Bar. In order to facilitate software reuse, Elixir provides three directives – alias, require and import. It also provides a macro called use which is summarized below − # Alias the module so it can be called as Bar instead of Foo.Bar alias Foo.Bar, as: Bar # Ensure the module is compiled and available (usually for macros) require Foo # Import functions from Foo so they can be called without the `Foo.` prefix import Foo # Invokes the custom code defined in Foo as an extension point use Foo Let us now understand in detail about each directive. The alias directive allows you to set up aliases for any given module name. For example, if you want to give an alias 'Str' to the String module, you can simply write − alias String, as: Str IO.puts(Str.length("Hello")) The above program generates the following result − 5 An alias is given to the String module as Str. Now when we call any function using the Str literal, it actually references to the String module. This is very helpful when we use very long module names and want to substitute those with shorter ones in the current scope. NOTE − Aliases MUST start with a capital letter. Aliases are valid only within the lexical scope they are called in. For example, if you have 2 modules in a file and make an alias within one of the modules, that alias will not be accessible in the second module. If you give the name of an in built module, like String or Tuple, as an alias to some other module, to access the inbuilt module, you will need to prepend it with "Elixir.". For example, alias List, as: String #Now when we use String we are actually using List. #To use the string module: IO.puts(Elixir.String.length("Hello")) When the above program is run, it generates the following result − 5 Elixir provides macros as a mechanism for meta-programming (writing code that generates code). Macros are chunks of code that are executed and expanded at compilation time. This means, in order to use a macro, we need to guarantee that its module and implementation are available during compilation. This is done with the require directive. Integer.is_odd(3) When the above program is run, it will generate the following result − ** (CompileError) iex:1: you must require Integer before invoking the macro Integer.is_odd/1 In Elixir, Integer.is_odd is defined as a macro. This macro can be used as a guard. This means that, in order to invoke Integer.is_odd, we will need the Integer module. Use the require Integer function and run the program as shown below. require Integer Integer.is_odd(3) This time the program will run and produce the output as: true. In general, a module is not required before usage, except if we want to use the macros available in that module. An attempt to call a macro that was not loaded will raise an error. Note that like the alias directive, require is also lexically scoped. We will talk more about macros in a later chapter. We use the import directive to easily access functions or macros from other modules without using the fully-qualified name. For instance, if we want to use the duplicate function from the List module several times, we can simply import it. import List, only: [duplicate: 2] In this case, we are importing only the function duplicate (with argument list length 2) from List. Although :only is optional, its usage is recommended in order to avoid importing all the functions of a given module inside the namespace. :except could also be given as an option in order to import everything in a module except a list of functions. The import directive also supports :macros and :functions to be given to :only. For example, to import all macros, a user can write − import Integer, only: :macros Note that import too is Lexically scoped just like the require and the alias directives. Also note that 'import'ing a module also 'require's it. Although not a directive, use is a macro tightly related to require that allows you to use a module in the current context. The use macro is frequently used by developers to bring external functionality into the current lexical scope, often modules. Let us understand the use directive through an example − defmodule Example do use Feature, option: :value end Use is a macro that transforms the above into − defmodule Example do require Feature Feature.__using__(option: :value) end The use Module first requires the module and then calls the __using__ macro on Module. Elixir has great metaprogramming capabilities and it has macros to generate code at compile time. The __using__ macro is called in the above instance, and the code is injected into our local context. The local context is where the use macro was called at the time of compilation. A function is a set of statements organized together to perform a specific task. Functions in programming work mostly like function in Math. You give functions some input, they generate output based on the input provided. There are 2 types of functions in Elixir − Functions defined using the fn..end construct are anonymous functions. These functions are sometimes also called as lambdas. They are used by assigning them to variable names. Functions defined using the def keyword are named functions. These are native functions provided in Elixir. Just as the name implies, an anonymous function has no name. These are frequently passed to other functions. To define an anonymous function in Elixir, we need the fn and end keywords. Within these, we can define any number of parameters and function bodies separated by ->. For example, sum = fn (a, b) -> a + b end IO.puts(sum.(1, 5)) When running above program, is run, it generates the following result − 6 Note that these functions are not called like the named functions. We have a '.' between the function name and its arguments. We can also define these functions using the capture operator. This is an easier method to create functions. We will now define the above sum function using the capture operator, sum = &(&1 + &2) IO.puts(sum.(1, 2)) When the above program is run, it generates the following result − 3 In the shorthand version, our parameters are not named but are available to us as &1, &2, &3, and so on. Pattern matching is not only limited to variables and data structures. We can use pattern matching to make our functions polymorphic. For example, we will declare a function that can either take 1 or 2 inputs (within a tuple) and print them to the console, handle_result = fn {var1} -> IO.puts("#{var1} found in a tuple!") {var_2, var_3} -> IO.puts("#{var_2} and #{var_3} found!") end handle_result.({"Hey people"}) handle_result.({"Hello", "World"}) When the above program is run, it produces the following result − Hey people found in a tuple! Hello and World found! We can define functions with names so we can easily refer to them later. Named functions are defined within a module using the def keyword. Named functions are always defined in a module. To call named functions, we need to reference them using their module name. The following is the syntax for named functions − def function_name(argument_1, argument_2) do #code to be executed when function is called end Let us now define our named function sum within the Math module. defmodule Math do def sum(a, b) do a + b end end IO.puts(Math.sum(5, 6)) When running above program, it produces following result − 11 For 1-liner functions, there is a shorthand notation to define these functions, using do:. For example − defmodule Math do def sum(a, b), do: a + b end IO.puts(Math.sum(5, 6)) When running above program, it produces following result − 11 Elixir provides us the ability to define private functions that can be accessed from within the module in which they are defined. To define a private function, use defp instead of def. For example, defmodule Greeter do def hello(name), do: phrase <> name defp phrase, do: "Hello " end Greeter.hello("world") When the above program is run, it produces the following result − Hello world But if we just try to explicitly call phrase function, using the Greeter.phrase() function, it will raise an error. If we want a default value for an argument, we use the argument \\ value syntax − defmodule Greeter do def hello(name, country \\ "en") do phrase(country) <> name end defp phrase("en"), do: "Hello, " defp phrase("es"), do: "Hola, " end Greeter.hello("Ayush", "en") Greeter.hello("Ayush") Greeter.hello("Ayush", "es") When the above program is run, it produces the following result − Hello, Ayush Hello, Ayush Hola, Ayush Recursion is a method where the solution to a problem depends on the solutions to smaller instances of the same problem. Most computer programming languages support recursion by allowing a function to call itself within the program text. Ideally recursive functions have an ending condition. This ending condition, also known as the base case stops reentering the function and adding function calls to the stack. This is where the recursive function call stops. Let us consider the following example to further understand the recursive function. defmodule Math do def fact(res, num) do if num === 1 do res else new_res = res * num fact(new_res, num-1) end end end IO.puts(Math.fact(1,5)) When the above program is run, it generates the following result − 120 So in the above function, Math.fact, we are calculating the factorial of a number. Note that we are calling the function within itself. Let us now understand how this works. We have provided it with 1 and the number whose factorial we want to calculate. The function checks if the number is 1 or not and returns res if it is 1(Ending condition). If not then it creates a variable new_res and assigns it the value of previous res * current num. It returns the value returned by our function call fact(new_res, num-1). This repeats until we get num as 1. Once that happens, we get the result. Let us consider another example, printing each element of the list one by one. To do this, we will utilize the hd and tl functions of lists and pattern matching in functions − a = ["Hey", 100, 452, :true, "People"] defmodule ListPrint do def print([]) do end def print([head | tail]) do IO.puts(head) print(tail) end end ListPrint.print(a) The first print function is called when we have an empty list(ending condition). If not, then the second print function will be called which will divide the list in 2 and assign the first element of the list to head and the remaining of the list to tail. The head then gets printed and we call the print function again with the rest of the list, i.e., tail. When the above program is run, it produces the following result − Hey 100 452 true People Due to immutability, loops in Elixir (as in any functional programming language) are written differently from imperative languages. For example, in an imperative language like C, you will write − for(i = 0; i < 10; i++) { printf("%d", array[i]); } In the example given above, we are mutating both the array and the variable i. Mutating is not possible in Elixir. Instead, functional languages rely on recursion: a function is called recursively until a condition is reached that stops the recursive action from continuing. No data is mutated in this process. Let us now write a simple loop using recursion that prints hello n times. defmodule Loop do def print_multiple_times(msg, n) when n <= 1 do IO.puts msg end def print_multiple_times(msg, n) do IO.puts msg print_multiple_times(msg, n - 1) end end Loop.print_multiple_times("Hello", 10) When the above program is run, it produces the following result − Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello We have utilized function's pattern matching techniques and recursion to successfully implement a loop. Recursive definitions are difficult to understand but converting loops to recursion is easy. Elixir provides us the Enum module. This module is used for the most iterative looping calls as it is much easier to use those than trying to figure out recursive definitions for the same. We will discuss those in the next chapter. Your own recursive definitions should only be used when you dont find a solution using that module. Those functions are tail call optimized and quite fast. An enumerable is an object that may be enumerated. "Enumerated" means to count off the members of a set/collection/category one by one (usually in order, usually by name). Elixir provides the concept of enumerables and the Enum module to work with them. The functions in the Enum module are limited to, as the name says, enumerating values in data structures. Example of an enumerable data structure is a list, tuple, map, etc. The Enum module provides us with a little over 100 functions to deal with enums. We will discuss a few important functions in this chapter. All of these functions take an enumerable as the first element and a function as the second and work on them. The functions are described below. When we use all? function, the entire collection must evaluate to true otherwise false will be returned. For example, to check if all of the elements in the list are odd numbers, then. res = Enum.all?([1, 2, 3, 4], fn(s) -> rem(s,2) == 1 end) IO.puts(res) When the above program is run, it produces the following result − false This is because not all elements of this list are odd. As the name suggests, this function returns true if any element of the collection evaluates to true. For example − res = Enum.any?([1, 2, 3, 4], fn(s) -> rem(s,2) == 1 end) IO.puts(res) When the above program is run, it produces the following result − true This function divides our collection into small chunks of the size provided as the second argument. For example − res = Enum.chunk([1, 2, 3, 4, 5, 6], 2) IO.puts(res) When the above program is run, it produces the following result − [[1, 2], [3, 4], [5, 6]] It may be necessary to iterate over a collection without producing a new value, for this case we use the each function − Enum.each(["Hello", "Every", "one"], fn(s) -> IO.puts(s) end) When the above program is run, it produces the following result − Hello Every one To apply our function to each item and produce a new collection we use the map function. It is one of the most useful constructs in functional programming as it is quite expressive and short. Let us consider an example to understand this. We will double the values stored in a list and store it in a new list res − res = Enum.map([2, 5, 3, 6], fn(a) -> a*2 end) IO.puts(res) When the above program is run, it produces the following result − [4, 10, 6, 12] The reduce function helps us reduce our enumerable to a single value. To do this, we supply an optional accumulator (5 in this example) to be passed into our function; if no accumulator is provided, the first value is used − res = Enum.reduce([1, 2, 3, 4], 5, fn(x, accum) -> x + accum end) IO.puts(res) When the above program is run, it produces the following result − 15 The accumulator is the initial value passed to the fn. From the second call onwards the value returned from previous call is passed as accum. We can also use reduce without the accumulator − res = Enum.reduce([1, 2, 3, 4], fn(x, accum) -> x + accum end) IO.puts(res) When the above program is run, it produces the following result − 10 The uniq function removes duplicates from our collection and returns only the set of elements in the collection. For example − res = Enum.uniq([1, 2, 2, 3, 3, 3, 4, 4, 4, 4]) IO.puts(res) When running above program, it produces the following result − [1, 2, 3, 4] All the functions in the Enum module are eager. Many functions expect an enumerable and return a list back. This means that when performing multiple operations with Enum, each operation is going to generate an intermediate list until we reach the result. Let us consider the following example to understand this − odd? = &(odd? = &(rem(&1, 2) != 0) res = 1..100_000 |> Enum.map(&(&1 * 3)) |> Enum.filter(odd?) |> Enum.sum IO.puts(res) When the above program is run, it produces the following result − 7500000000 The example above has a pipeline of operations. We start with a range and then multiply each element in the range by 3. This first operation will now create and return a list with 100_000 items. Then we keep all odd elements from the list, generating a new list, now with 50_000 items, and then we sum all entries. The |> symbol used in the snippet above is the pipe operator: it simply takes the output from the expression on its left side and passes it as the first argument to the function call on its right side. It’s similar to the Unix | operator. Its purpose is to highlight the flow of data being transformed by a series of functions. Without the pipe operator, the code looks complicated − Enum.sum(Enum.filter(Enum.map(1..100_000, &(&1 * 3)), odd?)) We have many other functions, however, only a few important ones have been described here. Many functions expect an enumerable and return a list back. It means, while performing multiple operations with Enum, each operation is going to generate an intermediate list until we reach the result. Streams support lazy operations as opposed to eager operations by enums. In short, streams are lazy, composable enumerables. What this means is Streams do not perform an operation unless it is absolutely needed. Let us consider an example to understand this − odd? = &(rem(&1, 2) != 0) res = 1..100_000 |> Stream.map(&(&1 * 3)) |> Stream.filter(odd?) |> Enum.sum IO.puts(res) When the above program is run, it produces the following result − 7500000000 In the example given above, 1..100_000 |> Stream.map(&(&1 * 3)) returns a data type, an actual stream, that represents the map computation over the range 1..100_000. It has not yet evaluated this representation. Instead of generating intermediate lists, streams build a series of computations that are invoked only when we pass the underlying stream to the Enum module. Streams are useful when working with large, possibly infinite, collections. Streams and enums have many functions in common. Streams mainly provide the same functions provided by the Enum module which generated Lists as their return values after performing computations on input enumerables. Some of them are listed in the following table − chunk(enum, n, step, leftover \\ nil) Streams the enumerable in chunks, containing n items each, where each new chunk starts step elements into the enumerable. concat(enumerables) Creates a stream that enumerates each enumerable in an enumerable. each(enum, fun) Executes the given function for each item. filter(enum, fun) Creates a stream that filters elements according to the given function on enumeration. map(enum, fun) Creates a stream that will apply the given function on enumeration. drop(enum, n) Lazily drops the next n items from the enumerable. Structs are extensions built on top of maps that provide compile-time checks and default values. To define a struct, the defstruct construct is used − defmodule User do defstruct name: "John", age: 27 end The keyword list used with defstruct defines what fields the struct will have along with their default values. Structs take the name of the module they are defined in. In the example given above, we defined a struct named User. We can now create User structs by using a syntax similar to the one used to create maps − new_john = %User{}) ayush = %User{name: "Ayush", age: 20} megan = %User{name: "Megan"}) The above code will generate three different structs with values − %User{age: 27, name: "John"} %User{age: 20, name: "Ayush"} %User{age: 27, name: "Megan"} Structs provide compile-time guarantees that only the fields (and all of them) defined through defstruct will be allowed to exist in a struct. So you cannot define your own fields once you have created the struct in the module. When we discussed maps, we showed how we can access and update the fields of a map. The same techniques (and the same syntax) apply to structs as well. For example, if we want to update the user we created in the earlier example, then − defmodule User do defstruct name: "John", age: 27 end john = %User{} #john right now is: %User{age: 27, name: "John"} #To access name and age of John, IO.puts(john.name) IO.puts(john.age) When the above program is run, it produces the following result − John 27 To update a value in a struct, we will again use the same procedure that we used in the map chapter, meg = %{john | name: "Meg"} Structs can also be used in pattern matching, both for matching on the value of specific keys as well as for ensuring that the matching value is a struct of the same type as the matched value. Protocols are a mechanism to achieve polymorphism in Elixir. Dispatching on a protocol is available to any data type as long as it implements the protocol. Let us consider an example of using protocols. We used a function called to_string in the previous chapters to convert from other types to the string type. This is actually a protocol. It acts according to the input that is given without producing an error. This might seem like we are discussing pattern matching functions, but as we proceed further, it turns out different. Consider the following example to further understand the protocol mechanism. Let us create a protocol that will display if the given input is empty or not. We will call this protocol blank?. We can define a protocol in Elixir in the following way − defprotocol Blank do def blank?(data) end As you can see, we do not need to define a body for the function. If you are familiar with interfaces in other programming languages, you can think of a Protocol as essentially the same thing. So this Protocol is saying that anything that implements it must have an empty? function, although it is up to the implementor as to how the function responds. With the protocol defined, let us understand how to add a couple of implementations. Since we have defined a protocol, we now need to tell it how to handle the different inputs that it might get. Let us build on the example we had taken earlier. We will implement the blank protocol for lists, maps and strings. This will show if the thing we passed is blank or not. #Defining the protocol defprotocol Blank do def blank?(data) end #Implementing the protocol for lists defimpl Blank, for: List do def blank?([]), do: true def blank?(_), do: false end #Implementing the protocol for strings defimpl Blank, for: BitString do def blank?(""), do: true def blank?(_), do: false end #Implementing the protocol for maps defimpl Blank, for: Map do def blank?(map), do: map_size(map) == 0 end IO.puts(Blank.blank? []) IO.puts(Blank.blank? [:true, "Hello"]) IO.puts(Blank.blank? "") IO.puts(Blank.blank? "Hi") You can implement your Protocol for as many or as few types as you want, whatever makes sense for the usage of your Protocol. This was a pretty basic use case of protocols. When the above program is run, it produces the following result − true false true false Note − If you use this for any types other than those you defined the protocol for, it will produce an error. File IO is an integral part of any programming language as it allows the language to interact with the files on the file system. In this chapter, we will discuss two modules − Path and File. The path module is a very small module that can be considered as a helper module for filesystem operations. The majority of the functions in the File module expect paths as arguments. Most commonly, those paths will be regular binaries. The Path module provides facilities for working with such paths. Using functions from the Path module as opposed to just manipulating binaries is preferred since the Path module takes care of different operating systems transparently. It is to be observed that Elixir will automatically convert slashes (/) into backslashes (\) on Windows when performing file operations. Let us consider the following example to further understand the Path module − IO.puts(Path.join("foo", "bar")) When the above program is run, it produces the following result − foo/bar There are a lot of methods that the path module provides. You can have a look at the different methods here. These methods are frequently used if you are performing many file manipulation operations. The file module contains functions that allow us to open files as IO devices. By default, files are opened in binary mode, which requires developers to use the specific IO.binread and IO.binwrite functions from the IO module. Let us create a file called newfile and write some data to it. {:ok, file} = File.read("newfile", [:write]) # Pattern matching to store returned stream IO.binwrite(file, "This will be written to the file") If you go to open the file we just wrote into, content will be displayed in the following way − This will be written to the file Let us now understand how to use the file module. To open a file, we can use any one of the following 2 functions − {:ok, file} = File.open("newfile") file = File.open!("newfile") Let us now understand the difference between the File.open function and the File.open!() function. The File.open function always returns a tuple. If file is successfully opened, it returns the first value in the tuple as :ok and the second value is literal of type io_device. If an error is caused, it will return a tuple with first value as :error and second value as the reason. The File.open function always returns a tuple. If file is successfully opened, it returns the first value in the tuple as :ok and the second value is literal of type io_device. If an error is caused, it will return a tuple with first value as :error and second value as the reason. The File.open!() function on the other hand will return a io_device if file is successfully opened else it will raise an error. NOTE: This is the pattern followed in all of the file module functions we are going to discuss. The File.open!() function on the other hand will return a io_device if file is successfully opened else it will raise an error. NOTE: This is the pattern followed in all of the file module functions we are going to discuss. We can also specify the modes in which we want to open this file. To open a file as read only and in utf-8 encoding mode, we use the following code − file = File.open!("newfile", [:read, :utf8]) We have two ways to write to files. Let us see the first one using the write function from the File module. File.write("newfile", "Hello") But this should not be used if you are making multiple writes to the same file. Every time this function is invoked, a file descriptor is opened and a new process is spawned to write to the file. If you are doing multiple writes in a loop, open the file via File.open and write to it using the methods in IO module. Let us consider an example to understand the same − #Open the file in read, write and utf8 modes. file = File.open!("newfile_2", [:read, :utf8, :write]) #Write to this "io_device" using standard IO functions IO.puts(file, "Random text") You can use other IO module methods like IO.write and IO.binwrite to write to files opened as io_device. We have two ways to read from files. Let us see the first one using the read function from the File module. IO.puts(File.read("newfile")) When running this code, you should get a tuple with the first element as :ok and the second one as the contents of newfile We can also use the File.read! function to just get the contents of the files returned to us. Whenever you open a file using the File.open function, after you are done using it, you should close it using the File.close function − File.close(file) In Elixir, all code runs inside processes. Processes are isolated from each other, run concurrent to one another and communicate via message passing. Elixir’s processes should not be confused with operating system processes. Processes in Elixir are extremely lightweight in terms of memory and CPU (unlike threads in many other programming languages). Because of this, it is not uncommon to have tens or even hundreds of thousands of processes running simultaneously. In this chapter, we will learn about the basic constructs for spawning new processes, as well as sending and receiving messages between different processes. The easiest way to create a new process is to use the spawn function. The spawn accepts a function that will be run in the new process. For example − pid = spawn(fn -> 2 * 2 end) Process.alive?(pid) When the above program is run, it produces the following result − false The return value of the spawn function is a PID. This is a unique identifier for the process and so if you run the code above your PID, it will be different. As you can see in this example, the process is dead when we check to see if it alive. This is because the process will exit as soon as it has finished running the given function. As already mentioned, all Elixir codes run inside processes. If you run the self function you will see the PID for your current session − pid = self Process.alive?(pid) When the above program is run, it produces following result − true We can send messages to a process with send and receive them with receive. Let us pass a message to the current process and receive it on the same. send(self(), {:hello, "Hi people"}) receive do {:hello, msg} -> IO.puts(msg) {:another_case, msg} -> IO.puts("This one won't match!") end When the above program is run, it produces the following result − Hi people We sent a message to the current process using the send function and passed it to the PID of self. Then we handled the incoming message using the receive function. When a message is sent to a process, the message is stored in the process mailbox. The receive block goes through the current process mailbox searching for a message that matches any of the given patterns. The receive block supports guards and many clauses, such as case. If there is no message in the mailbox matching any of the patterns, the current process will wait until a matching message arrives. A timeout can also be specified. For example, receive do {:hello, msg} -> msg after 1_000 -> "nothing after 1s" end When the above program is run, it produces the following result − nothing after 1s NOTE − A timeout of 0 can be given when you already expect the message to be in the mailbox. The most common form of spawning in Elixir is actually via spawn_link function. Before taking a look at an example with spawn_link, let us understand what happens when a process fails. spawn fn -> raise "oops" end When the above program is run, it produces the following error − [error] Process #PID<0.58.00> raised an exception ** (RuntimeError) oops :erlang.apply/2 It logged an error but the spawning process is still running. This is because processes are isolated. If we want the failure in one process to propagate to another one, we need to link them. This can be done with the spawn_link function. Let us consider an example to understand the same − spawn_link fn -> raise "oops" end When the above program is run, it produces the following error − ** (EXIT from #PID<0.41.0>) an exception was raised: ** (RuntimeError) oops :erlang.apply/2 If you are running this in iex shell then the shell handles this error and does not exit. But if you run by first making a script file and then using elixir <file-name>.exs, the parent process will also be brought down due to this failure. Processes and links play an important role when building fault-tolerant systems. In Elixir applications, we often link our processes to supervisors which will detect when a process dies and start a new process in its place. This is only possible because processes are isolated and don’t share anything by default. And since processes are isolated, there is no way a failure in a process will crash or corrupt the state of another. While other languages will require us to catch/handle exceptions; in Elixir, we are actually fine with letting processes fail because we expect supervisors to properly restart our systems. If you are building an application that requires state, for example, to keep your application configuration, or you need to parse a file and keep it in memory, where would you store it? Elixir's process functionality can come in handy when doing such things. We can write processes that loop infinitely, maintain state, and send and receive messages. As an example, let us write a module that starts new processes that work as a key-value store in a file named kv.exs. defmodule KV do def start_link do Task.start_link(fn -> loop(%{}) end) end defp loop(map) do receive do {:get, key, caller} -> send caller, Map.get(map, key) loop(map) {:put, key, value} -> loop(Map.put(map, key, value)) end end end Note that the start_link function starts a new process that runs the loop function, starting with an empty map. The loop function then waits for messages and performs the appropriate action for each message. In the case of a :get message, it sends a message back to the caller and calls loop again, to wait for a new message. While the :put message actually invokes loop with a new version of the map, with the given key and value stored. Let us now run the following − iex kv.exs Now you should be in your iex shell. To test out our module, try the following − {:ok, pid} = KV.start_link # pid now has the pid of our new process that is being # used to get and store key value pairs # Send a KV pair :hello, "Hello" to the process send pid, {:put, :hello, "Hello"} # Ask for the key :hello send pid, {:get, :hello, self()} # Print all the received messages on the current process. flush() When the above program is run, it produces the following result − "Hello" In this chapter, we are going to explore sigils, the mechanisms provided by the language for working with textual representations. Sigils start with the tilde (~) character which is followed by a letter (which identifies the sigil) and then a delimiter; optionally, modifiers can be added after the final delimiter. Regexes in Elixir are sigils. We have seen their use in the String chapter. Let us again take an example to see how we can use regex in Elixir. # A regular expression that matches strings which contain "foo" or # "bar": regex = ~r/foo|bar/ IO.puts("foo" =~ regex) IO.puts("baz" =~ regex) When the above program is run, it produces the following result − true false Sigils support 8 different delimiters − ~r/hello/ ~r|hello| ~r"hello" ~r'hello' ~r(hello) ~r[hello] ~r{hello} ~r<hello> The reason behind supporting different delimiters is that different delimiters can be more suited for different sigils. For example, using parentheses for regular expressions may be a confusing choice as they can get mixed with the parentheses inside the regex. However, parentheses can be handy for other sigils, as we will see in the next section. Elixir supports Perl compatible regexes and also support modifiers. You can read up more about the use of regexes here. Other than regexes, Elixir has 3 more inbuilt sigils. Let us have a look at the sigils. The ~s sigil is used to generate strings, like double quotes are. The ~s sigil is useful, for example, when a string contains both double and single quotes − new_string = ~s(this is a string with "double" quotes, not 'single' ones) IO.puts(new_string) This sigil generates strings. When the above program is run, it produces the following result − "this is a string with \"double\" quotes, not 'single' ones" The ~c sigil is used to generate char lists − new_char_list = ~c(this is a char list containing 'single quotes') IO.puts(new_char_list) When the above program is run, it produces the following result − this is a char list containing 'single quotes' The ~w sigil is used to generate lists of words (words are just regular strings). Inside the ~w sigil, words are separated by whitespace. new_word_list = ~w(foo bar bat) IO.puts(new_word_list) When the above program is run, it produces the following result − foobarbat The ~w sigil also accepts the c, s and a modifiers (for char lists, strings and atoms, respectively), which specify the data type of the elements of the resulting list − new_atom_list = ~w(foo bar bat)a IO.puts(new_atom_list) When the above program is run, it produces the following result − [:foo, :bar, :bat] Besides lowercase sigils, Elixir supports uppercase sigils to deal with escaping characters and interpolation. While both ~s and ~S will return strings, the former allows escape codes and interpolation while the latter does not. Let us consider an example to understand this − ~s(String with escape codes \x26 #{"inter" <> "polation"}) # "String with escape codes & interpolation" ~S(String without escape codes \x26 without #{interpolation}) # "String without escape codes \\x26 without \#{interpolation}" We can easily create our own custom sigils. In this example, we will create a sigil to convert a string to uppercase. defmodule CustomSigil do def sigil_u(string, []), do: String.upcase(string) end import CustomSigil IO.puts(~u/tutorials point/) When we run the above code, it produces the following result − TUTORIALS POINT First we define a module called CustomSigil and within that module, we created a function called sigil_u. As there is no existing ~u sigil in the existing sigil space, we will use it. The _u indicates that we wish use u as the character after the tilde. The function definition must take two arguments, an input and a list. List comprehensions are syntactic sugar for looping through enumerables in Elixir. In this chapter we will use comprehensions for iteration and generation. When we looked at the Enum module in the enumerables chapter, we came across the map function. Enum.map(1..3, &(&1 * 2)) In this example, we will pass a function as the second argument. Each item in the range will be passed into the function, and then a new list will be returned containing the new values. Mapping, filtering, and transforming are very common actions in Elixir and so there is a slightly different way of achieving the same result as the previous example − for n <- 1..3, do: n * 2 When we run the above code, it produces the following result − [2, 4, 6] The second example is a comprehension, and as you can probably see, it is simply syntactic sugar for what you can also achieve if you use the Enum.map function. However, there are no real benefits to using a comprehension over a function from the Enum module in terms of performance. Comprehensions are not limited to lists but can be used with all enumerables. You can think of filters as a sort of guard for comprehensions. When a filtered value returns false or nil it is excluded from the final list. Let us loop over a range and only worry about even numbers. We will use the is_even function from the Integer module to check if a value is even or not. import Integer IO.puts(for x <- 1..10, is_even(x), do: x) When the above code is run, it produces the following result − [2, 4, 6, 8, 10] We can also use multiple filters in the same comprehension. Add another filter that you want after the is_even filter separated by a comma. In the examples above, all the comprehensions returned lists as their result. However, the result of a comprehension can be inserted into different data structures by passing the :into option to the comprehension. For example, a bitstring generator can be used with the :into option in order to easily remove all spaces in a string − IO.puts(for <<c <- " hello world ">>, c != ?\s, into: "", do: <<c>>) When the above code is run, it produces the following result − helloworld The above code removes all spaces from the string using c != ?\s filter and then using the :into option, it puts all the returned characters in a string. Elixir is a dynamically typed language, so all types in Elixir are inferred by the runtime. Nonetheless, Elixir comes with typespecs, which are a notation used for declaring custom data types and declaring typed function signatures (specifications). By default, Elixir provides some basic types, such as integer or pid, and also complex types: for example, the round function, which rounds a float to its nearest integer, takes a number as an argument (an integer or a float) and returns an integer. In the related documentation, the round typed signature is written as − round(number) :: integer The above description implies that the function on the left takes as argument what is specified in parenthesis and returns what is on the right of ::, i.e., Integer. Function specs are written with the @spec directive, placed right before the function definition. The round function can be written as − @spec round(number) :: integer def round(number), do: # Function implementation ... Typespecs support complex types as well, for example, if you want to return a list of integers, then you can use [Integer] While Elixir provides a lot of useful inbuilt types, it is convenient to define custom types when appropriate. This can be done when defining modules through the @type directive. Let us consider an example to understand the same − defmodule FunnyCalculator do @type number_with_joke :: {number, String.t} @spec add(number, number) :: number_with_joke def add(x, y), do: {x + y, "You need a calculator to do that?"} @spec multiply(number, number) :: number_with_joke def multiply(x, y), do: {x * y, "It is like addition on steroids."} end {result, comment} = FunnyCalculator.add(10, 20) IO.puts(result) IO.puts(comment) When the above program is run, it produces the following result − 30 You need a calculator to do that? NOTE − Custom types defined through @type are exported and available outside the module they are defined in. If you want to keep a custom type private, you can use the @typep directive instead of @type. Behaviors in Elixir (and Erlang) are a way to separate and abstract the generic part of a component (which becomes the behavior module) from the specific part (which becomes the callback module). Behaviors provide a way to − Define a set of functions that have to be implemented by a module. Ensure that a module implements all the functions in that set. If you have to, you can think of behaviors like interfaces in object oriented languages like Java: a set of function signatures that a module has to implement. Let us consider an example to create our own behavior and then use this generic behavior to create a module. We will define a behavior that greets people hello and goodbye in different languages. defmodule GreetBehaviour do @callback say_hello(name :: string) :: nil @callback say_bye(name :: string) :: nil end The @callback directive is used to list the functions that adopting modules will need to define. It also specifies the no. of arguments, their type and their return values. We have successfully defined a behavior. Now we will adopt and implement it in multiple modules. Let us create two modules implementing this behavior in English and Spanish. defmodule GreetBehaviour do @callback say_hello(name :: string) :: nil @callback say_bye(name :: string) :: nil end defmodule EnglishGreet do @behaviour GreetBehaviour def say_hello(name), do: IO.puts("Hello " <> name) def say_bye(name), do: IO.puts("Goodbye, " <> name) end defmodule SpanishGreet do @behaviour GreetBehaviour def say_hello(name), do: IO.puts("Hola " <> name) def say_bye(name), do: IO.puts("Adios " <> name) end EnglishGreet.say_hello("Ayush") EnglishGreet.say_bye("Ayush") SpanishGreet.say_hello("Ayush") SpanishGreet.say_bye("Ayush") When the above program is run, it produces the following result − Hello Ayush Goodbye, Ayush Hola Ayush Adios Ayush As you have already seen, we adopt a behaviour using the @behaviour directive in the module. We have to define all the functions implemented in the behaviour for all the child modules. This can roughly be considered equivalent to interfaces in OOP languages. Elixir has three error mechanisms: errors, throws and exits. Let us explore each mechanism in detail. Errors (or exceptions) are used when exceptional things happen in the code. A sample error can be retrieved by trying to add a number into a string − IO.puts(1 + "Hello") When the above program is run, it produces the following error − ** (ArithmeticError) bad argument in arithmetic expression :erlang.+(1, "Hello") This was a sample inbuilt error. We can raise errors using the raise functions. Let us consider an example to understand the same − #Runtime Error with just a message raise "oops" # ** (RuntimeError) oops Other errors can be raised with raise/2 passing the error name and a list of keyword arguments #Other error type with a message raise ArgumentError, message: "invalid argument foo" You can also define your own errors and raise those. Consider the following example − defmodule MyError do defexception message: "default message" end raise MyError # Raises error with default message raise MyError, message: "custom message" # Raises error with custom message We do not want our programs to abruptly quit but rather the errors need to be handled carefully. For this we use error handling. We rescue errors using the try/rescue construct. Let us consider the following example to understand the same − err = try do raise "oops" rescue e in RuntimeError -> e end IO.puts(err.message) When the above program is run, it produces the following result − oops We have handled errors in the rescue statement using pattern matching. If we do not have any use of the error, and just want to use it for identification purposes, we can also use the form − err = try do 1 + "Hello" rescue RuntimeError -> "You've got a runtime error!" ArithmeticError -> "You've got a Argument error!" end IO.puts(err) When running above program, it produces the following result − You've got a Argument error! NOTE − Most functions in the Elixir standard library are implemented twice, once returning tuples and the other time raising errors. For example, the File.read and the File.read! functions. The first one returned a tuple if the file was read successfully and if an error was encountered, this tuple was used to give the reason for the error. The second one raised an error if an error was encountered. If we use the first function approach, then we need to use case for pattern matching the error and take action according to that. In the second case, we use the try rescue approach for error prone code and handle errors accordingly. In Elixir, a value can be thrown and later be caught. Throw and Catch are reserved for situations where it is not possible to retrieve a value unless by using throw and catch. The instances are quite uncommon in practice except when interfacing with libraries. For example, let us now assume that the Enum module did not provide any API for finding a value and that we needed to find the first multiple of 13 in a list of numbers − val = try do Enum.each 20..100, fn(x) -> if rem(x, 13) == 0, do: throw(x) end "Got nothing" catch x -> "Got #{x}" end IO.puts(val) When the above program is run, it produces the following result − Got 26 When a process dies of “natural causes” (for example, unhandled exceptions), it sends an exit signal. A process can also die by explicitly sending an exit signal. Let us consider the following example − spawn_link fn -> exit(1) end In the example above, the linked process died by sending an exit signal with value of 1. Note that exit can also be “caught” using try/catch. For example − val = try do exit "I am exiting" catch :exit, _ -> "not really" end IO.puts(val) When the above program is run, it produces the following result − not really Sometimes it is necessary to ensure that a resource is cleaned up after some action that can potentially raise an error. The try/after construct allows you to do that. For example, we can open a file and use an after clause to close it–even if something goes wrong. {:ok, file} = File.open "sample", [:utf8, :write] try do IO.write file, "olá" raise "oops, something went wrong" after File.close(file) end When we run this program, it will give us an error. But the after statement will ensure that the file descriptor is closed upon any such event. Macros are one of the most advanced and powerful features of Elixir. As with all advanced features of any language, macros should be used sparingly. They make it possible to perform powerful code transformations in compilation time. We will now understand what macros are and how to use them in brief. Before we start talking about macros, let us first look at Elixir internals. An Elixir program can be represented by its own data structures. The building block of an Elixir program is a tuple with three elements. For example, the function call sum(1, 2, 3) is represented internally as − {:sum, [], [1, 2, 3]} The first element is the function name, the second is a keyword list containing metadata and the third is the arguments list. You can get this as the output in iex shell if you write the following − quote do: sum(1, 2, 3) Operators are also represented as such tuples. Variables are also represented using such triplets, except that the last element is an atom, instead of a list. When quoting more complex expressions, we can see that the code is represented in such tuples, which are often nested inside each other in a structure resembling a tree. Many languages would call such representations an Abstract Syntax Tree (AST). Elixir calls these quoted expressions. Now that we can retrieve the internal structure of our code, how do we modify it? To inject new code or values, we use unquote. When we unquote an expression it will be evaluated and injected into the AST. Let us consider an example(in iex shell) to understand the concept − num = 25 quote do: sum(15, num) quote do: sum(15, unquote(num)) When the above program is run, it produces the following result − {:sum, [], [15, {:num, [], Elixir}]} {:sum, [], [15, 25]} In the example for the quote expression, it did not automatically replace num with 25. We need to unquote this variable if we want to modify the AST. So now that we are familiar with quote and unquote, we can explore metaprogramming in Elixir using macros. In the simplest of terms macros are special functions designed to return a quoted expression that will be inserted into our application code. Imagine the macro being replaced with the quoted expression rather than called like a function. With macros we have everything necessary to extend Elixir and dynamically add code to our applications Let us implement unless as a macro. We will begin by defining the macro using the defmacro macro. Remember that our macro needs to return a quoted expression. defmodule OurMacro do defmacro unless(expr, do: block) do quote do if !unquote(expr), do: unquote(block) end end end require OurMacro OurMacro.unless true, do: IO.puts "True Expression" OurMacro.unless false, do: IO.puts "False expression" When the above program is run, it produces the following result − False expression What is happening here is our code is being replaced by the quoted code returned by the unless macro. We have unquoted the expression to evaluate it in current context and also unquoted the do block to execute it in its context. This example shows us metaprogramming using macros in elixir. Macros can be used in much more complex tasks but should be used sparingly. This is because metaprogramming in general is considered a bad practice and should be used only when necessary. Elixir provides excellent interoperability with Erlang libraries. Let us discuss a few libraries in brief. The built-in Elixir String module handles binaries that are UTF-8 encoded. The binary module is useful when you are dealing with binary data that is not necessarily UTF-8 encoded. Let us consider an example to further understand the Binary module − # UTF-8 IO.puts(String.to_char_list("Ø")) # binary IO.puts(:binary.bin_to_list "Ø") When the above program is run, it produces the following result − [216] [195, 152] The above example shows the difference; the String module returns UTF-8 codepoints, while :binary deals with raw data bytes. The crypto module contains hashing functions, digital signatures, encryption and more. This module is not part of the Erlang standard library, but is included with the Erlang distribution. This means you must list :crypto in your project’s applications list whenever you use it. Let us see an example using the crypto module − IO.puts(Base.encode16(:crypto.hash(:sha256, "Elixir"))) When the above program is run, it produces the following result − 3315715A7A3AD57428298676C5AE465DADA38D951BDFAC9348A8A31E9C7401CB The digraph module contains functions for dealing with directed graphs built of vertices and edges. After constructing the graph, the algorithms in there will help finding, for instance, the shortest path between two vertices, or loops in the graph. Note that the functions in :digraph alter the graph structure indirectly as a side effect, while returning the added vertices or edges. digraph = :digraph.new() coords = [{0.0, 0.0}, {1.0, 0.0}, {1.0, 1.0}] [v0, v1, v2] = (for c <- coords, do: :digraph.add_vertex(digraph, c)) :digraph.add_edge(digraph, v0, v1) :digraph.add_edge(digraph, v1, v2) for point <- :digraph.get_short_path(digraph, v0, v2) do {x, y} = point IO.puts("#{x}, #{y}") end When the above program is run, it produces the following result − 0.0, 0.0 1.0, 0.0 1.0, 1.0 The math module contains common mathematical operations covering trigonometry, exponential and logarithmic functions. Let us consider the following example to understand how the Math module works − # Value of pi IO.puts(:math.pi()) # Logarithm IO.puts(:math.log(7.694785265142018e23)) # Exponentiation IO.puts(:math.exp(55.0)) #... When the above program is run, it produces the following result − 3.141592653589793 55.0 7.694785265142018e23 The queue is a data structure that implements (double-ended) FIFO (first-in first-out) queues efficiently. The following example shows how a Queue module works − q = :queue.new q = :queue.in("A", q) q = :queue.in("B", q) {{:value, val}, q} = :queue.out(q) IO.puts(val) {{:value, val}, q} = :queue.out(q) IO.puts(val) When the above program is run, it produces the following result − A B 35 Lectures 3 hours Pranjal Srivastava 54 Lectures 6 hours Pranjal Srivastava, Harshit Srivastava 80 Lectures 9.5 hours Pranjal Srivastava 43 Lectures 4 hours Mohammad Nauman Print Add Notes Bookmark this page
[ { "code": null, "e": 2472, "s": 2182, "text": "Elixir is a dynamic, functional language designed for building scalable and maintainable applications. It leverages the Erlang VM, known for running low-latency, distributed and fault-tolerant systems, while also being successfully used in web developme...
Scant3R - Web Security Scanner - GeeksforGeeks
14 Sep, 2021 Vulnerability Scanning is the process of finding the security flaws in the web-based application which can compromise the web application and reveal sensitive data. Scanning can be done in a manual way as well as in an automated way. Manual testing takes a lot of time if the scope of the target domain is vast. So automated testing is a good approach to be followed. Scant3rR is an automated tool developed in the python language which tests the target domain for various types of vulnerabilities or flaws like XSS, Injection, LFI, etc. The tool contains various modules which can be used in the scanning process. Scant3R tool is open source and free to use. Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process: Python Installation Steps on Linux Step 1: Check whether Python Environment is Established or not, use the following command. python3 Step 2: Open up your Kali Linux terminal and move to Desktop using the following command. cd Desktop Step 3: You are on Desktop now create a new directory called Scant3R using the following command. In this directory, we will complete the installation of the Scant3R tool. mkdir Scant3R Step 4: Now switch to the Scant3R directory using the following command. cd Scant3R Step 5: Now you have to install the tool. You have to clone the tool from GitHub. git clone https://github.com/knassar702/scant3r.git Step 6: The tool has been downloaded successfully in the Scant3R directory. Now list out the contents of the tool by using the below command. ls Step 7: You can observe that there is a new directory created of the Scant3R tool that has been generated while we were installing the tool. Now move to that directory using the below command: cd scant3r Step 8: Once again to discover the contents of the tool, use the below command. ls Step 9: Download the required packages for running the tool, use the following command. sudo pip3 install -r requirements.txt Step 10: Now we are done with our installation, Use the below command to view the help (gives a better understanding of the tool) index of the tool. python3 scant3r.py -h Example 1: Using Scant3R Tool for Normal scan echo “http://testphp.vulnweb.com/search.php?test=query&searchFor=1&goButton=go” | python3 scant3r.py Example 2: Using Scant3R Tool to Add module echo “http://testphp.vulnweb.com/search.php?test=query&searchFor=1&goButton=go” | python3 scant3r.py -m headers Example 3: Using Scant3R Tool to add Random User-agents echo “http://testphp.vulnweb.com/search.php?test=query&searchFor=1&goButton=go” | python3 scant3r.py -R Example 4: Using Scant3R Tool Add custom headers echo “http://testphp.vulnweb.com/search.php?test=query&searchFor=1&goButton=go” | python3 scant3r.py -H “Auth: U2NhblQzcgo=\nNew: True” Example 5: Using Scant3R Tool Add timeout echo “http://testphp.vulnweb.com/search.php?test=query&searchFor=1&goButton=go” | python3 scant3r.py -t 1000 Example 6: Using Scant3R Tool Add threads echo “http://testphp.vulnweb.com/search.php?test=query&searchFor=1&goButton=go” | python3 scant3r.py -w 50 Example 7: Using Scant3R Tool Add http/https proxy echo “http://testphp.vulnweb.com/search.php?test=query&searchFor=1&goButton=go” | python3 scant3r.py -p http://127.0.0.1:80 Example 8: Using Scant3R Tool Add cookies echo “http://testphp.vulnweb.com/search.php?test=query&searchFor=1&goButton=go” | python3 scant3r.py -c ‘login=test%2Ftest’ Example 9: Using Scant3R Tool to Follow redirects echo “http://testphp.vulnweb.com/search.php?test=query&searchFor=1&goButton=go” | python3 scant3r.py -r Example 10: Using Scant3R Tool to Dump HTTP requests/responses echo “http://testphp.vulnweb.com/search.php?test=query&searchFor=1&goButton=go” | python3 scant3r.py -H “Auth: U2NhblQzcgo=” -d Example 11: Using Scant3R Tool to Remove logo echo “http://testphp.vulnweb.com/search.php?test=query&searchFor=1&goButton=go” | python3 scant3r.py –nologo Example 12: Using Scant3R Tool to use PMG Module cat waybackurls.txt | python3 scant3r.py -m PMG Example 13: Using Scant3R Tool to use Headers Module echo https://testphp.vulnweb.com|python3 scant3r.py -m headers Example 14: Using Scant3R Tool to use Lorsrf Module echo ‘http://testphp.vulnweb.com/’ | python3 scant3r.py -m lorsrf -w 50 -R -x ‘http://myhost.burpcollaborator.net’ Example 15: Using Scant3R Tool to use Paths Module echo ‘http://testphp.vulnweb.com/’| python3 scant3r.py -m paths -w 50 Example 16: Using Scant3R Tool to use Neon Module echo http://$$$$$.com/admin/ | python3 scant3r.py -m neon Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Thread functions in C/C++ nohup Command in Linux with Examples mv command in Linux with examples scp command in Linux with Examples Docker - COPY Instruction chown command in Linux with Examples nslookup command in Linux with Examples SED command in Linux | Set 2 Named Pipe or FIFO with example C program uniq Command in LINUX with examples
[ { "code": null, "e": 24015, "s": 23987, "text": "\n14 Sep, 2021" }, { "code": null, "e": 24675, "s": 24015, "text": "Vulnerability Scanning is the process of finding the security flaws in the web-based application which can compromise the web application and reveal sensitive data...
Array of multiples - JavaScript
We are required to write a JavaScript function that takes in two numbers, say m and n, and it returns an array of first n multiples of m. For example − If the numbers are 4 and 6 Then the output should be − const output = [4, 8, 12, 16, 20, 24] Following is the code − const num1 = 4; const num2 = 6; const multiples = (num1, num2) => { const res = []; for(let i = num1; i <= num1 * num2; i += num1){ res.push(i); }; return res; }; console.log(multiples(num1, num2)); Following is the output in the console − [ 4, 8, 12, 16, 20, 24 ]
[ { "code": null, "e": 1200, "s": 1062, "text": "We are required to write a JavaScript function that takes in two numbers, say m and n, and it returns an array of first n multiples of m." }, { "code": null, "e": 1241, "s": 1200, "text": "For example − If the numbers are 4 and 6" ...
Font Awesome - File Type Icons
This chapter explains the usage of Font Awesome File Type icons. Assume that custom is the CSS class name where we defined the size and color, as shown in the example given below. <html> <head> <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css"> <style> i.custom {font-size: 2em; color: gray;} </style> </head> <body> <i class = "fa fa-adjust custom"></i> </body> </html> The following table shows the usage and the results of Font Awesome File Type icons. Replace the < body > tag of the above program with the code given in the table to get the respective outputs − 26 Lectures 2 hours Neha Gupta 20 Lectures 2 hours Asif Hussain 43 Lectures 5 hours Sharad Kumar 411 Lectures 38.5 hours In28Minutes Official 71 Lectures 10 hours Chaand Sheikh 207 Lectures 33 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2746, "s": 2566, "text": "This chapter explains the usage of Font Awesome File Type icons. Assume that custom is the CSS class name where we defined the size and color, as shown in the example given below." }, { "code": null, "e": 3057, "s": 2746, "text": "<h...
Exception Handling using classes in C++ - GeeksforGeeks
07 Apr, 2021 In this article, we will discuss how to handle the exceptions using classes. Exception Handling: Exceptions are run-time anomalies or abnormal conditions that a program encounters during its execution. There are two types of exceptions: Synchronous Exception Asynchronous Exception(Ex: which are beyond the program’s control, Disc failure, etc). Synchronous Exception Asynchronous Exception(Ex: which are beyond the program’s control, Disc failure, etc). C++ provides the following specialized keywords for this purpose: try: represents a block of code that can throw an exception. catch: represents a block of code that is executed when a particular exception is thrown. throw: Used to throw an exception. Also used to list the exceptions that a function throws, but doesn’t handle itself. try: represents a block of code that can throw an exception. catch: represents a block of code that is executed when a particular exception is thrown. throw: Used to throw an exception. Also used to list the exceptions that a function throws, but doesn’t handle itself. Problem Statement: Create a class Numbers which has two data members a and b. Write iterative functions to find the GCD of two numbers. Write an iterative function to check whether any given number is prime or not. If found to be true, then throws an exception to class MyPrimeException. Define your own MyPrimeException class. Solution: Define a class named Number which has two private data members as a and b. Define two member functions as: int gcd(): to calculate the HCF of the two numbers. bool isPrime(): to check if the given number is prime or not. int gcd(): to calculate the HCF of the two numbers. bool isPrime(): to check if the given number is prime or not. Use constructor which is used to initialize the data members. Take another class named Temporary which will be called when an exception is thrown. Below is the implementation to illustrate the concept of Exception Handling using classes: C++ // C++ program to illustrate the concept // of exception handling using class #include <bits/stdc++.h> using namespace std; // Class declaration class Number { private: int a, b; public: // Constructors Number(int x, int y) { a = x; b = y; } // Function that find the GCD // of two numbers a and b int gcd() { // While a is not equal to b while (a != b) { // Update a to a - b if (a > b) a = a - b; // Otherwise, update b else b = b - a; } // Return the resultant GCD return a; } // Function to check if the // given number is prime bool isPrime(int n) { // Base Case if (n <= 1) return false; // Iterate over the range [2, N] for (int i = 2; i < n; i++) { // If n has more than 2 // factors, then return // false if (n % i == 0) return false; } // Return true return true; } }; // Empty class class MyPrimeException { }; // Driver Code int main() { int x = 13, y = 56; Number num1(x, y); // Print the GCD of X and Y cout << "GCD is = " << num1.gcd() << endl; // If X is prime if (num1.isPrime(x)) cout << x << " is a prime number" << endl; // If Y is prime if (num1.isPrime(y)) cout << y << " is a prime number" << endl; // Exception Handling if ((num1.isPrime(x)) || (num1.isPrime(y))) { // Try Block try { throw MyPrimeException(); } // Catch Block catch (MyPrimeException t) { cout << "Caught exception " << "of MyPrimeException " << "class." << endl; } } return 0; } GCD is = 1 13 is a prime number Caught exception of MyPrimeException class. C++-Exception Handling CPP-Basics cpp-exception C++ C++ Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Iterators in C++ STL Friend class and function in C++ Polymorphism in C++ Sorting a vector in C++ Header files in C/C++ and its uses C++ Program for QuickSort How to return multiple values from a function in C or C++? CSV file management using C++ Program to print ASCII Value of a character
[ { "code": null, "e": 24117, "s": 24086, "text": " \n07 Apr, 2021\n" }, { "code": null, "e": 24194, "s": 24117, "text": "In this article, we will discuss how to handle the exceptions using classes." }, { "code": null, "e": 24214, "s": 24194, "text": "Exception ...
Float and Double in C
Float is a datatype which is used to represent the floating point numbers. It is a 32-bit IEEE 754 single precision floating point number ( 1-bit for the sign, 8-bit for exponent, 23*-bit for the value. It has 6 decimal digits of precision. Here is the syntax of float in C language, float variable_name; Here is an example of float in C language, Live Demo #include<stdio.h> #include<string.h> int main() { float x = 10.327; int y = 28; printf("The float value : %f\n", x); printf("The sum of float and int variable : %f\n", (x+y)); return 0; } The float value : 10.327000 The sum of float and int variable : 38.327000 Double is also a datatype which is used to represent the floating point numbers. It is a 64-bit IEEE 754 double precision floating point number for the value. It has 15 decimal digits of precision. Here is the syntax of double in C language, double variable_name; Here is an example of double in C language, Live Demo #include<stdio.h> #include<string.h> int main() { float x = 10.327; double y = 4244.546; int z = 28; printf("The float value : %f\n", x); printf("The double value : %f\n", y); printf("The sum of float, double and int variable : %f\n", (x+y+z)); return 0; } The float value : 10.327000 The double value : 4244.546000 The sum of float, double and int variable : 4282.873000
[ { "code": null, "e": 1303, "s": 1062, "text": "Float is a datatype which is used to represent the floating point numbers. It is a 32-bit IEEE 754 single precision floating point number ( 1-bit for the sign, 8-bit for exponent, 23*-bit for the value. It has 6 decimal digits of precision." }, { ...
Bayesian Statistics. Hard to believe there was once a... | by James Andrew Godwin | Towards Data Science
This article builds on my previous article about Bootstrap Resampling. Bayesian models are a rich class of models, which can provide attractive alternatives to Frequentist models. Arguably the most well-known feature of Bayesian statistics is Bayes theorem, more on this later. With the recent advent of greater computational power and general acceptance, Bayes methods are now widely used in areas ranging from medical research to natural language processing (NLP) to understanding to web searches. In the early 20th century there was a big debate about the legitimacy of what is now called Bayesian, which is essentially a probabilistic way of doing some statistics — in contrast to the “Frequentist” camp that we are all intimately familiar with. To use the parlance of our times, it was the #Team Jacob vs #Team Edward debate of its time, among statisticians. The argument is now moot as almost everyone is both Bayesian and Frequentist. A good heuristic is that some problems are better handled by Frequentist methods and some with Bayesian methods. By the end of this article I hope you can appreciate this joke: A Bayesian is one who, vaguely expecting a horse, and catching a glimpse of a donkey, strongly believes she has seen a mule! A limited version of Bayes theorem was proposed by the eponymous Reverend Thomas Bayes (1702–1761). Bayes’ interest was in probabilities of gambling games. He also was an avid supporter of Sir Isaac Newton’s newfangled theory of calculus with his amazingly entitled publication, “An Introduction to the Doctrine of Fluxions, and a Defence of the Mathematicians Against the Objections of the Author of The Analyst.” In 1814, Pierre-Simon Laplace published a version of Bayes theorem similar to its modern form in the “Essai philosophique sur les probabilités.” Laplace applied Bayesian methods to problems in celestial mechanics. Solving these problems had great practical implications for ships in the late 18th/early 19th centuries. The geophysicist and mathematician Harold Jeffreys extensively used Bayes’ methods. WWII saw many successful applications of Bayesian methods: Andrey Kolmagorov, a Russian (née Soviet) statistician used Bayes methods to greatly improve artillery accuracy Alan Turing used Bayesian models to break German U-boat codes Bernard Koopman, French born American mathematician, helped the Allies ability to locate German U-boats by intercepting directional radio transmissions The latter half of the 20th century lead to the following notable advances in computational Bayesian methods: Statistical sampling using Monte Carlo methods; Stanislaw Ulam, John von Neuman; 1946, 1947 MCMC, or Markov Chain Monte Carlo; Metropolis et al. (1953) Journal of Chemical Physics Hastings (1970), Monte Carlo sampling methods using Markov chains and their application Geman and Geman (1984) Stochastic relaxation, Gibbs distributions and the Bayesian restoration of images Duane, Kennedy, Pendleton, and Roweth (1987), Hamiltonian MCMC Gelfand and Smith (1990), Sampling-based approaches to calculating marginal densities. With greater computational power and general acceptance, Bayes methods are now widely used in areas ranging from medical research to natural language understanding to web search. Among pragmatists, the common belief today is that some problems are better handled by frequentist methods and some with Bayesian methods. From my first article on the Central Limit Theorem (CLT), I established that you need “enough data” for the CLT to apply. Bootstrap sampling is a convenient way of obtaining more distributions that approach your underlying distribution. These are Frequentist tools; but what happens if you have too little data to reliably apply the CLT? As a probabilistic Bayesian statistician, I already have some estimates, admittedly, with a little bit of guesswork, but there is a way of combining that guesswork in an intelligent fashion with my data. And that is what Bayesian statistics is basically all about — you combine it and basically, that combination is a simple multiplication of the two probable probability distributions, the one that you guessed at, and the other one, that for which you have evidence. The more data you have, the prior distribution becomes less and less important and Frequentist methods can be used. But, with less data, Bayesian’s will give you a better answer. So how then do Bayesian and Frequentist methodologies differ? Simply stated: Bayesian methodologies use prior distributions to quantify what is known about the parameters Frequentists do not quantify anything about the parameters; instead using p-values and confidence intervals (CI’s) to express the unknowns about parameters Both methods are useful, converging with more and more data — but contrasted: Strict Frequentist approach Goal is a point estimate and CI Start from observations Re-compute model given new observations Examples: Mean estimate, t-test, ANOVA Bayesian approach Goal is posterior distribution Start from prior distribution (the guesswork) Update posterior (the belief/hypothesis) given new observations Examples: posterior distribution of mean, highest density interval (HDI) overlap Today no one is a strict Frequentist. Bayesian methodologies simply work, that is fact. Bayes theorem describes the probability of an event, based on prior knowledge (our guesswork) of conditions that might be related to the event, our data. Bayes theorem tells us how to combine these two probabilities. For example, if developing a disease like Alzheimer’s is related to age, then, using Bayes’ theorem, a person’s age can be used to more reliably assess the probability that they have Alzheimer’s, or cancer, or any other age-related disease. Bayes theorem is used to update the probability for a hypothesis; the hypothesis is this guesswork, this prior distribution thing. Prior means your prior belief, the belief that you have before you have evidence, and it is a way to update it. Because you get more information, you update your hypothesis, and so on and so forth. For those who do not know, or who have forgotten, let us derive Bayes theorem from the rule for conditional probability: Translates to “the probability of A happening given B is the case.” “The probability of B happening given A happens.” Eliminating P(A∩B) and doing very minor algebra: or, rearranging terms Which is Bayes theorem! This describes how one finds the conditional probability of event A given event B. You have a disease test, and the probability that you will get a positive test result given that you have the disease is really, really high; in other words the test has a very high accuracy rate. The problem is that there is a probability that you will get a positive test result even if you do not have the disease. And that you can simply calculate from Bayes law. The big point is, is that these probabilities are not the same as the probability that you will get a positive result given the disease is not the same as the probability that you will have the disease given a positive result. These are two different probability distributions. And what makes them so different is the probability of disease and the probability of a positive test result. So if the disease is rare, the probability of disease will be very, very small. Disease testing: A = Have disease, B = Tested positive. Using Bayes theorem we have deduced that a positive test result for this disease indicates that only 10% of the time the person will actually have the disease, because the incidence rate of the disease is an order of magnitude lower than the false positive rate. A sample population has the following probabilities of hair and eye color combinations. I will run the code below in a Jupyter Notebook to find the conditional probabilities: # begin with the importsimport pandas as pdimport numpy as npimport matplotlibfrom matplotlib import pyplot as pltimport scipyimport seaborn as snsimport itertools%matplotlib inline# create the dataframehair_eye = pd.DataFrame({ 'black': [0.11, 0.03, 0.03, 0.01], 'blond': [0.01, 0.16, 0.02, 0.03], 'brunette': [0.2, 0.14, 0.09, 0.05], 'red': [0.04, 0.03, 0.02, 0.02], }, index=['brown', 'blue', 'hazel', 'green'])hair_eye N.B: this is string index for eye color rather than a numeric zero-based index. hair_eye.loc[‘hazel’, ‘red’] The figures in the table above are the conditional probabilities. Note that in this case: P(hair|eye)=P(eye|hair)P(hair|eye)=P(eye|hair) Given these conditional probabilities, it is easy to compute the marginal probabilities by summing the probabilities in the rows and columns. The marginal probability is the probability along one variable (one margin) of the distribution. The marginal distributions must sum to unity (1). ## Compute the marginal distribution of each eye colorhair_eye[‘marginal_eye’] = hair_eye.sum(axis=1)hair_eye hair_eye.sum(axis=0) hair_eye.loc[‘marginal_hair’] = hair_eye.sum(axis=0)hair_eye.describe I have blue eyes. I wonder what the marginal probabilities of hair color are given that they have blue eyes? # probability of blue eyes given any hair color divided by total probability of blue eyes# marginal probabilities of hair color given blue eyes#blue_black(.03/.36) + blue_brunette(.14/.36) + blue_red(.03/.36) + blue_blond(.16/.36)blue = hair_eye.loc[‘blue’,:]/hair_eye.loc[‘blue’,’marginal_eye’]blue There is a formulation of Bayes theorem that is convenient to use for computational problems because we do not want to sum all of the possibilities to compute P(B), like in the example above. Here are more facts and relationships about conditional probabilities, largely arising from the fact that P(B) is so hard to calculate: Rewriting Bayes theorem: This is a mess, but we do not always need the complicated denominator, which is the probability of B. P(B) is our actual evidence, which is hard to come by. Remember that this is probabilistic and that we are working with smaller data samples than we are normally used to. Rewriting we get: Ignoring the constant k, because it is given that the evidence - P(B) - is presumed to be constant, we get: We interpret the reduced relationship above as follows: The proportional relationships apply to the observed data distributions, or to parameters in a model (partial slopes, intercept, error distributions, lasso constant, e.g.,). The above equations tell you how to combine your prior belief if you want to call that, which I call the prior distribution with your evidence. An important nuance is that while we cannot speak about exact values we can talk about distributions; we can talk about the shapes of the curves of the probability distribution curves. What we want is the so-called posterior distribution. That is what we want. What we do is guess at the prior distribution: what is the probability of A? What is the probability that something is true given the data that I have? What is the probability of A given B? what is the probability that something is true given the data I have? Some people will rephrase this as what is the probability that my hypothesis A is true given the data B? I might have very little data. Too little to do any Frequentist approaches; but I can estimate that with the little small amount of data I have, called the likelihood, I can estimate the probability that this data would be correct, given my hypothesis that I can calculate directly. Because I have the data, not a lot of data, it is too little for me to actually believe, but I have some data. And I have my hypothesis. And so I can do my calculations on my distributions. The prior distribution is the probability of my hypothesis, which I do not know — but I can guess it. If I am really bad at guessing, I am going to say that this prior distribution is a uniform distribution, it could be a Gaussian or any other shape. Now if I guess a uniform distribution I am still doing probabilistic statistics, Bayesian statistics, but I am getting really, really close to what Frequentists would do. In Bayesian, I will update this prior distribution as I get more data because I will say, “Hey!” at first I thought it was uniform. Now I see that this thing, this probability distribution actually has a mean somewhere in the middle. So I am now going to choose a different distribution. Or I’m going to modify my distribution to accommodate what I am seeing in my posterior. I am trying to make this prior distribution look similar in shape to my posterior distribution. And when I say similar in shape, that is actually very misleading. What I am trying to do is find a mathematical formula that will mix the probability of A and the probability of A given B similarly. Similar in type that the math, that the equation looks similar, as in the formulaic of the question and not the actual probabilities; we call that getting the conjugate prior. This is when you search for a distribution that is mathematically similar to what you believe to be the final distribution. This is formally referred to as searching for a conjugate prior. A beta distribution, because of its flexibility is often, but not always, used as the prior. To reiterate, the hypothesis is formalized as parameters in the model, P(A), and the likelihood, P(B|A), is the probability of the data given those parameters — this is easy to do, t-tests can do this! Given prior assumptions about the behavior of the parameters (the prior), produce a model which tells us the probability of observing our data, to compute new probability of our parameters. Thus the steps for working with a Bayes model are: Identify data relevant to the research question: e.g., measurement scales of the data Define a descriptive model for the data. For instance, pick a linear model formula or a beta distribution of (2,1) Specify a prior distribution of the parameters — this the formalization of the hypothesis. For example, thinking the error in the linear model is normally distributed as N(θ,σ2) Choose the Bayesian inference formula to compute posterior parameter probabilities Update Bayes model if more data is observed. This is key! The posterior distribution naturally updates as more data is added Simulate data values from realizations of the posterior distribution of the parameters The choice of the prior distribution is very important to Bayesian analysis. A prior should be convincing to a skeptical audience. Some heuristics to consider are: Domain knowledge (SME) Prior observations If poor knowledge use less informative prior Caution: the uniform prior is informative, you need to set the limits on the range of values One analytically and computationally simple choice is the before mentioned conjugate prior. When a likelihood is multiplied by a conjugate prior the distribution of the posterior is the same as the likelihood. Most named distributions have conjugates: As a health official for your city, you are interested in analyzing COVID-19 infection rates. You decide to sample 10 people at an intersection while the light is red and determine if they test positive for Covid — the test is fast and to avoid sampling bias we take the test to them. The data are binomially distributed; a person tests positive or tests negative — for the sake of simplicity, assume the test is 100% accurate. In this notebook example: Select a prior for the parameter p, the probability of having COVID-19. Using data, compute the likelihood. Compute the posterior and posterior distributions. Try another prior distribution. Add more data to our data set to updated the posterior distribution. The likelihood of the data and the posterior distribution are binomially distributed. The binomial distribution has one parameter we need to estimate, p, the probability. We can write this formally for k successes in N trials: The following code computes some basic summary statistics: sampled = [‘yes’,’no’,’yes’,’no’,’no’,’yes’,’no’,’no’,’no’,’yes’]positive = [1 if x is ‘yes’ else 0 for x in sampled]positive N = len(positive) # sample sizen_positive = sum(positive) # number of positive driversn_not = N — n_positive # number negativeprint(‘Tested positive= %d Tested negative= %d’ ‘\nProbability of having COVID-19= %.1f’ % (n_positive, n_not, n_positive / (n_positive+ n_not))) For the prior I will start with a uniform distribution as I do not know what to expect re Covid rates: N = 100p = np.linspace(.01, .99, num=N)pp = [1./N] * Nplt.plot(p, pp, linewidth=2, color=’blue’)plt.show() Next step: compute the likelihood. The likelihood is the probability of the data given the parameter, P(X|p). Each observation of each test as “positive” or “not” is a Bernoulli trial, so I choose the binomial distribution. def likelihood(p, data): k = sum(data) N = len(data) # Compute Binomial likelihood l = scipy.special.comb(N, k) * p**k * (1-p)**(N-k) # Normalize the likelihood to sum to unity return l/sum(l)l = likelihood(p, positive)plt.plot(p, l)plt.title(‘Likelihood function’)plt.xlabel(‘Parameter’)plt.ylabel(‘Likelihood’)plt.show() Now that we have a prior and a likelihood we can compute the posterior distribution of the parameter p: P(p|X). N.B. The computational methods used here are simplified for the purpose of illustration. Computationally efficient code must be used! def posterior(prior, like): post = prior * like # compute the product of the probabilities return post / sum(post) # normalize the distributiondef plot_post(prior, like, post, x): maxy = max(max(prior), max(like), max(post)) plt.figure(figsize=(12, 4)) plt.plot(x, like, label=’likelihood’, linewidth=12, color=’black’, alpha=.2) plt.plot(x, prior, label=’prior’) plt.plot(x, post, label=’posterior’, color=’green’) plt.ylim(0, maxy) plt.xlim(0, 1) plt.title(‘Density of prior, likelihood and posterior’) plt.xlabel(‘Parameter value’) plt.ylabel(‘Density’) plt.legend() post = posterior(pp, l)plot_post(pp, l, post, p) print(‘Maximum of the prior density = %.3f’ % max(pp))print(‘Maximum likelihood = %.3f’ % max(l))print(‘MAP = %.3f’ % max(post)) With a uniform prior distribution, the posterior is just the likelihood. The key point is that the Frequentist probabilities are identical to the Bayesian posterior distribution given a uniform prior. From the chart above, I chose the conjugate prior of the Binomial distribution which is the beta distribution. The beta distribution is defined on the interval 0 ≤ Beta(P|A, B)≤10 ≤ Beta(P|A, B)≤ 1. The beta distribution has two parameters, a and b, which determine the shape. plt.figure(figsize=(12, 8))alpha = [.5, 1, 2, 3, 4]beta = alpha[:]x = np.linspace(.001, .999, num=100) #100 samplesfor i, (a, b) in enumerate(itertools.product(alpha, beta)): plt.subplot(len(alpha), len(beta), i+1) plt.plot(x, scipy.stats.beta.pdf(x, a, b)) plt.title(‘(a, b) = ({}, {})’.format(a,b))plt.tight_layout() I still do not know a lot about the behavior of drivers at this intersection who may or may not have COVID-19, so I pick a rather uninformative or broad beta distribution as the prior for the hypothesis. I choose a symmetric prior with a=2 and b=2: def beta_prior(x, a, b): l = scipy.stats.beta.pdf(p, a, b) # compute likelihood return l / l.sum() # normalize and returnpp = beta_prior(p, 2, 2)post = posterior(pp, l)plot_post(pp, l, post, p) Take note that the mode of the posterior is close to the mode of the likelihood, but has shifted toward the mode of the prior. This behavior of Bayesian posteriors to be shifted toward the prior is known as the shrinkage property: the tendency of the maximum likelihood point of the posterior is said to shrink toward the maximum likelihood point of the prior. Let us update the model with 10 new observations to our data set. Note that the more observations added to the model moves the posterior distribution closer to the likelihood. N.B. With large datasets, it might require HUGE amounts of data to see convergence in behavior of the posterior and the likelihood. new_samples = [’yes’,’no’,’no’,’no’,’no’, ‘yes’,’no’,’yes’,’no’,’no’] # new data to update model, n = 20new_positive = [1 if x is ‘yes’ else 0 for x in new_samples]l = likelihood(p, positive+ new_positive)post = posterior(pp, l)plot_post(pp, l, post, p) A credible interval is an interval on the Bayesian posterior distribution. The credible interval is sometimes called the highest density interval (HDI). For instance, the 90% credible interval encompasses 90% of the posterior distribution with the highest probability density. It can be confusing since both credible intervals of Bayesian and confidence intervals of Frequentist are abbreviated the same (CI). Luckily, the credible interval is the Bayesian analog of the Frequentist confidence interval. However, they are conceptually different. The confidence interval is chosen on the distribution of a test statistic, whereas the credible interval is computed on the posterior distribution of the parameter. For symmetric distributions, the credible interval can be numerically the same as the confidence interval. However, in the general case, these two quantities can be quite different. Now we plot the posterior distribution of the parameter of the binomial distribution parameter p. The 95% credible interval, or HDI, is also computed and displayed: num_samples = 100000lower_q, upper_q = [.025, .975]# Caution, this code assumes a symmetric prior distribution and will not work in the general casedef plot_ci(p, post, num_samples, lower_q, upper_q): # Compute a large sample by resampling with replacement samples = np.random.choice(p, size=num_samples, replace=True, p=post) ci = scipy.percentile(samples, [lower_q*100, upper_q*100]) # compute the quantiles interval = upper_q — lower_q plt.title(‘Posterior density with %.3f credible interval’ % interval) plt.plot(p, post, color=’blue’) plt.xlabel(‘Parameter value’) plt.ylabel(‘Density’) plt.axvline(x=ci[0], color=’red’) plt.axvline(x=ci[1], color=’red’) print(‘The %.3f credible interval is %.3f to %.3f’ % (interval, lower_q, upper_q)) plot_ci(p, post, num_samples, lower_q, upper_q) Because the posterior distribution above is symmetric, like the beta prior we chose, the analysis is identical to CI’s in the frequentist approach. We can be 95% confident that around 40% of driver’s tested at this intersection during a red light will have COVID-19! This info is very useful for health agencies to allocate resources appropriately. If you remember the joke in the third paragraph, about the Bayesian who vaguely suspected a horse and caught a fleeting glimpse of a donkey and strongly suspects seeing a mule — I hope you can now assign each clause of the joke the appropriate part Bayes theorem. Check out my next piece on linear regression and using bootstrap with regression models. Find me on Linkedin Physicist cum Data Scientist- Available for new opportunity | SaaS | Sports | Start-ups | Scale-ups
[ { "code": null, "e": 243, "s": 172, "text": "This article builds on my previous article about Bootstrap Resampling." }, { "code": null, "e": 672, "s": 243, "text": "Bayesian models are a rich class of models, which can provide attractive alternatives to Frequentist models. Arguab...
How to get the device’s IMEI/ESN number programmatically in android?
This example demonstrates how do I get the device’s IMEI/ESN number programmatically in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/button" android:text="Check IEMI number" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_above="@id/textView" android:layout_marginBottom="20sp"/> <TextView android:id="@+id/textView" android:textSize="16sp" android:hint="Your IEMI number" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true"/> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.telephony.TelephonyManager; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { Button button; TextView textView; String IMEINumber; private static final int REQUEST_CODE = 101; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); button = findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_CODE); return; } IMEINumber = telephonyManager.getDeviceId(); textView.setText(IMEINumber); } }); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { switch (requestCode) { case REQUEST_CODE: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "Permission granted.", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "Permission denied.", Toast.LENGTH_SHORT).show(); } } } } } Step 4 − Add the following code to androidManifest.xml <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code.
[ { "code": null, "e": 1159, "s": 1062, "text": "This example demonstrates how do I get the device’s IMEI/ESN number programmatically in android." }, { "code": null, "e": 1288, "s": 1159, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill al...
How to compile 32-bit program on 64- bit gcc in C and C++
Nowadays the compiler comes with default 64-bit version. Sometimes we need to compile and execute a code into some 32bit system. In that time, we have to use this feature. At first, we have to check the current target version of the gcc compiler. To check this, we have to type this command. gcc –v Using built-in specs. COLLECT_GCC=gcc COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/7/lto-wrapper OFFLOAD_TARGET_NAMES=nvptx-none OFFLOAD_TARGET_DEFAULT=1 Target: x86_64-linux-gnu ........... ........... ........... Here it is showing that Target is x86_64. So we are using the 64-bit version of gcc. Now to use the 32-bit system, we have to write the following command. gcc –m32 program_name.c Sometimes this command may generate some error like below. This indicates that the standard library of gcc is missing. In that situation we have to install them. In file included from test_c.c:1:0: /usr/include/stdio.h:27:10: fatal error: bits/libc-header-start.h: No such file or directory #include <bits/libc-header-start.h> ^~~~~~~~~~~~~~~~~~~~~~~~~~ compilation terminated. Now, to install the standard library for gcc, we have to write the following commands. sudo apt-get install gcc-multilib sudo apt-get install g++-multilib Now by using this code we will see the differences of executing in 32-bit system and the 64-bit system. #include<stdio.h> main(){ printf("The Size is: %lu\n", sizeof(long)); } $ gcc test_c.c test_c.c:3:1: warning: return type defaults to ‘int’ [-Wimplicit-int] main(){ ^~~~ $ ./a.out The Size is: 8 $ gcc -m32 test_c.c test_c.c:3:1: warning: return type defaults to ‘int’ [-Wimplicit-int] main(){ ^~~~ test_c.c: In function ‘main’: test_c.c:4:28: warning: format ‘%lu’ expects argument of type ‘long unsigned int’, but argument 2 has type ‘unsigned int’ [-Wformat=] printf("The Size is: %lu\n", sizeof(long)); ~~^ %u $ ./a.out The Size is: 4
[ { "code": null, "e": 1234, "s": 1062, "text": "Nowadays the compiler comes with default 64-bit version. Sometimes we need to compile and execute a code into some 32bit system. In that time, we have to use this feature." }, { "code": null, "e": 1354, "s": 1234, "text": "At first, ...
Explain Asynchronous vs Deferred JavaScript - GeeksforGeeks
26 Mar, 2020 Generally, when we use a script tag to load any JavaScript code, the HTML parsing is paused by the browser when it encounters the script tag and it starts to download the JavaScript file first. The HTML elements script tag will not be executed until the browser is done with downloading the script and executing it. The browser waits till the script gets downloaded, executed and after this, it processes the rest of the page. In modern browsers, the script tends to be larger than HTML file, hence their download size is large and processing time will be longer. This increases the load time of the page and restricts the user to navigate through the website. To solve this problem, async and defer attributes come into play. Syntax: A normal script is included in the page in the following way. <script src = "script.js"></script> When HTML parser finds this element, a request is sent to the server to get the script. Asynchronous: When we use the async attribute the script is downloaded asynchronously with the rest of the page without pausing the HTML parsing and the contents of the page are processed and displayed. Once the script is downloaded, the HTML parsing will be paused and the script’s execution will happen. Once the execution is done, HTML parsing will then resume. The page and other scripts don’t wait for async scripts and async scripts also don’t wait for them. It is great for independent scripts and externally located scripts. Syntax:<script async src = "script.js"></script> <script async src = "script.js"></script> Deferred: The defer attribute tells the browser not to interfere with the HTML parsing and only to execute the script file once the HTML document has been fully parsed. Whenever a script with this attribute is encountered, the downloading of the script starts asynchronously in the background and when the scripts get downloaded, it is executed only after the HTML parsing is finished. Syntax:<script defer src = "script.js"></script> <script defer src = "script.js"></script> Asynchronous vs Deferred: JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to Open URL in New Tab using JavaScript ? Difference Between PUT and PATCH Request Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 25104, "s": 25076, "text": "\n26 Mar, 2020" }, { "code": null, "e": 25531, "s": 25104, "text": "Generally, when we use a script tag to load any JavaScript code, the HTML parsing is paused by the browser when it encounters the script tag and it starts to downl...
How to create an AWS session using Boto3 library in Python?
When a user wants to use AWS services using lambda or programming code, a session needs to set up first to access AWS services. An AWS session could be default as well as customized based on needs. Problem Statement − Use Boto3 library in Python to create an AWS session. Step 1 − To create an AWS session, first set up authentication credentials. Users can find it in IAM console or alternatively, create the credential file manually. By default, its location is at ~/.aws/credentials Example [default] aws_access_key_id = YOUR_ACCESS_KEY aws_secret_access_key = YOUR_SECRET_ACCESS_KEY aws_session_token = YOUR_SESSION_TOKEN region = REGION_NAME Step 2 − Install Boto3 using the command - pip install boto3 Step 3 − Import the Boto3 library. Step 4 − If creating the session with default credential, use Session() with no parameter. Step 5 − If session is customized, pass the following parameters − aws_access_key_id (string) -- AWS access key ID aws_access_key_id (string) -- AWS access key ID aws_secret_access_key (string) -- AWS secret access key aws_secret_access_key (string) -- AWS secret access key aws_session_token (string) -- AWS temporary session token aws_session_token (string) -- AWS temporary session token region_name (string) -- Default region when creating new connections region_name (string) -- Default region when creating new connections profile_name (string) -- The name of a profile to use. If not given, then the default profile is used. profile_name (string) -- The name of a profile to use. If not given, then the default profile is used. The following code creates an AWS session for default as well as customized credentials − import boto3 # To create default session: def create_aws_session(): session = boto3.session.Session() #it creates the default session and can use to connect with any AWS service return session print(create_aws_session()) # To Create customized session: def create_customized_session(aws_access_key, aws_secret_key, aws_token, region_name=None,profile_name=None): session = boto3.session.Session(aws_access_key_id=aws_access_key, aws_secret_access_key=aws_secret_key, aws_session_token = aws_token, region_name=region_name, profile_name = profile_name) # Here, region_name and profile_name are optional parameters and default value is None Print(session) return session #if default region_name is not present or NONE and region_name is not passed in #credential file/calling parameter Session(region_name=None) Session(region_name=None) #if default region_name is present and region_name is passed in credential file/calling #parameter Session(region_name=YOUR_REGION_NAME) Session(region_name= YOUR_REGION_NAME)
[ { "code": null, "e": 1190, "s": 1062, "text": "When a user wants to use AWS services using lambda or programming code, a session needs to set up first to access AWS services." }, { "code": null, "e": 1260, "s": 1190, "text": "An AWS session could be default as well as customized ...
Construct XOR tree by Given leaf nodes of Perfect Binary Tree - GeeksforGeeks
03 Jun, 2021 Given the leaf nodes of a perfect binary tree, the task is to construct the XOR tree and print the root node of this tree. An XOR tree is a tree whose parent node is the XOR of the left child and the right child node of the tree. Parent node = Left child node ^ Right child node Examples: Input: arr = {40, 32, 12, 1, 4, 3, 2, 7} Output: Nodes of the XOR tree 7 5 2 8 13 7 5 40 32 12 1 4 3 2 7Root: 7 Explanation: Input: arr = {5, 7, 2, 8, 12, 3, 9, 1} Output: Nodes of the XOR tree 15 8 7 2 10 15 8 5 7 2 8 12 3 9 1Root: 15 Input: arr = {4, 2, 10, 1, 14, 30, 21, 7} Output: Nodes of the XOR tree 15 13 2 6 11 16 18 4 2 10 1 14 30 21 7 Root: 15 Input: arr = {1, 2, 3, 4} Output: Nodes of the XOR tree 4 3 7 1 2 3 4 Root: 4 Input: arr = {47, 62, 8, 10, 4, 3, 1, 7} Output: Nodes of the XOR tree 18 19 1 17 2 7 6 47 62 8 10 4 3 1 7 Root: 18 Approach: Since it’s a perfect binary tree, there are a total of 2^h-1 nodes, where h is the height of the XOR tree.Since leaf nodes of a perfect binary tree are given, the root node is built by first building the left and right subtrees recursively.Every node in the left and right subtrees is formed by performing the XOR operation on their children. Since it’s a perfect binary tree, there are a total of 2^h-1 nodes, where h is the height of the XOR tree. Since leaf nodes of a perfect binary tree are given, the root node is built by first building the left and right subtrees recursively. Every node in the left and right subtrees is formed by performing the XOR operation on their children. Below is the implementation of the above approach. C++ C Java Python C# Javascript // C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Maximum size for xor treeint maxsize = 100005; // Allocating space to xor treevector<int> xor_tree(maxsize); // A recursive function that constructs xor tree// for vector array[start.....end].// x is index of current node in XOR tree void construct_Xor_Tree_Util(vector<int> current, int start, int end, int x){ // If there is one element in vector array, store it // in current node of XOR tree if (start == end) { xor_tree[x] = current[start]; // cout<<xor_tree[x]<<" x"; return; } // for left subtree int left = x * 2 + 1; // for right subtree int right = x * 2 + 2; // for getting the middle index from corner indexes. int mid = start + (end - start) / 2; // Build the left and the right subtrees by xor operation construct_Xor_Tree_Util(current, start, mid, left); construct_Xor_Tree_Util(current, mid + 1, end, right); // merge the left and right subtrees by // XOR operation xor_tree[x] = (xor_tree[left] ^ xor_tree[right]);} // Function to construct XOR tree from the given vector array.// This function calls construct_Xor_Tree_Util() to fill the// allocated memory of xor_tree vector arrayvoid construct_Xor_Tree(vector<int> arr, int n){ construct_Xor_Tree_Util(arr, 0, n - 1, 0);} // Driver Codeint main(){ // leaf nodes of Perfect Binary Tree vector<int> leaf_nodes = { 40, 32, 12, 1, 4, 3, 2, 7 }; int n = leaf_nodes.size(); // Build the xor tree construct_Xor_Tree(leaf_nodes, n); // Height of xor tree int x = (int)(ceil(log2(n))); // Maximum size of xor tree int max_size = 2 * (int)pow(2, x) - 1; cout << "Nodes of the XOR Tree:\n"; for (int i = 0; i < max_size; i++) { cout << xor_tree[i] << " "; } // Root node is at index 0 considering // 0-based indexing in XOR Tree int root = 0; // print value at root node cout << "\nRoot: " << xor_tree[root];} // C program to build xor tree by leaf nodes// of perfect binary tree and root node value of tree #include <math.h>#include <stdio.h> // maximum size for xor tree#define maxsize 10005 // Allocating space to xor treeint xortree[maxsize]; // A recursive function that constructs xor tree// for array[start.....end].// x is index of current node in xor tree stvoid construct_Xor_Tree_Util(int current[], int start, int end, int x){ // If there is one element in array, store it // in current node of xor tree and return if (start == end) { xortree[x] = current[start]; // printf("%d ", xortree[x]); return; } // for left subtree int left = x * 2 + 1; // for right subtree int right = x * 2 + 2; // for getting the middle index // from corner indexes. int mid = start + (end - start) / 2; // Build the left and the right subtrees // by xor operation construct_Xor_Tree_Util(current, start, mid, left); construct_Xor_Tree_Util(current, mid + 1, end, right); // merge the left and right subtrees by // XOR operation xortree[x] = (xortree[left] ^ xortree[right]);} // Function to construct XOR tree from given array.// This function calls construct_Xor_Tree_Util()// to fill the allocated memory of xort arrayvoid construct_Xor_Tree(int arr[], int n){ int i = 0; for (i = 0; i < maxsize; i++) xortree[i] = 0; construct_Xor_Tree_Util(arr, 0, n - 1, 0);} // Driver Codeint main(){ // leaf nodes of Binary Tree int leaf_nodes[] = { 40, 32, 12, 1, 4, 3, 2, 7 }, i = 0; int n = sizeof(leaf_nodes) / sizeof(leaf_nodes[0]); // Build the xor tree construct_Xor_Tree(leaf_nodes, n); // Height of xor tree int x = (int)(ceil(log2(n))); // Maximum size of xor tree int max_size = 2 * (int)pow(2, x) - 1; printf("Nodes of the XOR tree\n"); for (i = 0; i < max_size; i++) { printf("%d ", xortree[i]); } // Root node is at index 0 considering // 0-based indexing in XOR Tree int root = 0; // print value at root node printf("\nRoot: %d", xortree[root]);} // Java implementation of the above approachclass GFG{ // Maximum size for xor treestatic int maxsize = 100005; // Allocating space to xor treestatic int []xor_tree = new int[maxsize]; // A recursive function that constructs xor tree// for vector array[start.....end].// x is index of current node in XOR tree static void construct_Xor_Tree_Util(int []current, int start, int end, int x){ // If there is one element in vector array, store it // in current node of XOR tree if (start == end) { xor_tree[x] = current[start]; // System.out.print(xor_tree[x]+" x"; return; } // for left subtree int left = x * 2 + 1; // for right subtree int right = x * 2 + 2; // for getting the middle index from corner indexes. int mid = start + (end - start) / 2; // Build the left and the right subtrees by xor operation construct_Xor_Tree_Util(current, start, mid, left); construct_Xor_Tree_Util(current, mid + 1, end, right); // merge the left and right subtrees by // XOR operation xor_tree[x] = (xor_tree[left] ^ xor_tree[right]);} // Function to conXOR tree from the given vector array.// This function calls construct_Xor_Tree_Util() to fill the// allocated memory of xor_tree vector arraystatic void construct_Xor_Tree(int []arr, int n){ construct_Xor_Tree_Util(arr, 0, n - 1, 0);} // Driver Codepublic static void main(String[] args){ // leaf nodes of Perfect Binary Tree int []leaf_nodes = { 40, 32, 12, 1, 4, 3, 2, 7 }; int n = leaf_nodes.length; // Build the xor tree construct_Xor_Tree(leaf_nodes, n); // Height of xor tree int x = (int)(Math.ceil(Math.log(n))); // Maximum size of xor tree int max_size = 2 * (int)Math.pow(2, x) - 1; System.out.print("Nodes of the XOR Tree:\n"); for (int i = 0; i < max_size; i++) { System.out.print(xor_tree[i]+ " "); } // Root node is at index 0 considering // 0-based indexing in XOR Tree int root = 0; // print value at root node System.out.print("\nRoot: " + xor_tree[root]);}} // This code is contributed by PrinciRaj1992 # Python3 implementation of the above approachfrom math import ceil,log # Maximum size for xor treemaxsize = 100005 # Allocating space to xor treexor_tree = [0] * maxsize # A recursive function that constructs xor tree# for vector array[start.....end].# x is index of current node in XOR treedef construct_Xor_Tree_Util(current, start, end, x): # If there is one element in vector array, store it # in current node of XOR tree if (start == end): xor_tree[x] = current[start] # cout<<xor_tree[x]<<" x" return # for left subtree left = x * 2 + 1 # for right subtree right = x * 2 + 2 # for getting the middle index from corner indexes. mid = start + (end - start) // 2 # Build the left and the right subtrees by xor operation construct_Xor_Tree_Util(current, start, mid, left) construct_Xor_Tree_Util(current, mid + 1, end, right) # merge the left and right subtrees by # XOR operation xor_tree[x] = (xor_tree[left] ^ xor_tree[right]) # Function to construct XOR tree from the given vector array.# This function calls construct_Xor_Tree_Util() to fill the# allocated memory of xor_tree vector arraydef construct_Xor_Tree(arr, n): construct_Xor_Tree_Util(arr, 0, n - 1, 0) # Driver Codeif __name__ == '__main__': # leaf nodes of Perfect Binary Tree leaf_nodes = [40, 32, 12, 1, 4, 3, 2, 7] n = len(leaf_nodes) # Build the xor tree construct_Xor_Tree(leaf_nodes, n) # Height of xor tree x = (ceil(log(n, 2))) # Maximum size of xor tree max_size = 2 * pow(2, x) - 1 print("Nodes of the XOR Tree:") for i in range(max_size): print(xor_tree[i], end=" ") # Root node is at index 0 considering # 0-based indexing in XOR Tree root = 0 # prevalue at root node print("\nRoot: ", xor_tree[root]) # This code is contributed by mohit kumar 29 // C# implementation of the above approachusing System;using System.Collections.Generic; class GFG{ // Maximum size for xor treestatic int maxsize = 100005; // Allocating space to xor treestatic int []xor_tree = new int[maxsize]; // A recursive function that constructs xor tree// for vector array[start.....end].// x is index of current node in XOR treestatic void construct_Xor_Tree_Util(int []current, int start, int end, int x){ // If there is one element in vector array, store it // in current node of XOR tree if (start == end) { xor_tree[x] = current[start]; // Console.Write(xor_tree[x]+" x"; return; } // for left subtree int left = x * 2 + 1; // for right subtree int right = x * 2 + 2; // for getting the middle index from corner indexes. int mid = start + (end - start) / 2; // Build the left and the right subtrees by xor operation construct_Xor_Tree_Util(current, start, mid, left); construct_Xor_Tree_Util(current, mid + 1, end, right); // merge the left and right subtrees by // XOR operation xor_tree[x] = (xor_tree[left] ^ xor_tree[right]);} // Function to conXOR tree from the given vector array.// This function calls construct_Xor_Tree_Util() to fill the// allocated memory of xor_tree vector arraystatic void construct_Xor_Tree(int []arr, int n){ construct_Xor_Tree_Util(arr, 0, n - 1, 0);} // Driver Codepublic static void Main(String[] args){ // leaf nodes of Perfect Binary Tree int []leaf_nodes = { 40, 32, 12, 1, 4, 3, 2, 7 }; int n = leaf_nodes.Length; // Build the xor tree construct_Xor_Tree(leaf_nodes, n); // Height of xor tree int x = (int)(Math.Ceiling(Math.Log(n))); // Maximum size of xor tree int max_size = 2 * (int)Math.Pow(2, x) - 1; Console.Write("Nodes of the XOR Tree:\n"); for (int i = 0; i < max_size; i++) { Console.Write(xor_tree[i] + " "); } // Root node is at index 0 considering // 0-based indexing in XOR Tree int root = 0; // print value at root node Console.Write("\nRoot: " + xor_tree[root]);}} // This code is contributed by PrinciRaj1992 <script> // Javascript implementation of the above approach // Maximum size for xor treevar maxsize = 100005; // Allocating space to xor treevar xor_tree = Array(maxsize); // A recursive function that constructs xor tree// for vector array[start.....end].// x is index of current node in XOR tree function construct_Xor_Tree_Util(current, start, end, x){ // If there is one element in vector array, store it // in current node of XOR tree if (start == end) { xor_tree[x] = current[start]; // cout<<xor_tree[x]<<" x"; return; } // for left subtree var left = x * 2 + 1; // for right subtree var right = x * 2 + 2; // for getting the middle index from corner indexes. var mid = start + parseInt((end - start) / 2); // Build the left and the right subtrees by xor operation construct_Xor_Tree_Util(current, start, mid, left); construct_Xor_Tree_Util(current, mid + 1, end, right); // merge the left and right subtrees by // XOR operation xor_tree[x] = (xor_tree[left] ^ xor_tree[right]);} // Function to construct XOR tree from the given vector array.// This function calls construct_Xor_Tree_Util() to fill the// allocated memory of xor_tree vector arrayfunction construct_Xor_Tree(arr, n){ construct_Xor_Tree_Util(arr, 0, n - 1, 0);} // Driver Code// leaf nodes of Perfect Binary Treevar leaf_nodes = [40, 32, 12, 1, 4, 3, 2, 7 ];var n = leaf_nodes.length;// Build the xor treeconstruct_Xor_Tree(leaf_nodes, n);// Height of xor treevar x = (Math.ceil(Math.log2(n)));// Maximum size of xor treevar max_size = 2 * Math.pow(2, x) - 1;document.write( "Nodes of the XOR Tree:<br>");for (var i = 0; i < max_size; i++) { document.write( xor_tree[i] + " ");}// Root node is at index 0 considering// 0-based indexing in XOR Treevar root = 0;// print value at root nodedocument.write( "<br>Root: " + xor_tree[root]); </script> Nodes of the XOR Tree: 7 5 2 8 13 7 5 40 32 12 1 4 3 2 7 Root: 7 Time Complexity: O(N) mohit kumar 29 princiraj1992 rutvik_56 Binary Tree Bitwise-XOR Bit Magic Recursion Tree Recursion Bit Magic Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Cyclic Redundancy Check and Modulo-2 Division Little and Big Endian Mystery Program to find whether a given number is power of 2 Binary representation of a given number Bits manipulation (Important tactics) 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 Program for Sum of the digits of a given number
[ { "code": null, "e": 25308, "s": 25280, "text": "\n03 Jun, 2021" }, { "code": null, "e": 25588, "s": 25308, "text": "Given the leaf nodes of a perfect binary tree, the task is to construct the XOR tree and print the root node of this tree. An XOR tree is a tree whose parent node ...
PySpark - SparkConf
To run a Spark application on the local/cluster, you need to set a few configurations and parameters, this is what SparkConf helps with. It provides configurations to run a Spark application. The following code block has the details of a SparkConf class for PySpark. class pyspark.SparkConf ( loadDefaults = True, _jvm = None, _jconf = None ) Initially, we will create a SparkConf object with SparkConf(), which will load the values from spark.* Java system properties as well. Now you can set different parameters using the SparkConf object and their parameters will take priority over the system properties. In a SparkConf class, there are setter methods, which support chaining. For example, you can write conf.setAppName(“PySpark App”).setMaster(“local”). Once we pass a SparkConf object to Apache Spark, it cannot be modified by any user. Following are some of the most commonly used attributes of SparkConf − set(key, value) − To set a configuration property. set(key, value) − To set a configuration property. setMaster(value) − To set the master URL. setMaster(value) − To set the master URL. setAppName(value) − To set an application name. setAppName(value) − To set an application name. get(key, defaultValue=None) − To get a configuration value of a key. get(key, defaultValue=None) − To get a configuration value of a key. setSparkHome(value) − To set Spark installation path on worker nodes. setSparkHome(value) − To set Spark installation path on worker nodes. Let us consider the following example of using SparkConf in a PySpark program. In this example, we are setting the spark application name as PySpark App and setting the master URL for a spark application to → spark://master:7077. The following code block has the lines, when they get added in the Python file, it sets the basic configurations for running a PySpark application. --------------------------------------------------------------------------------------- from pyspark import SparkConf, SparkContext conf = SparkConf().setAppName("PySpark App").setMaster("spark://master:7077") sc = SparkContext(conf=conf) --------------------------------------------------------------------------------------- Print Add Notes Bookmark this page
[ { "code": null, "e": 2072, "s": 1805, "text": "To run a Spark application on the local/cluster, you need to set a few configurations and parameters, this is what SparkConf helps with. It provides configurations to run a Spark application. The following code block has the details of a SparkConf class...