title stringlengths 3 221 | text stringlengths 17 477k | parsed listlengths 0 3.17k |
|---|---|---|
How to specify the name for drop-down list in HTML5 ? | 26 Mar, 2021
Drop-down lists are also another way to allow people to choose only one choice from a number of alternatives. Since the default option is usually the first item on the list, using the drop-down list can be a safe choice if you know that one option is always preferred over the others. The drop-down list can only be used when the user must pick between choices since it does not provide the user with the option of not selecting something. In HTML 5, the name attribute defines the name of a drop-down list. After a form has been entered, the name attribute in JavaScript is used to refer to elements or form data.
Syntax:
<select>
<option value=””>option1</option>
<option value=””>option2</option>
</select>
<select> is a tag used to construct a dropdown list, as seen in the above code. The <option> tag, which is embedded in the select tag, is an attribute value or attributes for the selection list, with the value representing whether the option is chosen, disabled, or has certain other properties. We can use CSS to show our selection list effects and set positions like this.
Attributes: The following are some of the attributes that are included in the <select> tag
Name: This attribute is useful for naming a control that will be sent to the server to be detected and to receive necessary value.
Multiple:The user will pick several values from the selector list if the attribute is set to “multiple.”
Size: The Size parameter determines the size of the scrolling box that covers the Dropdown list. It’s also useful for highlighting multiple choices from a list.
Value: This attribute indicates whether a choice in the selection list has been chosen.
Selected: Selected attributes allow the display of already selected list items from the list at the very beginning of page loads.
Label: Label attribute works as another approach for labeling options value.
Disabled: If we want a drop-down list with a disable option, we can use the disabled attribute in the HTML select list.
onChange:When a user selects a choice from a dropdown list, an event is triggered on item selection.
onFocus: When the user hovers the mouse over a selection list option to pick it, an event is triggered to select the object.
Form: This attribute is used to specify one or more similar types to the select field.
disabled: With the support of this attribute, we will keep our drop-down list hidden from the user.
required: When filling out a form, we want to make it clear that this field allows the user to choose some value from a list before submitting the form, so in this situation, we define that the user must choose any value from the list.
Examples 1: Below is the code that illustrates a drop-down list with a name attribute.
HTML
<!DOCTYPE html><html> <body style="text-align:center;"> <h1>GeeksForGeeks Practice</h1> <h2>GFG Courses</h2> <form action="/action_page.php"> <label for="course"> Select a course from drop-down list : </label> <select name="course" id="course"> <option value="1"> Getting Started with C </option> <option value="2"> DSA Self-Paced </option> <option value="3"> Complete Interview Preparation </option> <option value="4"> Java Collections </option> <option value="5"> 30 Days Of Code </option> </select> <br><br> <input type="submit" value="Submit"> </form></body> </html>
Output:
Output
Example 2:
HTML
<!DOCTYPE html><html> <head> <style> body{ background-color: lightblue;} h1{ color: green; text-align: center; } h2{ color: yellow; text-align: center; } p{ font-family: verdana; font-size: 20px; } </style></head> <body> <h1>GeeksForGeeks</h1> <h2>GFG Contest</h2> <h3>"Coding Question of the Day"</h3> <p> Given a sorted deck of cards numbered 1 to N.<br> 1) We pick up 1 card and put it on the back of the deck.<br><br> 2) Now, we pick up another card, it turns out the deck..<br><br> </p> <form action="/action_page.php"> <label for="course"> Choose a Programming Language : </label> <select name="course" id="course"> <option value="1">C++</option> <option value="2">C</option> <option value="3">JAVA</option> <option value="4">Python</option> <option value="5">C#</option> </select><br><br> <input type="submit" value="Select"> </form></body> </html>
Output:
HTML-Attributes
HTML-Questions
HTML-Tags
HTML5
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
Form validation using jQuery
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Mar, 2021"
},
{
"code": null,
"e": 643,
"s": 28,
"text": "Drop-down lists are also another way to allow people to choose only one choice from a number of alternatives. Since the default option is usually the first item on the list, u... |
Comparing Path of Two Files in Java | 26 Oct, 2020
The path of two files can be compared lexicographically in Java using java.io.file.compareTo() method. It is useful to raise a Red Flag by the operating system when the program is requesting the file modification access which is already in use by another program.
To compare the path of the file, compareTo() method of File Class is used. compareTo() method compares two abstract path-names lexicographically. The ordering defined by this method is dependent upon the operating system.
Parameters: This method requires a single parameter i.e.the abstract pathname that is to be compared.
Return Value: This method returns 0 if the argument is equal to this abstract pathname, a negative value if the abstract pathname is lexicographically less than the argument, and a value greater than 0 if the abstract pathname is lexicographically greater than the argument respectively.
Example:
Java
// Comparing path of two files in Java import java.io.File; public class GFG { public static void main(String[] args) { File file1 = new File("/home/mayur/GFG.java"); File file2 = new File("/home/mayur/file.txt"); File file3 = new File("/home/mayur/GFG.java"); // Path comparision if (file1.compareTo(file2) == 0) { System.out.println( "paths of file1 and file2 are same"); } else { System.out.println( "Paths of file1 and file2 are not same"); } // Path comparision if (file1.compareTo(file3) == 0) { System.out.println( "paths of file1 and file3 are same"); } else { System.out.println( "Paths of file1 and file3 are not same"); } }}
Output:
Java-Files
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Oct, 2020"
},
{
"code": null,
"e": 292,
"s": 28,
"text": "The path of two files can be compared lexicographically in Java using java.io.file.compareTo() method. It is useful to raise a Red Flag by the operating system when the progra... |
Data Structures | Linked List | Question 15 | 28 Jun, 2021
Given pointer to a node X in a singly linked list. Only one pointer is given, pointer to head node is not given, can we delete the node X from given linked list?(A) Possible if X is not last node. Use following two steps (a) Copy the data of next of X to X. (b) Delete next of X.(B) Possible if size of linked list is even.(C) Possible if size of linked list is odd(D) Possible if X is not first node. Use following two steps (a) Copy the data of next of X to X. (b) Delete next of X.Answer: (A)Explanation: Following are simple steps.
struct node *temp = X->next;
X->data = temp->data;
X->next = temp->next;
free(temp);
Quiz of this Question
Data Structures
Data Structures-Linked List
Linked Lists
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Data Structures | Array | Question 2
Data Structures | Queue | Question 2
Amazon Interview Experience for SDE-II
Data Structures | Hash | Question 5
Data Structures | Binary Trees | Question 1
Data Structures | Misc | Question 9
Data Structures | Queue | Question 11
FIFO vs LIFO approach in Programming
Bit manipulation | Swap Endianness of a number
Advantages of vector over array in C++ | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 588,
"s": 52,
"text": "Given pointer to a node X in a singly linked list. Only one pointer is given, pointer to head node is not given, can we delete the node X from given linked list?(A) Possible ... |
Print squares of first n natural numbers without using *, / and – | 02 Dec, 2021
Given a natural number ‘n’, print squares of first n natural numbers without using *, / and -. Examples :
Input: n = 5
Output: 0 1 4 9 16
Input: n = 6
Output: 0 1 4 9 16 25
We strongly recommend to minimize the browser and try this yourself first.Method 1: The idea is to calculate next square using previous square value. Consider the following relation between square of x and (x-1). We know square of (x-1) is (x-1)2 – 2*x + 1. We can write x2 as
x2 = (x-1)2 + 2*x - 1
x2 = (x-1)2 + x + (x - 1)
When writing an iterative program, we can keep track of previous value of x and add the current and previous values of x to current value of square. This way we don’t even use the ‘-‘ operator.Below is the implementation of above approach:
C++
Java
Python 3
C#
PHP
Javascript
// C++ program to print squares of first 'n' natural numbers// without using *, / and -#include<iostream>using namespace std; void printSquares(int n){ // Initialize 'square' and previous value of 'x' int square = 0, prev_x = 0; // Calculate and print squares for (int x = 0; x < n; x++) { // Update value of square using previous value square = (square + x + prev_x); // Print square and update prev for next iteration cout << square << " "; prev_x = x; }} // Driver program to test above functionint main(){ int n = 5; printSquares(n);}
// Java program to print squares// of first 'n' natural numbers// without using *, / andimport java.io.*; class GFG{static void printSquares(int n){ // Initialize 'square' and // previous value of 'x' int square = 0, prev_x = 0; // Calculate and // print squares for (int x = 0; x < n; x++) { // Update value of square // using previous value square = (square + x + prev_x); // Print square and update // prev for next iteration System.out.print( square + " "); prev_x = x; }} // Driver Codepublic static void main (String[] args){ int n = 5; printSquares(n);}} // This code is contributed// by akt_mit
# Python 3 program to print squares of first# 'n' natural numbers without using *, / and -def printSquares(n): # Initialize 'square' and previous # value of 'x' square = 0; prev_x = 0; # Calculate and print squares for x in range(0, n): # Update value of square using # previous value square = (square + x + prev_x) # Print square and update prev # for next iteration print(square, end = " ") prev_x = x # Driver Coden = 5;printSquares(n); # This code is contributed# by Akanksha Rai
// C# program to print squares// of first 'n' natural numbers// without using *, / andusing System; public class GFG{ static void printSquares(int n){ // Initialize 'square' and // previous value of 'x' int square = 0, prev_x = 0; // Calculate and // print squares for (int x = 0; x < n; x++) { // Update value of square // using previous value square = (square + x + prev_x); // Print square and update // prev for next iteration Console.Write( square + " "); prev_x = x; }} // Driver Code static public void Main (){ int n = 5; printSquares(n); }} // This code is contributed// by ajit
<?php// PHP program to print squares// of first 'n' natural numbers// without using *, / and - function printSquares($n){ // Initialize 'square' and // previous value of 'x' $square = 0; $prev_x = 0; // Calculate and // print squares for ($x = 0; $x < $n; $x++) { // Update value of square // using previous value $square = ($square + $x + $prev_x); // Print square and update // prev for next iteration echo $square, " "; $prev_x = $x; }} // Driver Code $n = 5; printSquares($n); // This code is contributed by ajit?>
<script>// JavaScript program to print squares of first 'n' natural numbers// without using *, / and - function printSquares(n) { // Initialize 'square' and previous value of 'x' let square = 0, prev_x = 0; // Calculate and print squares for (let x = 0; x < n; x++) { // Update value of square using previous value square = (square + x + prev_x); // Print square and update prev for next iteration document.write(square + " "); prev_x = x; } } // Driver program to test above function let n = 5; printSquares(n); // This code is contributed by Surbhi Tyagi </script>
Output:
0 1 4 9 16
Time Complexity: O(n)
Auxiliary Space: O(1)
Method 2: Sum of first n odd numbers are squares of natural numbers from 1 to n. For example 1, 1+3, 1+3+5, 1+3+5+7, 1+3+5+7+9, ....Following is program based on above concept. Thanks to Aadithya Umashanker and raviteja for suggesting this method.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to print squares of first 'n' natural numbers// without using *, / and -#include<iostream>using namespace std; void printSquares(int n){ // Initialize 'square' and first odd number int square = 0, odd = 1; // Calculate and print squares for (int x = 0; x < n; x++) { // Print square cout << square << " "; // Update 'square' and 'odd' square = square + odd; odd = odd + 2; }} // Driver program to test above functionint main(){ int n = 5; printSquares(n);}
// Java program to print// squares of first 'n'// natural numbers without// using *, / and -import java.io.*; class GFG{static void printSquares(int n){ // Initialize 'square' // and first odd number int square = 0, odd = 1; // Calculate and // print squares for (int x = 0; x < n; x++) { // Print square System.out.print(square + " " ); // Update 'square' // and 'odd' square = square + odd; odd = odd + 2; }} // Driver Codepublic static void main (String[] args){ int n = 5; printSquares(n);}} // This code is contributed// by ajit
# Python3 program to print squares# of first 'n' natural numbers# without using *, / and - def printSquares(n): # Initialize 'square' and # first odd number square = 0 odd = 1 # Calculate and print squares for x in range(0 , n): # Print square print(square, end= " ") # Update 'square' and 'odd' square = square + odd odd = odd + 2 # Driver Coden = 5;printSquares(n) # This code is contributed# by Rajput-Ji
// C# program to print squares of first 'n'// natural numbers without using *, / and -using System; class GFG{static void printSquares(int n){ // Initialize 'square' // and first odd number int square = 0, odd = 1; // Calculate and // print squares for (int x = 0; x < n; x++) { // Print square Console.Write(square + " " ); // Update 'square' // and 'odd' square = square + odd; odd = odd + 2; }} // Driver Codepublic static void Main (){ int n = 5; printSquares(n);}} // This code is contributed// by inder_verma..
<?php// PHP program to print squares// of first 'n' natural numbers// without using *, / and -function printSquares($n){ // Initialize 'square' and // first odd number $square = 0; $odd = 1; // Calculate and print squares for ($x = 0; $x < $n; $x++) { // Print square echo $square , " "; // Update 'square' and 'odd' $square = $square + $odd; $odd = $odd + 2; }} // Driver Code$n = 5;printSquares($n); // This code is contributed by m_kit?>
<script>// Javascript program to print squares of first 'n' natural numbers// without using *, / and - function printSquares(n){ // Initialize 'square' and first odd number let square = 0, odd = 1; // Calculate and print squares for (let x = 0; x < n; x++) { // Print square document.write(square + " "); // Update 'square' and 'odd' square = square + odd; odd = odd + 2; }} // Driver program to test above functionlet n = 5;printSquares(n); // This code is contributed by subham348.</script>
Output :
0 1 4 9 16
Time Complexity: O(n)
Auxiliary Space: O(1)
This article is contributed by Sachin. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
jit_t
inderDuMCA
Rajput-Ji
Akanksha_Rai
surbhityagi15
subham348
rishavmahato348
sumitgumber28
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Sieve of Eratosthenes
Prime Numbers
Find minimum number of coins that make a given value
Program to find GCD or HCF of two numbers
Minimum number of jumps to reach end
Algorithm to solve Rubik's Cube
The Knight's tour problem | Backtracking-1
Program for Decimal to Binary Conversion | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Dec, 2021"
},
{
"code": null,
"e": 162,
"s": 54,
"text": "Given a natural number ‘n’, print squares of first n natural numbers without using *, / and -. Examples : "
},
{
"code": null,
"e": 232,
"s": 162,
"text"... |
Node.js Callback Concept | 13 Oct, 2021
A callback is a function which is called when a task is completed, thus helps in preventing any kind of blocking and a callback function allows other code to run in the meantime. Callback is called when task get completed and is asynchronous equivalent for a function. Using Callback concept, Node.js can process a large number of requests without waiting for any function to return the result which makes Node.js highly scalable. For example: In Node.js, when a function start reading file, it returns the control to execution environment immediately so that the next instruction can be executed. Once file I/O gets completed, callback function will get called to avoid blocking or wait for File I/O.
Example 1: Code for reading a file synchronously (blocking code) in Node.js. Create a text file inputfile1.txt with the following content:
Hello Programmer!!!
Learn NodeJS with GeeksforGeeks
Create a sync.js file with the following code:
// Write JavaScript codevar fs = require("fs");var filedata = fs.readFileSync('inputfile1.txt');console.log(filedata.toString());console.log("End of Program execution");
Explanation: fs library is loaded to handle file-system related operations. The readFileSync() function is synchronous and blocks execution until finished. The function blocks the program until it reads the file and then only it proceeds to end the programOutput:
Example 2: Code for reading a file asynchronously (non-blocking code) in Node.js. Create a text file inputfile1.txt with the following content.
Hello Programmer!!!
Learn NodeJS with GeeksforGeeks
Create a async.js file with the following code:
// Write a JavaScript codevar fs = require("fs"); fs.readFile('inputfile1.txt', function (ferr, filedata) { if (ferr) return console.error(ferr); console.log(filedata.toString()); }); console.log("End of Program execution");
Explanation: fs library is loaded to handle file-system related operations. The readFile() function is asynchronous and control return immediately to the next instruction in the program while the function keep running in the background. A callback function is passed which gets called when the task running in the background are finished.Output:
Node.js-Basics
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to install the previous version of node.js and npm ?
Node.js fs.writeFile() Method
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
JWT Authentication with Node.js
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": 54,
"s": 26,
"text": "\n13 Oct, 2021"
},
{
"code": null,
"e": 756,
"s": 54,
"text": "A callback is a function which is called when a task is completed, thus helps in preventing any kind of blocking and a callback function allows other code to run in the meant... |
Java Program to Illustrate a Method without Parameters But with Return Type | 17 Jun, 2021
The task is to illustrate a method that does not contain any parameter but should return some value. Methods are used to break a complete program into a number of modules that can be executed one by one. Considering any random shape to illustrate: Circle
Example: First a class named ‘Circle’ is supposed to be created, then with the help of this class, it can calculate the area and circumference of a circle.
Area calculationCircumference calculation
Area calculation
Circumference calculation
Inside the class Circle, we will declare a variable called radius to take the value of the radius from the user so that by using this value of radius we will be able to calculate the area and circumference of a circle. Now, for calculating the area and circumference, we need to create two separate methods called area() and circumference(), which does not take any value as a parameter but will definitely return some value, and the value which this method will return are the final values of area and circumference of the circle. The methods will return the values after calculating it with the help of the values of variables. The most important thing to calculate the area and circumference, and to use these methods are first to need is to call those methods which are known as calling a function, for this we have to create an object of Circle class because in the main method, and we want to access them, methods of another class hence we need to make the object of that class which contains our methods area() and circumference() and by using the object of the class Circle, we will easily call the methods and those methods will return some value, and we will display it by using our predefined function.
Syntax:
class name
{
datatype MethodName()
{
statements....
..
..
return value;
}
}
Implementation:
Example 1: Area calculation
Java
// Java Program to Illustrate a Method// without Parameters but with Return Type // Importing generic java classesimport java.util.*;// Importing Scanner class if// input is from user (optional)*/import java.util.Scanner; // Auxiliary Class (Sample class)// class which contains the method area()class Circle { // initializing the variable radius double radius; // functions calculating area double area() { double r = 7; // Area of circle will be calculate and // will store into the variable ar double ar = 3.14 * r * r; // Method returning the area return ar; }} // Main Classpublic class GFG { // Main driver method public static void main(String args[]) { // Object of circle is created Circle c = new Circle(); // Big type variable to hold area value double area; // Area method is called and // will store the value in variable area area = c.area(); // Printing area of circle System.out.println("Area of circle is : " + area); }}
Area of circle is : 153.86
Example 2: Circumference calculation
Java
// Java Program to Illustrate a Method// without Parameters but with Return Type // Importing java generic classesimport java.util.*; class Circle { double radius; // method which does not contain // parameter but will return // the circumference of circle double circumference() { double r = 7; double circum = 2 * 3.14 * r; // Method returning the circumference of circle return circum; }}public class GFG { public static void main(String args[]) { // the object of circle is created to call the // method circumference() Circle c = new Circle(); double circum; // the value returned from method will store into // the variable circum circum = c.circumference(); System.out.println("Circumference of circle is : " + circum); }}
Circumference of circle is : 43.96
varshagumber28
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 283,
"s": 28,
"text": "The task is to illustrate a method that does not contain any parameter but should return some value. Methods are used to break a complete program into a number of modules that... |
HTTP headers | Authorization | 11 May, 2020
The HTTP headers Authorization header is a request type header that used to contains the credentials information to authenticate a user through a server. If the server responds with 401 Unauthorized and the WWW-Authenticate header not usually.
Syntax:
Authorization: <type> <credentials>
Directives: This header accept two directive as mentioned above and described below:
<type>: This directive holds the authentication type the default type is Basic and the other types are IANA registry of Authentication schemes and Authentication for AWS servers (AWS4-HMAC-SHA256).
<credentials>: This directive is totally depends on the type of authentication if the authentication is Basic then the credentials are struct with Username and Password combine with a colon like “Username:Password” and the resulted string is base64 encoded.
Example:
Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l
Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l
Supported browsers: The browsers compatible with HTTP headers Authorization are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 May, 2020"
},
{
"code": null,
"e": 272,
"s": 28,
"text": "The HTTP headers Authorization header is a request type header that used to contains the credentials information to authenticate a user through a server. If the server respond... |
multimap find() in C++ STL | 01 Jul, 2021
multimap::find() is a built-in function in C++ STL which returns an iterator or a constant iterator that refers to the position where the key is present in the multimap. In case of multiple same keys being present, the iterator that refers to one of the keys (typically the first one). In case we wish to get all the items with a given key, we may use equal_range(). If the key is not present in the multimap container, it returns an iterator or a constant iterator which refers to multimap.end(). Syntax:
iterator multimap_name.find(key)
or
constant iterator multimap_name.find(key)
Parameters: The function accepts one mandatory parameter key which specifies the key to be searched in the multimap container. Return Value: The function returns an iterator or a constant iterator which refers to the position where the key is present in the multimap. If the key is not present in the multimap container, it returns an iterator or a constant iterator which refers to multimap.end().
CPP
// C++ program for illustration// of multimap::find() function#include <bits/stdc++.h>using namespace std; int main(){ // initialize container multimap<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 2, 60 }); mp.insert({ 3, 20 }); mp.insert({ 1, 50 }); mp.insert({ 4, 50 }); cout << "The elements from position 3 in multimap are : \n"; cout << "KEY\tELEMENT\n"; // find() function finds the position at which 3 is for (auto itr = mp.find(3); itr != mp.end(); itr++) cout << itr->first << '\t' << itr->second << '\n'; return 0;}
The elements from position 3 in multimap are :
KEY ELEMENT
3 20
4 50
himanshu raj
lucaopensource
CPP-Functions
cpp-multimap
cpp-multimap-functions
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
vector erase() and clear() in C++
Substring in C++
Priority Queue in C++ Standard Template Library (STL)
Inheritance in C++
Object Oriented Programming in C++
The C++ Standard Template Library (STL)
C++ Classes and Objects
Sorting a vector in C++
2D Vector In C++ With User Defined Size | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n01 Jul, 2021"
},
{
"code": null,
"e": 561,
"s": 53,
"text": "multimap::find() is a built-in function in C++ STL which returns an iterator or a constant iterator that refers to the position where the key is present in the multimap. In c... |
Python PIL | Image.seek() Method | 02 Aug, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.
Image.seek() Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an EOFError exception. When a sequence file is opened, the library automatically seeks to frame 0.
Note that in the current version of the library, most sequence formats only allows you to seek to the next frame.
Syntax: Image.seek(frame)
Parameters:frame – Frame number, starting at 0.
Raises: EOFError – If the call attempts to seek beyond the end of the sequence.
Image Used:
# importing image class from PIL packagefrom PIL import Image # creating gif image objectimg = Image.open(r"C:\Users\System-Pc\Desktop\time.gif")img1 = img.tell()print(img1) # using seek() methodimg2 = img.seek(img.tell() + 1)img3 = img.tell()print(img3)img.show()
Output:
0
1
Python-pil
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
Create a directory in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Aug, 2019"
},
{
"code": null,
"e": 355,
"s": 28,
"text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to ... |
Formatting Unordered and Ordered Lists in CSS | The style and position of unordered and ordered lists can be formatted by CSS properties with list-style-type, list-style-image and list-style-position.
The syntax of CSS list-style property is as follows −
Selector {
list-style: /*value*/
}
The following examples illustrate CSS list-style property −
The following example styles ordered list −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
ol {
list-style: upper-roman;
line-height: 150%;
}
</style>
</head>
<body>
<h2>Latest C# Versions</h2>
<ol>
<li>C# 8.0</li>
<li>C# 7.3</li>
<li>C# 7.2</li>
<li>C# 7.1</li>
<li>C# 7.0</li>
</ol>
</body>
</html>
This gives the following output −
The following example styles unordered list −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
ul > ul{
list-style: circle inside;
}
li:last-child {
list-style-type: square;
}
</style>
</head>
<body>
<h2>Programming Languages</h2>
<ul>
<li>C++ programming language created by Bjarne Stroustrup as an extension of the C programming language.</li>
<li>Java programming language developed by James Gosling.</li>
<ul>
<li>Core Java</li>
<li>Advanced Java</li>
</ul>
<li>Scala is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way.</li>
</ul>
</body>
</html>
This gives the following output − | [
{
"code": null,
"e": 1215,
"s": 1062,
"text": "The style and position of unordered and ordered lists can be formatted by CSS properties with list-style-type, list-style-image and list-style-position."
},
{
"code": null,
"e": 1269,
"s": 1215,
"text": "The syntax of CSS list-style ... |
Installing ESP32 Board in Arduino IDE | One very big advantage with ESP32, which has aided its quick adoption and massive popularity, is the provision for programming the ESP32 within the Arduino IDE.
Now, I should point out here that Arduino is not the only IDE that helps you compile code for ESP32 and flash it into the microcontroller. There is ESP−IDF which is the official development framework for ESP32, which provides much more flexibility in terms of configuration options. However, it is hardly as intuitive and user−friendly as the Arduino IDE, and if you are starting out with ESP32, Arduino IDE is ideal to get your hands dirty. Also, with the number of supporting libraries built for ESP32 in Arduino, courtesy of the huge developer community, there's hardly any functionality of ESP32 which can't
be realized with the Arduino IDE. ESP-IDF is more suitable for the more advanced and experienced programmers, who need to stretch ESP32 to its limits. If you are one of those, you are looking
for the ESP−IDF Getting Started Guide. Others can follow along.
Now, to install the ESP32 board in the Arduino IDE, you need to follow the below steps −
Make sure you have Arduino IDE (preferably the latest version) installed on your machine
Make sure you have Arduino IDE (preferably the latest version) installed on your machine
Open Arduino and go to File −> Preferences
Open Arduino and go to File −> Preferences
In the Additional Boards Manager URL, enter
In the Additional Boards Manager URL, enter
https://dl.espressif.com/dl/package_esp32_index.json
In case you have an existing JSON file's URL in the preferences (this is likely if you've installed ESP8266, stm32duino, or any such additional board in the IDE),
you can just append the above path to the existing path, using a comma. An example is shown below, for ESP8266 and ESP32 boards −
http://arduino.esp8266.com/stable/package_esp8266com_index.json, https://dl.espressif.com/dl/package_esp32_index.json
Go to Tools −> Board−> Boards Manager. A pop−up would open up. Search for ESP32 and install the esp32 by Espressif Systems board. The image below shows the board already installed because I had installed the board before preparing this tutorial.
Go to Tools −> Board−> Boards Manager. A pop−up would open up. Search for ESP32 and install the esp32 by Espressif Systems board. The image below shows the board already installed because I had installed the board before preparing this tutorial.
Once your ESP32 board has been installed, you can verify the installation by going to Tools −> Boards. You can see a whole bunch of boards under the ESP32 Arduino section.
Choose the board of your choice. If you are not sure which board best represents the one you have, you can choose ESP32 Dev Module.
Next, connect your board to your machine using the USB Cable. You should see an additional COM Port under Tools−> Port. Select that additional port. In case you see multiple ports, you can disconnect the USB and see which port disappeared. That port corresponds to ESP32.
Once the port is identified, pick any one example sketch from File −> Examples. We will choose the StartCounter example from File −> Examples −> Preferences −> StartCounter.
Open that sketch, compile it and flash it into the ESP32 by clicking on the Upload button (the right arrow button, besides the Compile button).
Then open the Serial Monitor using Tools −> Serial Monitor, or simply by pressing Ctrl + Shift + M on your keyboard. You should see the counter value getting incremented after every ESP32 restart.
Congratulations!! You've set up the environment for working with ESP32.
54 Lectures
4.5 hours
Frahaan Hussain
20 Lectures
5 hours
Azaz Patel
20 Lectures
4 hours
Azaz Patel
0 Lectures
0 mins
Eduonix Learning Solutions
169 Lectures
12.5 hours
Kalob Taulien
29 Lectures
2 hours
Zenva
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2344,
"s": 2183,
"text": "One very big advantage with ESP32, which has aided its quick adoption and massive popularity, is the provision for programming the ESP32 within the Arduino IDE."
},
{
"code": null,
"e": 3214,
"s": 2344,
"text": "Now, I should point o... |
How do you run your own code alongside Tkinter's event loop? | Tkinter is widely used to create and develop GUI based applications and games.
Tkinter provides its window or frame where we execute our programs and functions
along with other attributes.
Let us consider that we are working with a particular application and we want to
write the changes in the code while running the application. Tkinter provides a
callback method which can be used to run the window while iterating over it. We
can keep running the window using the after(duration,task) method that will basically run the changes after a duration.
In this example, we will create a window which prints the numbers in the range (0
to 9) whilst running the main window or frame.
#Import the required libraries
from tkinter import *
from tkinter import messagebox
#Create an instance of tkinter frame or window
win= Tk()
#Set the geometry
win.geometry("700x200")
#Define the function for button
def some_task():
for i in range(10):
print(i)
#Recursively call the function
win.after(2000, some_task)
#Keep Running the window
win.after(2000, some_task)
win.mainloop()
Running the above code will keep printing the numbers in the range (0 to 9) on the
console, and along with that, it will display the main window.
0
1
2
3
4
5
6
7
8
9
....... | [
{
"code": null,
"e": 1251,
"s": 1062,
"text": "Tkinter is widely used to create and develop GUI based applications and games.\nTkinter provides its window or frame where we execute our programs and functions\nalong with other attributes."
},
{
"code": null,
"e": 1612,
"s": 1251,
... |
Bootstrap - Progress Bars | This chapter discusses about Bootstrap progress bars. The purpose of progress bars is to show that assets are loading, in progress, or that there is action taking place regarding elements on the page.
To create a basic progress bar −
Add a <div> with a class of .progress.
Add a <div> with a class of .progress.
Next, inside the above <div>, add an empty <div> with a class of .progress-bar.
Next, inside the above <div>, add an empty <div> with a class of .progress-bar.
Add a style attribute with the width expressed as a percentage. Say for example, style = "60%"; indicates that the progress bar was at 60%.
Add a style attribute with the width expressed as a percentage. Say for example, style = "60%"; indicates that the progress bar was at 60%.
Let us see an example below −
<div class = "progress">
<div class = "progress-bar" role = "progressbar" aria-valuenow = "60"
aria-valuemin = "0" aria-valuemax = "100" style = "width: 40%;">
<span class = "sr-only">40% Complete</span>
</div>
</div>
To create a progress bar with different styles −
Add a <div> with a class of .progress.
Add a <div> with a class of .progress.
Next, inside the above <div>, add an empty <div> with a class of .progress-bar and class progress-bar-* where * could be success, info, warning, danger.
Next, inside the above <div>, add an empty <div> with a class of .progress-bar and class progress-bar-* where * could be success, info, warning, danger.
Add a style attribute with the width expressed as a percentage. Say for example, style = "60%"; indicates that the progress bar was at 60%.
Add a style attribute with the width expressed as a percentage. Say for example, style = "60%"; indicates that the progress bar was at 60%.
Let us see an example below −
<div class = "progress">
<div class = "progress-bar progress-bar-success" role = "progressbar"
aria-valuenow = "60" aria-valuemin = "0" aria-valuemax = "100" style = "width: 90%;">
<span class = "sr-only">90% Complete (Sucess)</span>
</div>
</div>
<div class = "progress">
<div class = "progress-bar progress-bar-info" role = "progressbar"
aria-valuenow = "60" aria-valuemin = "0" aria-valuemax = "100" style = "width: 30%;">
<span class = "sr-only">30% Complete (info)</span>
</div>
</div>
<div class = "progress">
<div class = "progress-bar progress-bar-warning" role = "progressbar"
aria-valuenow = "60" aria-valuemin = "0" aria-valuemax = "100" style = "width: 20%;">
<span class = "sr-only">20%Complete (warning)</span>
</div>
</div>
<div class = "progress">
<div class = "progress-bar progress-bar-danger" role = "progressbar"
aria-valuenow = "60" aria-valuemin = "0" aria-valuemax = "100" style = "width: 10%;">
<span class = "sr-only">10% Complete (danger)</span>
</div>
</div>
To create a striped progress bar −
Add a <div> with a class of .progress and .progress-striped.
Add a <div> with a class of .progress and .progress-striped.
Next, inside the above <div>, add an empty <div> with a class of .progress-bar and class progress-bar-* where * could be success, info, warning, danger.
Next, inside the above <div>, add an empty <div> with a class of .progress-bar and class progress-bar-* where * could be success, info, warning, danger.
Add a style attribute with the width expressed as a percentage. Say for example, style = "60%"; indicates that the progress bar was at 60%.
Add a style attribute with the width expressed as a percentage. Say for example, style = "60%"; indicates that the progress bar was at 60%.
Let us see an example below −
<div class = "progress progress-striped">
<div class = "progress-bar progress-bar-success" role = "progressbar"
aria-valuenow = "60" aria-valuemin = "0" aria-valuemax = "100" style = "width: 90%;">
<span class = "sr-only">90% Complete (Sucess)</span>
</div>
</div>
<div class = "progress progress-striped">
<div class = "progress-bar progress-bar-info" role = "progressbar"
aria-valuenow = "60" aria-valuemin = "0" aria-valuemax = "100" style = "width: 30%;">
<span class = "sr-only">30% Complete (info)</span>
</div>
</div>
<div class = "progress progress-striped">
<div class = "progress-bar progress-bar-warning" role = "progressbar"
aria-valuenow = "60" aria-valuemin = "0" aria-valuemax = "100" style="width: 20%;">
<span class = "sr-only">20%Complete (warning)</span>
</div>
</div>
<div class = "progress progress-striped">
<div class = "progress-bar progress-bar-danger" role = "progressbar"
aria-valuenow = "60" aria-valuemin = "0" aria-valuemax = "100" style = "width: 10%;">
<span class = "sr-only">10% Complete (danger)</span>
</div>
</div>
To create an animated progress bar −
Add a <div> with a class of .progress and .progress-striped. Also add class .active to .progress-striped.
Add a <div> with a class of .progress and .progress-striped. Also add class .active to .progress-striped.
Next, inside the above <div>, add an empty <div> with a class of .progress-bar.
Next, inside the above <div>, add an empty <div> with a class of .progress-bar.
Add a style attribute with the width expressed as a percentage. Say for example, style = "60%"; indicates that the progress bar was at 60%.
Add a style attribute with the width expressed as a percentage. Say for example, style = "60%"; indicates that the progress bar was at 60%.
This will animate the stripes right to left.
Let us see an example below −
<div class = "progress progress-striped active">
<div class = "progress-bar progress-bar-success" role = "progressbar"
aria-valuenow = "60" aria-valuemin = "0" aria-valuemax = "100" style = "width: 40%;">
<span class = "sr-only">40% Complete</span>
</div>
</div>
You can even stack multiple progress bars. Place the multiple progress bars into the same .progress to stack them as seen in the following example −
<div class = "progress">
<div class = "progress-bar progress-bar-success" role = "progressbar"
aria-valuenow = "60" aria-valuemin = "0" aria-valuemax = "100" style = "width: 40%;">
<span class = "sr-only">40% Complete</span>
</div>
<div class = "progress-bar progress-bar-info" role = "progressbar"
aria-valuenow = "60" aria-valuemin = "0" aria-valuemax = "100" style = "width: 30%;">
<span class = "sr-only">30% Complete (info)</span>
</div>
<div class = "progress-bar progress-bar-warning" role = "progressbar"
aria-valuenow = "60" aria-valuemin = "0" aria-valuemax = "100" style = "width: 20%;">
<span class = "sr-only">20%Complete (warning)</span>
</div>
</div>
26 Lectures
2 hours
Anadi Sharma
54 Lectures
4.5 hours
Frahaan Hussain
161 Lectures
14.5 hours
Eduonix Learning Solutions
20 Lectures
4 hours
Azaz Patel
15 Lectures
1.5 hours
Muhammad Ismail
62 Lectures
8 hours
Yossef Ayman Zedan
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3532,
"s": 3331,
"text": "This chapter discusses about Bootstrap progress bars. The purpose of progress bars is to show that assets are loading, in progress, or that there is action taking place regarding elements on the page."
},
{
"code": null,
"e": 3565,
"s": ... |
string.format() function in Lua programming | There are cases when we want to format strings which will help us to print the output in a particular format.
When we use the string.format() function it returns a formatted version of its variable number of arguments following the description given by its first argument, the so-called format string.
The format string that we get the output, is similar to those of the printf function of standard C: It is composed of regular text and directives, which control where and how each argument must be placed in the formatted string.
string.format(“s = %a”)
The string.format() syntax above contains an identifier s which is the string and the identifier a is the letter that tells how to format the argument.
There are many letters to tell how to format the argument, these are −
‘d’ - a decimal number
‘x’ - for hexadecimal
‘o’ - for octal
‘f’ - for a floating-point number
‘s’ - strings
and there are many other variants.
Now let’s consider some examples where we will run the string.format() function.
Consider the following example −
Live Demo
s = string.format("x = %.4f",2345)
print(s)
x = 2345.0000
Now let’s consider one more example where we will print the string in a format that looks exactly similar to a date. Consider an example shown below −
Live Demo
d = 5; m = 11; y = 2021
date = string.format("%02d/%02d/%04d",d,m,y)
print(date)
05/11/2021 | [
{
"code": null,
"e": 1172,
"s": 1062,
"text": "There are cases when we want to format strings which will help us to print the output in a particular format."
},
{
"code": null,
"e": 1364,
"s": 1172,
"text": "When we use the string.format() function it returns a formatted version ... |
How to deploy Machine Learning Model in Laravel Application | by Davis David | Towards Data Science | The topic of Machine Learning Model Deployment is not new nowadays, but many AI practitioners especially beginners find it difficult to deploy their models into production. In this article, we are going to learn how to call our model API from the Algorithmia platform to the Laravel application and make predictions.
Before moving on I recommend you read my previous article where I explained in detail all about the Algorithmia platform and how you can deploy your model and call it for prediction in the programming language of your choice(Python, PHP, javascript, java, c#, NodeJS, Go, Ruby e.t.c).
In the previous article, you will learn
How to create an NLP model that detects spam SMS text messages.
How to use Algorithmia, a MLOps platform.
How to deploy your model into the Algorithmia platform.
How to use your deployed NLP model in any Python application(Flask or Django).
Why Algorithmia?Algorithmia helps to separate Machine Learning concerns from the rest of your application (example, e-commerce site or android app). By calling your model and making predictions as an API call, your application can be free of the concerns of a machine learning environment. All you need to do is create correctly formatted input.
Laravel is one of the most popular open-source PHP web frameworks for the development of web applications, created by Taylor Otwell. It follows the model-view-controller architectural pattern and based on Symfony.
If you are not familiar with Laravel, I recommend you take this latest Laravel Crash course 2020 from Travesy Media Youtube Channel.
In this article, we will create a simple Laravel app with two web pages. The first page will have a simple HTML form to write a text message and the second page will show the model prediction result if the text message provided is a spam message or a normal message.
To install the laravel framework, your machine must meet the following few requirements.
PHP >= 7.2.5
BCMath PHP Extension
Ctype PHP Extension
Fileinfo PHP extension
JSON PHP Extension
Mbstring PHP Extension
OpenSSL PHP Extension
PDO PHP Extension
Tokenizer PHP Extension
XML PHP Extension
Laravel uses Composer to manage its dependencies. Make sure you have Composer installed on your machine before using Laravel.
Then you can install laravel 7 by typing the following command.
composer create-project --prefer-dist laravel/laravel:^7.0 laravel-sms-spam-detection
The command mentioned above will make Laravel installed on the specific directory called laravel-sms-spam-detection.
The next thing after installing Laravel is to set your application key to a random string by running the following command.
php artisan key:generate
The next step is to install the algorithmia PHP client. To install run the following command in the laravel-sms-spam-detection directory.
composer require algorithmia/algorithmia
Then run this command to regenerate the list of all classes that need to be included in this project. This will also include new classes from the algorithimia package we have installed.
composer dumpautoload
Now we have successfully install algorithmia for PHP in our Laravel project. 👍
The following command will create a simple controller called SpamController.
php artisan make:controller SpamController
YOu can then access this new controller in the “app/Http/Controller” directory. The controller will have two methods.
The first method will be responsible to show the blade file with a simple HTML form to write a text message(we will create this blade file in the next steps). The name of the method is show_form()
The above method will show a view from the sms_spam_form blade file.
The second method will receive the text message and make a prediction by using Algorithimia PHP Client if the text message provided is a normal message or spam message. The name of the method is detect().
NB: Click the “API Key” tab on your algorithm panel to collect the API key that will help you call the code that runs the model.
To call the algorithm, we need to add the name of the algorithm with its version to the client object we have created. The name of the algorithm is “Davis/spam_detection/0.2.0”.The above method will then make a prediction and show the results in the sms_spam_result blade file.
Here is the complete source code in the SpamController PHP file.
Add the following route code in the “routes/web.php” file for the Laravel application.
The first route will show a simple HTML form with sample normal and spam messages and the second route will show a result page with model prediction results.
We then create two blade files, the first blade file is sms_spam_form.blade.php in the “resources/views/” folder directory. It will have a simple form with a text-area form attribute to write a text message and a submission button. It will also have some examples of a normal message and spam message you can try to use.
The second blade file is sms_spam_result.blade.php in the “resources/views/” folder directory. It will show the text message provided in the HTML form, the prediction results, and a button to try again.
We can start the server by using the below command from the project directory.
php artisan serve
Now we can open our laravel application with the following Url in the browser.
http://127.0.0.1:8000/
Then you can see our first page with HTML form.
To make a prediction write a text message in the textarea and click the predict button.Example of the normal text message: “Haven't mus ask if u can 1st wat. Of meet 4 lunch den u n him meet can already lor. Or u wan 2 go ask da ge 1st then confirm w me asap?”
After clicking the predict button the Laravel app will show the result page with the prediction result.
Our model predicts the text message provided is a normal message.
Let’s try another text message.
Text Message: “This weeks SavaMob member offers are now accessible. Just call 08709501522 for details! SavaMob, POBOX 139, LA3 2WU. Only £1.50/week. SavaMob — offers mobile!”
Then click the predict button.
Our model predicts the text message provided is a spam message.
In this article, you have learned how to deploy your model from Algorithmia to a Laravel application by using Algorithmia PHP Client. You can also deploy in different applications from different programming languages, you just need to install the specific algorithmia package for the language of your choice and call the API for prediction.
You can download the source code for this laravel application here: https://github.com/Davisy/Laravel-SMS-Spam-Detection
Congratulations, you have made it to the end of this article!
If you learned something new or enjoyed reading this article, please share it so that others can see it. Until then, see you in the next post! I can also be reached on Twitter @Davis_McDavid
One last thing: Read more articles like this in the following links. | [
{
"code": null,
"e": 489,
"s": 172,
"text": "The topic of Machine Learning Model Deployment is not new nowadays, but many AI practitioners especially beginners find it difficult to deploy their models into production. In this article, we are going to learn how to call our model API from the Algorith... |
Inserting data in a table in SAP HANA | To insert the data, you need to run the Insert statement in SQL editor. “Demo_HANA” is table name.
Insert into Demo_HANA Values (1,'John');
Insert into Demo_HANA Values (2,'Anna');
Insert into Demo_HANA Values (3,'Jason');
Insert into Demo_HANA Values (4,'Nick');
In SQL editor, add INSERT statements and execute (F8) as below − | [
{
"code": null,
"e": 1161,
"s": 1062,
"text": "To insert the data, you need to run the Insert statement in SQL editor. “Demo_HANA” is table name."
},
{
"code": null,
"e": 1326,
"s": 1161,
"text": "Insert into Demo_HANA Values (1,'John');\nInsert into Demo_HANA Values (2,'Anna');\... |
How to update listview after insert values in Android sqlite using Kotlin? | This example demonstrates how to update listview after insert values in Android sqlite using Kotlin.
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"
tools:context=".MainActivity">
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Name" />
<EditText
android:id="@+id/salary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Salary"
android:inputType="numberDecimal" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="@+id/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save" />
<Button
android:id="@+id/refresh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Refresh" />
</LinearLayout>
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private lateinit var save: Button
private lateinit var refresh: Button
private lateinit var name: EditText
private lateinit var salary: EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
val helper = DatabaseHelper(this)
val arrayList: ArrayList<String> = helper.getAllContacts() as ArrayList<String>
name = findViewById(R.id.name)
salary = findViewById(R.id.salary)
save = findViewById(R.id.save)
refresh = findViewById(R.id.refresh)
val listView: ListView = findViewById(R.id.listView)
val arrayAdapter: ArrayAdapter<*> = ArrayAdapter<Any?>(this@MainActivity,
android.R.layout.simple_list_item_1, arrayList as List<Any?>)
listView.adapter = arrayAdapter
save.setOnClickListener {
arrayList.clear()
arrayList.addAll(helper.getAllContacts())
arrayAdapter.notifyDataSetChanged()
listView.invalidateViews()
listView.refreshDrawableState()
}
refresh.setOnClickListener {
if (name.text.toString().isNotEmpty() && salary.text.toString().isNotEmpty()) {
if (helper.addData(name.text.toString(), salary.text.toString())) {
Toast.makeText(this, "Inserted", Toast.LENGTH_LONG).show()
} else {
Toast.makeText(this, "NOT Inserted", Toast.LENGTH_LONG).show()
}
} else {
name.error = "Enter NAME"
salary.error = "Enter Salary"
}
}
}
}
Step 4 − Create a new class DataBaseHelper.kt and add the following code
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteException
import android.database.sqlite.SQLiteOpenHelper
import java.io.IOException
class DatabaseHelper(context: Context) :
SQLiteOpenHelper(context, dataBaseName, null, dataBaseVersion) {
private val contactsTableName = "SalaryDetails"
companion object {
const val dataBaseName = "salaryDatabase3"
const val dataBaseVersion = 1
}
override fun onCreate(db: SQLiteDatabase?) {
try {
db?.execSQL("create table $contactsTableName(id INTEGER PRIMARY KEY, name text,salary text )")
} catch (e: SQLiteException) {
try {
throw IOException(e)
} catch (e1: IOException) {
e1.printStackTrace()
}
}
}
override fun onUpgrade(db: SQLiteDatabase?, p1: Int, p2: Int) {
db?.execSQL("DROP TABLE IF EXISTS $contactsTableName")
onCreate(db)
}
fun addData(s: String?, s1: String?): Boolean {
val db = this.writableDatabase
val contentValues = ContentValues()
contentValues.put("name", s)
contentValues.put("salary", s1)
db.insert(contactsTableName, null, contentValues)
return true
}
fun getAllContacts(): Collection<String> {
val db: SQLiteDatabase = this.readableDatabase
val arrayList = ArrayList<String>()
val res: Cursor = db.rawQuery("select * from $contactsTableName", null)
res.moveToFirst()
while (!res.isAfterLast) {
arrayList.add(res.getString(res.getColumnIndex("name")));
res.moveToNext();
}
return arrayList
}
}
Step 5 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11">
<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 the 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": 1163,
"s": 1062,
"text": "This example demonstrates how to update listview after insert values in Android sqlite using Kotlin."
},
{
"code": null,
"e": 1291,
"s": 1163,
"text": "Step 1 − Create a new project in Android Studio, go to File? New Project and fill... |
Path compareTo() method in Java with Examples | 25 May, 2021
The Java Path interface was added to Java NIO in Java 7. The Path interface is located in the java.nio.file package, so the fully qualified name of the Java Path interface is java.nio.file.Path. A Java Path instance represents a path in the file system. A path can use to locate either a file or a directory.path of an entity could be of two types one is an absolute path and the other is a relative path. The absolute path is the location address from the root to the entity while the relative path is the location address that is relative to some other path.compareTo(java.nio.file.Path) method of java.nio.file.Path used to compare two abstract paths lexicographically. Two paths can be compared by this method. The ordering of paths defined by this method is provider-specific, and in the case of the default provider, platform specific. This method returns zero if the argument is equal to this path, a value less than zero if this path is lexicographically less than the argument, or a value greater than zero if this path is lexicographically greater than the argument. This method does not access the file system. There is no need for a file is required to exist. This method may not be used to compare paths that are associated with different file system providers.Syntax:
int compareTo(Path other)
Parameters: This method accepts a single parameter another path which is the path compared to this current path.Return value: This method returns zero if the argument is equal to this path, a value less than zero if this path is lexicographically less than the argument, or a value greater than zero if this path is lexicographically greater than the argument.Exception: This method throw and Exception ClassCastException if the paths are associated with different providers.Below programs illustrate compareTo(java.nio.file.Path) method: Program 1:
Java
// Java program to demonstrate// Path.compareTo(Path) method import java.io.IOException;import java.nio.file.Path;import java.nio.file.Paths; public class GFG { public static void main(String[] args) throws IOException { // create object of Paths Path path1 = Paths.get("D:","eclipse","configuration","org.eclipse.update"); Path path2 = Paths.get("D:","eclipse","configuration","org.eclipse.update"); // compare paths int value = path1.compareTo(path2); // print result if (value == 0) System.out.println("Both are equal"); else if (value < 0) System.out.println("Path 2 is greater " + "than path 1"); else System.out.println("Path 1 is greater " + "than path 2"); }}
Both are equal
Program 2:
Java
// Java program to demonstrate// Path.compareTo(Path) method import java.io.IOException;import java.nio.file.Path;import java.nio.file.Paths; public class GFG { public static void main(String[] args) throws IOException { // create object of Paths Path path1 = Paths.get("D:","eclipse","configuration","org.eclipse.update"); Path path2 = Paths.get("D:\\temp\\Spring"); // compare paths int value = path1.compareTo(path2); // print result if (value == 0) System.out.println("Both are equal"); else if (value < 0) System.out.println("Path 2 is greater " + "than path 1"); else System.out.println("Path 1 is greater " + "than path 2"); }}
Path 2 is greater than path 1
References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#compareTo(java.nio.file.Path)
Kaustubh Deokar
Java-Functions
Java-Path
java.nio.file package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Functional Interfaces in Java
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 May, 2021"
},
{
"code": null,
"e": 1312,
"s": 28,
"text": "The Java Path interface was added to Java NIO in Java 7. The Path interface is located in the java.nio.file package, so the fully qualified name of the Java Path interface is... |
Good example of functional testing a Python Tkinter application | Let us suppose that we have a GUI-based Python tkinter application that takes the
text input from the user and validates by saving it in a new text file. The file contains
the same text input that the user has typed. We can check and validate the user input from the file.
In Functional Testing, we are primarily concerned about backend API, database,
user-server communication, Input and output, etc.
To check the application using the functional testing strategy, we have to first
understand the user requirement and the input/output. After testing the pre-phase,
we test our application for different test cases.
For example, we have a GUI-based tkinter application that takes the user input
and saves it in the form of a text file in the system.
from tkinter import *
win = Tk()
win.geometry("700x600")
# Create title label
title_label = Label(win, text="Enter the File Name")
title_label.pack(anchor='n')
# Create title entry
title_entry = Entry(win, width=35)
title_entry.pack(anchor='nw')
# Create save button and function
def save():
# Get contents of title entry and text entry
# Create a file to write these contents in to it
file_title = title_entry.get()
file_contents = text_entry.get(0.0, END)
with open(file_title + ".txt", "w") as file:
file.write(file_contents)
print("File successfully created")
file.close()
pass
#Create a save button to save the content of the file
save_button = Button(win, text="Save The File", command=save)
save_button.pack()
# Create text entry
text_entry = Text(win, width=40, height=30, border=4, relief=RAISED)
text_entry.pack()
win.mainloop()
Running the above code will create a window like this,
Once we will click the Save the File button, it will save the filename as “Tutorials.txt”.
Now, go to the file location and open the text file externally. It will have the same
text as the user input. | [
{
"code": null,
"e": 1460,
"s": 1187,
"text": "Let us suppose that we have a GUI-based Python tkinter application that takes the\ntext input from the user and validates by saving it in a new text file. The file contains\nthe same text input that the user has typed. We can check and validate the user... |
What is the use of router in Express.js ? | 04 Jun, 2021
Express.js is a powerful framework for node.js. One of the main advantages of this framework is defining different routes or middleware to handle the client’s different incoming requests. In this article, we will discuss, how to use the router in the express.js server.
The express.Router() function is used to create a new router object. This function is used when you want to create a new router object in your program to handle requests. Multiple requests can be easily differentiated with the help of the Router() function in Express.js.This is the advantage of the use of the Router.
Syntax:
express.Router( [options] )
Parameters: This function accepts one optional parameter whose properties are shown below.
Case-sensitive: This enables case sensitivity.
mergeParams: It preserves the request params values from the parent router.
strict: This enables strict routing.
Return Value: This function returns the New Router Object.
Installing Module: Install the module using the following command.
npm install express
Project structure: It will look like this.
Note: The routes folder contains Home.js and login.js file.
Implementation:
Home.js
// Importing express moduleconst express = require("express") // Creating express routerconst router = express.Router() // Handling request using routerrouter.get("/home", (req,res,next) => { res.send("This is the homepage request")}) // Exporting routermodule.exports = router
login.js
// Importing the moduleconst express = require("express") // Creating express Routerconst router = express.Router() // Handling login requestrouter.get("/login", (req,res,next) => { res.send("This is the login request")}) module.exports = router
index.js
// Requiring moduleconst express = require("express") // Importing all the routesconst homeroute = require("./routes/Home.js")const loginroute = require("./routes/login") // Creating express serverconst app = express() // Handling routes requestapp.use("/", homeroute)app.use("/", loginroute) // Server setupapp.listen((3000), () => { console.log("Server is Running")})
Run index.js using the below command:
node index.js
Output: We will see the following output on the terminal screen.
Server is Running
Now go to http://localhost:3000/login and http://localhost:3000/home, we will see the following output on the browser screen.
Express.js
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Jun, 2021"
},
{
"code": null,
"e": 298,
"s": 28,
"text": "Express.js is a powerful framework for node.js. One of the main advantages of this framework is defining different routes or middleware to handle the client’s different incomi... |
userdel command in Linux with Examples | 27 May, 2019
userdel command in Linux system is used to delete a user account and related files. This command basically modifies the system account files, deleting all the entries which refer to the username LOGIN. It is a low-level utility for removing the users.
Syntax:
userdel [options] LOGIN
Options:
userdel -f: This option forces the removal of the specified user account. It doesn’t matter that the user is still logged in. It also forces the userdel to remove the user’s home directory and mail spool, even if another user is using the same home directory or even if the mail spool is not owned by the specified user.Example:sudo userdel -f neuser
Example:
sudo userdel -f neuser
userdel -r: Whenever we are deleting a user using this option then the files in the user’s home directory will be removed along with the home directory itself and the user’s mail spool. All the files located in other file systems will have to be searched for and deleted manually.Example:sudo userdel -r newuser2
Example:
sudo userdel -r newuser2
userdel -h : This option display help message and exit.Example:userdel -h
Example:
userdel -h
userdel -R: This option apply changes in the CHROOT_DIR directory and use the configuration files from the CHROOT_DIR directory.Example:sudo userdel -R newuser2
Example:
sudo userdel -R newuser2
userdel -Z : This option remove any SELinux(Security-Enhanced Linux) user mapping for the user’s login.Example:sudo userdel -Z newuser2
Example:
sudo userdel -Z newuser2
userdel command with help option: The userdel command throws an error if no options, filename or arguments are passed. So, when we use the -h option, it gives the general syntax along with the various options that can be used with the userdel command.Example:
Example:
linux-command
Linux-system-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
'crontab' in Linux with Examples
Tail command in Linux with examples
Conditional Statements | Shell Script
Docker - COPY Instruction
scp command in Linux with Examples
UDP Server-Client implementation in C
echo command in Linux with Examples
Cat command in Linux with examples
touch command in Linux with Examples | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n27 May, 2019"
},
{
"code": null,
"e": 306,
"s": 54,
"text": "userdel command in Linux system is used to delete a user account and related files. This command basically modifies the system account files, deleting all the entries which r... |
Python | Calendar Module | 02 Jul, 2021
Python defines an inbuilt module calendar that handles operations related to the calendar. The calendar module allows output calendars like the program and provides additional useful functions related to the calendar. Functions and classes defined in the Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. By default, these calendars have Monday as the first day of the week, and Sunday as the last (the European convention).Example #1: Display the Calendar of a given month.
Python3
# Python program to display calendar of# given month of the year # import moduleimport calendar yy = 2017mm = 11 # display the calendarprint(calendar.month(yy, mm))
Output:
Example #2: Display calendar of the given year.
Python3
# Python code to demonstrate the working of# calendar() function to print calendar # importing calendar module# for calendar operationsimport calendar # using calendar to print calendar of year# prints calendar of 2018print ("The calendar of year 2018 is : ")print (calendar.calendar(2018, 2, 1, 6))
Output:
class calendar.Calendar : The calendar class creates a Calendar object. A Calendar object provides several methods that can be used for preparing the calendar data for formatting. This class doesn’t do any formatting itself. This is the job of subclasses. Calendar class allows the calculations for various tasks based on date, month, and year. Calendar class provides the following methods:
class calendar.TextCalendar : TextCalendar class can be used to generate plain text calendars. TextCalendar class in Python allows you to edit the calendar and use it as per your requirement.
class calendar.HTMLCalendar : HTMLCalendar class can be used to generate HTML calendars. HTMLCalendar class in Python allows you to edit the calendar and use as per your requirement.
Simple TextCalendar class :For simple text calendars calendar module provides the following functions :
clintra
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Jul, 2021"
},
{
"code": null,
"e": 594,
"s": 52,
"text": "Python defines an inbuilt module calendar that handles operations related to the calendar. The calendar module allows output calendars like the program and provides additiona... |
MoviePy – Getting Sub Clip | 01 Aug, 2020
In this article we will see how we can show a video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. A subclip is a section of a master (source) clip that you want to edit and manage separately in your project. You can use subclips to organize long media files. You work with subclips in a Timeline panel as you do with master clips. Trimming and editing a subclip is constrained by its start and end points. Clipping helps in overcome the the memory error occur while showing large video at a single time.
In order to do this we will use subclip method with the VideoFileClip object
Syntax : clip.subclip(i, j)
Argument : It takes two integer argument which are starting and ending value in seconds
Return : It returns VideoFileClip object
Below is the implementation
# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video dsa gfg intro videoclip = VideoFileClip("dsa_geek.webm") # getting subclip as video is largeclip = clip.subclip(55, 65) # showing clipclip.ipython_display(width = 480)
Output :
Moviepy - Building video __temp__.mp4.
Moviepy - Writing video __temp__.mp4
Moviepy - Done !
Moviepy - video ready __temp__.mp4
Another example
# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video gfgclip = VideoFileClip("geeks.mp4") # getting subclip clip = clip.subclip(0, 7) # showing clipclip.ipython_display()
Output :
Moviepy - Building video __temp__.mp4.
MoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3
MoviePy - Done.
Moviepy - Writing video __temp__.mp4
Moviepy - Done !
Moviepy - video ready __temp__.mp
Python-MoviePy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 614,
"s": 28,
"text": "In this article we will see how we can show a video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GI... |
HTML - <hr> Tag | The HTML <hr> tag is used for creating a horizontal line. This is also called Horizontal Rule in HTML.
<!DOCTYPE html>
<html>
<head>
<title>HTML hr Tag</title>
</head>
<body>
<p>This text will be followed by a horizontal line <hr /></p>
</body>
</html>
This will produce the following result −
This text will be followed by a horizontal line
This tag supports all the global attributes described in − HTML Attribute Reference
The HTML <hr> tag also supports following additional attributes −
This tag supports all the event attributes described in − HTML Events Reference | [
{
"code": null,
"e": 2611,
"s": 2508,
"text": "The HTML <hr> tag is used for creating a horizontal line. This is also called Horizontal Rule in HTML."
},
{
"code": null,
"e": 2788,
"s": 2611,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML hr Tag</title>\n </he... |
R – while loop | 27 Oct, 2021
While loop in R programming language is used when the exact number of iterations of loop is not known beforehand. It executes the same code again and again until a stop condition is met. While loop checks for the condition to be true or false n+1 times rather than n times. This is because the while loop checks for the condition before entering the body of the loop.
while (test_expression) {
statement
update_expression
}
Control falls into the while loop.
The flow jumps to Condition
Condition is tested. If Condition yields true, the flow goes into the Body.If Condition yields false, the flow goes outside the loop
If Condition yields true, the flow goes into the Body.
If Condition yields false, the flow goes outside the loop
The statements inside the body of the loop get executed.
Updation takes place.
Control flows back to Step 2.
The while loop has ended and the flow has gone outside.
It seems to be that while loop will run forever but it is not true, condition is provided to stop it.
When the condition is tested and the result is false then loop is terminated.
And when the tested result is True, then loop will continue its execution.
Example 1:
R
# R program to illustrate while loop result <- c("Hello World")i <- 1 # test expressionwhile (i < 6) { print(result) # update expression i = i + 1}
Output:
[1] "Hello World"
[1] "Hello World"
[1] "Hello World"
[1] "Hello World"
[1] "Hello World"
Example 2:
R
# R program to illustrate while loop result <- 1i <- 1 # test expressionwhile (i < 6) { print(result) # update expression i = i + 1 result = result + 1}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Here we will use the break statement in the R programming language. Break statement in R is used to bring the control out of the loop when some external condition is triggered.
R
# R program to illustrate while loop result <- c("Hello World")i <- 1 # test expressionwhile (i < 6) { print(result) if( i == 3){ break} # update expression i = i + 1}
Output:
[1] "Hello World"
[1] "Hello World"
[1] "Hello World"
kumar_satyam
Picked
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change column name of a given DataFrame in R
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Adding elements in a vector in R programming - append() method
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
Convert Factor to Numeric and Numeric to Factor in R Programming | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Oct, 2021"
},
{
"code": null,
"e": 396,
"s": 28,
"text": "While loop in R programming language is used when the exact number of iterations of loop is not known beforehand. It executes the same code again and again until a stop condit... |
Dart – Date and Time | 23 Feb, 2021
A DateTime object is a point in time. The time zone is either UTC or the local time zone. Accurate date-time handling is required in almost every data context. Dart has the marvelous built-in classes DateTime and Duration in dart:core.Some of its uses are:
Compare and calculate with date times
Get every part of a date-time
Work with different time zones
Measure time spans
Example:
Dart
void main(){ // Get the current date and time.var now = DateTime.now();print(now); // Create a new DateTime with the local time zone.var y2k = DateTime(2000); // January 1, 2000print(y2k); // Specify the month and day.y2k = DateTime(2000, 1, 2); // January 2, 2000print(y2k); // Specify the date as a UTC time.y2k = DateTime.utc(2000); // 1/1/2000, UTCprint(y2k); // Specify a date and time in ms since the Unix epoch.y2k = DateTime.fromMillisecondsSinceEpoch(946684800000, isUtc: true);print(y2k); // Parse an ISO 8601 date.y2k = DateTime.parse('2000-01-01T00:00:00Z');print(y2k);}
Output:
2020-08-25 11:58:56.257
2000-01-01 00:00:00.000
2000-01-02 00:00:00.000
2000-01-01 00:00:00.000Z
2000-01-01 00:00:00.000Z
2000-01-01 00:00:00.000Z
The millisecondsSinceEpoch property of a date returns the number of milliseconds since the “Unix epoch”—January 1, 1970, UTC.
Example:
Dart
void main(){ // 1/1/2000, UTCvar y2k = DateTime.utc(2000);print(y2k.millisecondsSinceEpoch == 946684800000); // 1/1/1970, UTCvar unixEpoch = DateTime.utc(1970);print(unixEpoch.millisecondsSinceEpoch == 0);}
Output:
true
true
The Duration class can be used to calculate the difference between two dates and to move date forward or backward.
Example:
Dart
void main(){ var y2k = DateTime.utc(2000); // Add one year.var y2001 = y2k.add(Duration(days: 366));print(y2001.year == 2001); // Subtract 30 days.var december2000 = y2001.subtract(Duration(days: 30));assert(december2000.year == 2000);print(december2000.month == 12); // Calculate the difference between two dates.// Returns a Duration object.var duration = y2001.difference(y2k);print(duration.inDays == 366); // y2k was a leap year. }
Output:
true
true
true
Dart-Date
Dart-Time
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Feb, 2021"
},
{
"code": null,
"e": 285,
"s": 28,
"text": "A DateTime object is a point in time. The time zone is either UTC or the local time zone. Accurate date-time handling is required in almost every data context. Dart has the ma... |
How to use a specific chrome profile in selenium? | We can use a specific Chrome profile in Selenium. This can be done with the help of the ChromeOptions class. We need to create an object of this class and then apply addArguments method on it.
The path of the specific Chrome profile that we want to use is passed as a parameter to this method. We can open Chrome’s default profile with Selenium. To get the Chrome profile path, we need to input chrome://version/ in the Chrome browser and then press enter.
Syntax
o = webdriver.ChromeOptions()
o.add_argument = {'user-data-dir':'/Users/Application/Chrome/Default'}
Code Implementation
from selenium import webdriver
#object of ChromeOptions class
o = webdriver.ChromeOptions()
#adding specific Chrome Profile Path
o.add_arguments = {'user-data-dir':'<path of specific Chrome profile>'}
#set chromedriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe", options=o)
#maximize browser
driver.maximize_window()
#launch URL
driver.get("https://www.tutorialspoint.com/index.htm")
#get browser title
print(driver.title)
#close browser
driver.close() | [
{
"code": null,
"e": 1380,
"s": 1187,
"text": "We can use a specific Chrome profile in Selenium. This can be done with the help of the ChromeOptions class. We need to create an object of this class and then apply addArguments method on it."
},
{
"code": null,
"e": 1644,
"s": 1380,
... |
How to Send WhatsApp Message to an Unsaved Number? | 28 Feb, 2021
Generally, if we want to send a WhatsApp message to any number registered on WhatsApp we have to start a chat from the contacts page. This requires us to have that particular contact already saved in our phone. Unlike the traditional SMS service, using the WhatsApp app, we cannot just enter a number and start a chat with an unknown/unsaved contact, while the reverse works, i.e. we can receive chats from an unknown number.
However, there is a trick using which this can be made possible.
Enter this URL in a browser, replacing the CC with the country dialing code without any symbol (91 for India) and the XXXXXXXXXX with the 10-digit phone number you wish to start a conversation with.
wa.me/CCXXXXXXXXXX
for eg:
wa.me/919876543210
This URL then expands to :
https://api.whatsapp.com/send/?phone=919876543210
This is basically a WhatsApp API, so this method is completely safe and not a 3rd party plugin.
If this URL is sent as a WhatsApp message, then simply clicking on it will start a chat with the desired number.
If doing this from a PC
Make sure you are logged on to web.whatsapp.com or the WhatsApp desktop app.
Then click on the Continue to Chat (if using WhatsApp web) or Open WhatsApp Desktop (if logged on the Desktop App) button and you are good to go.
Whatsapp Send Message to Unknown Number
Using this you can send a message to yourselves too for making a grocery list or creating such draft messages.
Technical Scripter 2020
Technical Scripter
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Feb, 2021"
},
{
"code": null,
"e": 478,
"s": 52,
"text": "Generally, if we want to send a WhatsApp message to any number registered on WhatsApp we have to start a chat from the contacts page. This requires us to have that particular... |
Divide two integers without using multiplication, division and mod operator | 14 Jun, 2022
Given a two integers say a and b. Find the quotient after dividing a by b without using multiplication, division and mod operator.
Example:
Input : a = 10, b = 3
Output : 3
Input : a = 43, b = -8
Output : -5
Approach : Keep subtracting the divisor from the dividend until the dividend becomes less than the divisor. The dividend becomes the remainder, and the number of times subtraction is done becomes the quotient. Below is the implementation of the above approach :
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to Divide two// integers without using multiplication,// division and mod operator#include <bits/stdc++.h>using namespace std; // Function to divide a by b and// return floor value of the resultint divide(int dividend, int divisor){ // Calculate sign of divisor i.e., // sign will be negative only if // either one of them is negative // otherwise it will be positive int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1; // Update both divisor and // dividend positive dividend = abs(dividend); divisor = abs(divisor); // Initialize the quotient int quotient = 0; while (dividend >= divisor) { dividend -= divisor; ++quotient; } // Return the value of quotient with the appropriate // sign. return quotient * sign;} // Driver codeint main(){ int a = 10, b = 3; cout << divide(a, b) << "\n"; a = 43, b = -8; cout << divide(a, b); return 0;}
/*Java implementation to Divide twointegers without using multiplication,division and mod operator*/ import java.io.*; class GFG { // Function to divide a by b and // return floor value it static int divide(int dividend, int divisor) { // Calculate sign of divisor i.e., // sign will be negative only if // either one of them is negative // otherwise it will be positive int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1; // Update both divisor and // dividend positive dividend = Math.abs(dividend); divisor = Math.abs(divisor); // Initialize the quotient int quotient = 0; while (dividend >= divisor) { dividend -= divisor; ++quotient; } // if the sign value computed earlier is -1 then // negate the value of quotient if (sign == -1) quotient = -quotient; return quotient; } public static void main(String[] args) { int a = 10; int b = 3; System.out.println(divide(a, b)); a = 43; b = -8; System.out.println(divide(a, b)); }} // This code is contributed by upendra singh bartwal.
# Python 3 implementation to Divide two# integers without using multiplication,# division and mod operator # Function to divide a by b and# return floor value it def divide(dividend, divisor): # Calculate sign of divisor i.e., # sign will be negative only if # either one of them is negative # otherwise it will be positive sign = -1 if ((dividend < 0) ^ (divisor < 0)) else 1 # Update both divisor and # dividend positive dividend = abs(dividend) divisor = abs(divisor) # Initialize the quotient quotient = 0 while (dividend >= divisor): dividend -= divisor quotient += 1 # if the sign value computed earlier is -1 then negate the value of quotient if sign == -1: quotient = -quotient return quotient # Driver codea = 10b = 3print(divide(a, b))a = 43b = -8print(divide(a, b)) # This code is contributed by# Smitha Dinesh Semwal
// C# implementation to Divide two without// using multiplication, division and mod// operatorusing System; class GFG { // Function to divide a by b and // return floor value it static int divide(int dividend, int divisor) { // Calculate sign of divisor i.e., // sign will be negative only if // either one of them is negative // otherwise it will be positive int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1; // Update both divisor and // dividend positive dividend = Math.Abs(dividend); divisor = Math.Abs(divisor); // Initialize the quotient int quotient = 0; while (dividend >= divisor) { dividend -= divisor; ++quotient; } // if the sign value computed earlier is -1 then // negate the value of quotient if (sign == -1) quotient = -quotient; return quotient; } public static void Main() { int a = 10; int b = 3; Console.WriteLine(divide(a, b)); a = 43; b = -8; Console.WriteLine(divide(a, b)); }} // This code is contributed by vt_m.
<?php// PHP implementation to Divide two// integers without using multiplication,// division and mod operator // Function to divide a by b and// return floor value itfunction divide($dividend, $divisor) { // Calculate sign of divisor i.e., // sign will be negative only if // either one of them is negative // otherwise it will be positive $sign = (($dividend < 0) ^ ($divisor < 0)) ? -1 : 1; // Update both divisor and // dividend positive $dividend = abs($dividend); $divisor = abs($divisor); // Initialize the quotient $quotient = 0; while ($dividend >= $divisor) { $dividend -= $divisor; ++$quotient; } //if the sign value computed earlier is -1 then negate the value of quotient if($sign==-1) $quotient=-$quotient; return $quotient;} // Driver code$a = 10;$b = 3;echo divide($a, $b)."\n"; $a = 43;$b = -8;echo divide($a, $b); // This code is contributed by Sam007?>
<script> // Javascript implementation to Divide two// integers without using multiplication,// division and mod operator // Function to divide a by b and// return floor value itfunction divide(dividend, divisor) { // Calculate sign of divisor i.e.,// sign will be negative only if// either one of them is negative// otherwise it will be positivelet sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1; // Update both divisor and// dividend positivedividend = Math.abs(dividend);divisor = Math.abs(divisor); // Initialize the quotientlet quotient = 0;while (dividend >= divisor) { dividend -= divisor; ++quotient;}//if the sign value computed earlier is -1 then negate the value of quotientif(sign==-1) quotient=-quotient;return quotient;} // Driver codelet a = 10, b = 3;document.write(divide(a, b) + "<br>"); a = 43, b = -8;document.write(divide(a, b)); // This code is contributed by Surbhi Tyagi. </script>
3
-5
Time complexity : O(a/b) Auxiliary space : O(1)Efficient Approach: Use bit manipulation in order to find the quotient. The divisor and dividend can be written as
dividend = quotient * divisor + remainder
As every number can be represented in base 2(0 or 1), represent the quotient in binary form by using the shift operator as given below :
Determine the most significant bit in the divisor. This can easily be calculated by iterating on the bit position i from 31 to 1.Find the first bit for which divisor << i is less than dividend and keep updating the ith bit position for which it is true.Add the result in the temp variable for checking the next position such that (temp + (divisor << i) ) is less than the dividend.Return the final answer of the quotient after updating with a corresponding sign.
Determine the most significant bit in the divisor. This can easily be calculated by iterating on the bit position i from 31 to 1.
Find the first bit for which divisor << i is less than dividend and keep updating the ith bit position for which it is true.
Add the result in the temp variable for checking the next position such that (temp + (divisor << i) ) is less than the dividend.
Return the final answer of the quotient after updating with a corresponding sign.
Below is the implementation of the above approach :
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to Divide two// integers without using multiplication,// division and mod operator#include <bits/stdc++.h>using namespace std; // Function to divide a by b and// return floor value itint divide(long long dividend, long long divisor) { // Calculate sign of divisor i.e., // sign will be negative only if // either one of them is negative // otherwise it will be positive int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1; // remove sign of operands dividend = abs(dividend); divisor = abs(divisor); // Initialize the quotient long long quotient = 0, temp = 0; // test down from the highest bit and // accumulate the tentative value for // valid bit for (int i = 31; i >= 0; --i) { if (temp + (divisor << i) <= dividend) { temp += divisor << i; quotient |= 1LL << i; } } //if the sign value computed earlier is -1 then negate the value of quotient if(sign==-1) quotient=-quotient; return quotient;} // Driver codeint main() { int a = 10, b = 3; cout << divide(a, b) << "\n"; a = 43, b = -8; cout << divide(a, b); return 0;}
// Java implementation to Divide// two integers without using// multiplication, division// and mod operatorimport java.io.*;import java.util.*; // Function to divide a by b// and return floor value itclass GFG{public static long divide(long dividend, long divisor){ // Calculate sign of divisor// i.e., sign will be negative// only if either one of them// is negative otherwise it// will be positivelong sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1; // remove sign of operandsdividend = Math.abs(dividend);divisor = Math.abs(divisor); // Initialize the quotientlong quotient = 0, temp = 0; // test down from the highest// bit and accumulate the// tentative value for// valid bit// 1<<31 behaves incorrectly and gives Integer// Min Value which should not be the case, instead // 1L<<31 works correctly.for (int i = 31; i >= 0; --i){ if (temp + (divisor << i) <= dividend) { temp += divisor << i; quotient |= 1L << i; }} //if the sign value computed earlier is -1 then negate the value of quotientif(sign==-1) quotient=-quotient;return quotient;} // Driver codepublic static void main(String args[]){int a = 10, b = 3;System.out.println(divide(a, b)); int a1 = 43, b1 = -8;System.out.println(divide(a1, b1)); }} // This code is contributed// by Akanksha Rai(Abby_akku)
# Python3 implementation to# Divide two integers# without using multiplication,# division and mod operator # Function to divide a by# b and return floor value itdef divide(dividend, divisor): # Calculate sign of divisor # i.e., sign will be negative # either one of them is negative # only if otherwise it will be # positive sign = (-1 if((dividend < 0) ^ (divisor < 0)) else 1); # remove sign of operands dividend = abs(dividend); divisor = abs(divisor); # Initialize # the quotient quotient = 0; temp = 0; # test down from the highest # bit and accumulate the # tentative value for valid bit for i in range(31, -1, -1): if (temp + (divisor << i) <= dividend): temp += divisor << i; quotient |= 1 << i; #if the sign value computed earlier is -1 then negate the value of quotient if sign ==-1 : quotient=-quotient; return quotient; # Driver codea = 10;b = 3;print(divide(a, b)); a = 43;b = -8;print(divide(a, b)); # This code is contributed by mits
// C# implementation to Divide// two integers without using// multiplication, division// and mod operatorusing System; // Function to divide a by b// and return floor value itclass GFG{public static long divide(long dividend, long divisor){ // Calculate sign of divisor// i.e., sign will be negative// only if either one of them// is negative otherwise it// will be positivelong sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1; // remove sign of operandsdividend = Math.Abs(dividend);divisor = Math.Abs(divisor); // Initialize the quotientlong quotient = 0, temp = 0; // test down from the highest// bit and accumulate the// tentative value for// valid bitfor (int i = 31; i >= 0; --i){ if (temp + (divisor << i) <= dividend) { temp += divisor << i; quotient |= 1LL << i; }}//if the sign value computed earlier is -1 then negate the value of quotient if(sign==-1) quotient=-quotient;return quotient;} // Driver codepublic static void Main(){int a = 10, b = 3;Console.WriteLine(divide(a, b)); int a1 = 43, b1 = -8;Console.WriteLine(divide(a1, b1)); }} // This code is contributed by mits
<?php// PHP implementation to// Divide two integers// without using multiplication,// division and mod operator // Function to divide a by// b and return floor value itfunction divide($dividend, $divisor){ // Calculate sign of divisor// i.e., sign will be negative// either one of them is negative// only if otherwise it will be// positive$sign = (($dividend < 0) ^ ($divisor < 0)) ? -1 : 1; // remove sign of operands$dividend = abs($dividend);$divisor = abs($divisor); // Initialize// the quotient$quotient = 0;$temp = 0; // test down from the highest// bit and accumulate the// tentative value for valid bitfor ($i = 31; $i >= 0; --$i){ if ($temp + ($divisor << $i) <= $dividend) { $temp += $divisor << $i; $quotient |= (double)(1) << $i; }}//if the sign value computed earlier is -1 then negate the value of quotientif($sign==-1) $quotient=-$quotient;return $quotient;} // Driver code$a = 10;$b = 3;echo divide($a, $b). "\n"; $a = 43;$b = -8;echo divide($a, $b); // This code is contributed by mits?>
<script> // JavaScript implementation to Divide// two integers without using// multiplication, division// and mod operator // Function to divide a by b// and return floor value it function divide(dividend, divisor){ // Calculate sign of divisor// i.e., sign will be negative// only if either one of them// is negative otherwise it// will be positivevar sign = ((dividend < 0)?1:0 ^ (divisor < 0)?1:0) ? -1 : 1; // remove sign of operandsdividend = Math.abs(dividend);divisor = Math.abs(divisor); // Initialize the quotientvar quotient = 0, temp = 0; // test down from the highest// bit and accumulate the// tentative value for// valid bitwhile (dividend >= divisor) { dividend -= divisor; ++quotient;}//if the sign value computed earlier is -1 then negate the value of quotientif(sign==-1) quotient=-quotient;return quotient;} // Driver code var a = 10, b = 3;document.write(divide(a, b) + "<br>"); var a1 = 43, b1 = -8;document.write(divide(a1, b1) + "<br>"); </script>
3
-5
Time complexity : O(log(a)) Auxiliary space : O(1)
Sam007
Mithun Kumar
Akanksha_Rai
ajit2994
nirajkumar123580
abhishekagc966
ujjwalmittal
surbhityagi15
rutvik_56
shetgaonkarashwin18
akhilkashyap
akashdeep8
vaibhavimandloi
surinderdawra388
SristiJain1
simmytarika5
kingrishabdugar
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
Bits manipulation (Important tactics)
Josephus problem | Set 1 (A O(n) Solution)
Bit Fields in C
C++ bitset and its application
Find the element that appears once
Add two numbers without using arithmetic operators
Set, Clear and Toggle a given bit of a number in C
Cyclic Redundancy Check and Modulo-2 Division
Count total set bits in all numbers from 1 to n | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Jun, 2022"
},
{
"code": null,
"e": 185,
"s": 54,
"text": "Given a two integers say a and b. Find the quotient after dividing a by b without using multiplication, division and mod operator."
},
{
"code": null,
"e": 195,
... |
Maximum number formed from array with K number of adjacent swaps allowed | 05 Aug, 2021
Given an array a[ ] and the number of adjacent swap operations allowed are K. The task is to find the max number that can be formed using these swap operations. Examples:
Input : a[]={ 1, 2, 9, 8, 1, 4, 9, 9, 9 }, K = 4 Output : 9 8 1 2 1 4 9 9 9 After 1st swap a[ ] becomes 1 9 2 8 1 4 9 9 9 After 2nd swap a[ ] becomes 9 1 2 8 1 4 9 9 9 After 3rd swap a[ ] becomes 9 1 8 2 1 4 9 9 9 After 4th swap a[ ] becomes 9 8 1 2 1 4 9 9 9Input : a[]={2, 5, 8, 7, 9}, K = 2 Output : 8 2 5 7 9
Approach:
Starting from the first digit, check for the next K digits and store the index of the largest number.
Bring that greatest digit to the top by swapping the adjacent digits.
Reduce to value of K by the number of adjacent swaps done.
Repeat the above steps until the number of swaps becomes zero.
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 print the// elements of the arrayvoid print(int arr[], int n){ for (int i = 0; i < n; i++) { cout << arr[i] << " "; } cout << endl;} // Exchange array elements one by// one from right to left side// starting from the current position// and ending at the target positionvoid swapMax(int* arr, int target_position, int current_position){ int aux = 0; for (int i = current_position; i > target_position; i--) { aux = arr[i - 1]; arr[i - 1] = arr[i]; arr[i] = aux; }} // Function to return the// maximum number arrayvoid maximizeArray(int* arr, int length, int swaps){ // Base condition if (swaps == 0) return; // Start from the first index for (int i = 0; i < length; i++) { int max_index = 0, max = INT_MIN; // Search for the next K elements int limit = (swaps + i) > length ? length : swaps + i; // Find index of the maximum // element in next K elements for (int j = i; j <= limit; j++) { if (arr[j] > max) { max = arr[j]; max_index = j; } } // Update the value of // number of swaps swaps -= (max_index - i); // Update the array elements by // swapping adjacent elements swapMax(arr, i, max_index); if (swaps == 0) break; }} // Driver codeint main(){ int arr[] = { 1, 2, 9, 8, 1, 4, 9, 9, 9 }; int length = sizeof(arr) / sizeof(int); int swaps = 4; maximizeArray(arr, length, swaps); print(arr, length); return 0;}
// Java implementation of the above approachclass GFG{ // Function to print the// elements of the arraystatic void print(int arr[], int n){ for (int i = 0; i < n; i++) { System.out.print(arr[i] + " "); } System.out.println();} // Exchange array elements one by// one from right to left side// starting from the current position// and ending at the target positionstatic void swapMax(int[] arr, int target_position, int current_position){ int aux = 0; for (int i = current_position; i > target_position; i--) { aux = arr[i - 1]; arr[i - 1] = arr[i]; arr[i] = aux; }} // Function to return the// maximum number arraystatic void maximizeArray(int[] arr, int length, int swaps){ // Base condition if (swaps == 0) return; // Start from the first index for (int i = 0; i < length; i++) { int max_index = 0, max = Integer.MIN_VALUE; // Search for the next K elements int limit = (swaps + i) > length ? length : swaps + i; // Find index of the maximum // element in next K elements for (int j = i; j <= limit; j++) { if (arr[j] > max) { max = arr[j]; max_index = j; } } // Update the value of // number of swaps swaps -= (max_index - i); // Update the array elements by // swapping adjacent elements swapMax(arr, i, max_index); if (swaps == 0) break; }} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 2, 9, 8, 1, 4, 9, 9, 9 }; int length = arr.length; int swaps = 4; maximizeArray(arr, length, swaps); print(arr, length);}} /* This code is contributed by PrinciRaj1992 */
# Python3 implementation of the above approachimport sys # Function to print the# elements of the arraydef print_ele(arr, n) : for i in range(n) : print(arr[i],end=" "); print(); # Exchange array elements one by# one from right to left side# starting from the current position# and ending at the target positiondef swapMax(arr, target_position, current_position) : aux = 0; for i in range(current_position, target_position,-1) : aux = arr[i - 1]; arr[i - 1] = arr[i]; arr[i] = aux; # Function to return the# maximum number arraydef maximizeArray(arr, length, swaps) : # Base condition if (swaps == 0) : return; # Start from the first index for i in range(length) : max_index = 0; max = -(sys.maxsize-1); # Search for the next K elements if (swaps + i) > length : limit = length else: limit = swaps + i # Find index of the maximum # element in next K elements for j in range(i, limit + 1) : if (arr[j] > max) : max = arr[j]; max_index = j; # Update the value of # number of swaps swaps -= (max_index - i); # Update the array elements by # swapping adjacent elements swapMax(arr, i, max_index); if (swaps == 0) : break; # Driver codeif __name__ == "__main__" : arr = [ 1, 2, 9, 8, 1, 4, 9, 9, 9 ]; length = len(arr); swaps = 4; maximizeArray(arr, length, swaps); print_ele(arr, length); # This code is contributed by AnkitRai01
// C# program to find the sum// and product of k smallest and// k largest prime numbers in an array using System; class GFG{ // Function to print the// elements of the arraystatic void print(int []arr, int n){ for (int i = 0; i < n; i++) { Console.Write(arr[i] + " "); } Console.WriteLine();} // Exchange array elements one by// one from right to left side// starting from the current position// and ending at the target positionstatic void swapMax(int[] arr, int target_position, int current_position){ int aux = 0; for (int i = current_position; i > target_position; i--) { aux = arr[i - 1]; arr[i - 1] = arr[i]; arr[i] = aux; }} // Function to return the// maximum number arraystatic void maximizeArray(int[] arr, int length, int swaps){ // Base condition if (swaps == 0) return; // Start from the first index for (int i = 0; i < length; i++) { int max_index = 0, max = int.MinValue; // Search for the next K elements int limit = (swaps + i) > length ? length : swaps + i; // Find index of the maximum // element in next K elements for (int j = i; j <= limit; j++) { if (arr[j] > max) { max = arr[j]; max_index = j; } } // Update the value of // number of swaps swaps -= (max_index - i); // Update the array elements by // swapping adjacent elements swapMax(arr, i, max_index); if (swaps == 0) break; }} // Driver codepublic static void Main(String[] args){ int []arr = { 1, 2, 9, 8, 1, 4, 9, 9, 9 }; int length = arr.Length; int swaps = 4; maximizeArray(arr, length, swaps); print(arr, length);}} /* This code is contributed by PrinciRaj1992 */
<script> // JavaScript implementation of the above approach // Function to print the// elements of the arrayfunction print(arr, n) { for (let i = 0; i < n; i++) { document.write(arr[i] + " "); } document.write("<br>");} // Exchange array elements one by// one from right to left side// starting from the current position// and ending at the target positionfunction swapMax(arr, target_position, current_position) { let aux = 0; for (let i = current_position; i > target_position; i--) { aux = arr[i - 1]; arr[i - 1] = arr[i]; arr[i] = aux; }} // Function to return the// maximum number arrayfunction maximizeArray(arr, length, swaps) { // Base condition if (swaps == 0) return; // Start from the first index for (let i = 0; i < length; i++) { let max_index = 0, max = Number.MIN_SAFE_INTEGER; // Search for the next K elements let limit = (swaps + i) > length ? length : swaps + i; // Find index of the maximum // element in next K elements for (let j = i; j <= limit; j++) { if (arr[j] > max) { max = arr[j]; max_index = j; } } // Update the value of // number of swaps swaps -= (max_index - i); // Update the array elements by // swapping adjacent elements swapMax(arr, i, max_index); if (swaps == 0) break; }} // Driver code let arr = [1, 2, 9, 8, 1, 4, 9, 9, 9];let length = arr.length;let swaps = 4;maximizeArray(arr, length, swaps); print(arr, length); // This code is contributed by gfgking </script>
9 8 1 2 1 4 9 9 9
Time Complexity: O(N*N) where N is the length of given array
princiraj1992
ankthon
gfgking
saurabh1990aror
number-digits
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
What is Data Structure: Types, Classifications and Applications
Chocolate Distribution Problem
Next Greater Element
Find duplicates in O(n) time and O(1) extra space | Set 1
Find subarray with given sum | Set 1 (Nonnegative Numbers)
Move all negative numbers to beginning and positive to end with constant extra space
Count pairs with given sum | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n05 Aug, 2021"
},
{
"code": null,
"e": 227,
"s": 54,
"text": "Given an array a[ ] and the number of adjacent swap operations allowed are K. The task is to find the max number that can be formed using these swap operations. Examples: "
... |
Deploying an Image Classification Web App with Python | by Ruben Winastwan | Towards Data Science | It is no doubt that doing a data science and machine learning project, starting from collecting the data, processing the data, visualizing insights about the data, and developing a machine learning model to do a predictive task is a fun thing to do. What makes it more fun and doable is that we can do all of those steps in our local machine and then be done with it.
However, wouldn’t it be awesome if other people can make use of our machine learning model to do fun and cool stuff? The true magic of machine learning comes when our model can get into other people’s hand and they can do useful stuff from it.
Creating a web app is one of the solutions such that other people can make use of our machine learning model. Fortunately, it is very simple to create a web app nowadays.
If you’re using Python, you can use Streamlit library to create a simple machine learning web app in your local machine. To deploy the web app to be accessible to other people, then we can use Heroku or other cloud platforms. In this article, I will show you step-by-step on how to create your own simple web app for image classification using Python, Streamlit, and Heroku.
If you haven’t installed Streamlit yet, you can install it by running the following pip command in your prompt.
pip install streamlit
For this image classification example, the rock-paper-scissor dataset created by Laurence Moroney will be used. You can download the data on his website. As a summary, rock-paper-scissor is a synthetic dataset which contains people’s hand forming either rock, paper, or scissor shape. In total, there are 2520 training images and 372 test images.
Below is the sneak-peek of what the synthetic image data look like:
Overall there are three steps will be covered in this article:
Creating the first Python file to load the data, build the model, and finally train the model.
Creating the second Python file to load the model and to build the web app.
Deploying the web app using Heroku.
As a first step, download the training set and the test set and save it to the directory of your choice. Next, you need to unzip them. There will be two folders, one called ‘rps’ for training images and the other called ‘rps-test-set’ for test images. After that, create a Python file called rps_model.py to load the data, build the machine learning model, and train the model.
Before building the model, you need to first specify the path to the training set folder and the test set folder in your local machine using os library.
import ostrain_dir = os.path.join('directory/to/your/rps/')test_dir = os.path.join('directory/to/your/rps-test-set/')
Next, we can use image generator from TensorFlow library to generate training and test set as well as to automatically label the data. Another advantage of using image generator is that we can do data augmentation ‘on the fly’ to increase the number of training set by zooming, rotating, or shifting the training images. Also, we can split a certain portion of the training set for the validation set to compare the performance of the model.
from tensorflow.keras.preprocessing.image import ImageDataGeneratordef image_gen_w_aug(train_parent_directory, test_parent_directory): train_datagen = ImageDataGenerator(rescale=1/255, rotation_range = 30, zoom_range = 0.2, width_shift_range=0.1, height_shift_range=0.1, validation_split = 0.15) test_datagen = ImageDataGenerator(rescale=1/255) train_generator = train_datagen.flow_from_directory(train_parent_directory, target_size = (75,75), batch_size = 214, class_mode = 'categorical', subset='training') val_generator = train_datagen.flow_from_directory(train_parent_directory, target_size = (75,75), batch_size = 37, class_mode = 'categorical', subset = 'validation') test_generator = test_datagen.flow_from_directory(test_parent_directory, target_size=(75,75), batch_size = 37, class_mode = 'categorical') return train_generator, val_generator, test_generator
After creating the function above, now you can call the function and pass the argument with train_dir and test_dir variables that you have defined before.
train_generator, validation_generator, test_generator = image_gen_w_aug(train_dir, test_dir)
And with this step, you have already loaded the data!
As a machine learning model, you can build your own CNN model if you wish. But in this article, transfer learning method will be applied instead. The InceptionV3 model with pre-trained weights from ImageNet is used.
However, since this model is very deep, the model used will be until the layer called mixed_5 and all the weights up until this layer are fixed to speed up the training time. From this layer, the model will be flattened to be connected to a dense layer and then to the final dense output. All the weights after mixed_5 are trainable.
from tensorflow.keras.applications.inception_v3 import InceptionV3from tensorflow.keras.layers import Flatten, Dense, Dropoutdef model_output_for_TL (pre_trained_model, last_output): x = Flatten()(last_output) # Dense hidden layer x = Dense(512, activation='relu')(x) x = Dropout(0.2)(x) # Output neuron. x = Dense(3, activation='softmax')(x) model = Model(pre_trained_model.input, x) return modelpre_trained_model = InceptionV3(input_shape = (75, 75, 3), include_top = False, weights = 'imagenet')for layer in pre_trained_model.layers: layer.trainable = Falselast_layer = pre_trained_model.get_layer('mixed5')last_output = last_layer.outputmodel_TL = model_output_for_TL(pre_trained_model, last_output)
If you haven’t imported InceptionV3 model yet, it will take a couple of minutes to download the model.
At this step, you’ve built the model! Next, we need to train the model.
Now it’s time for us to train the model. Before you train the model, first you need to compile the model. In this article, the optimizer will be Adam and since we have a classification problem, then we should use categorical cross-entropy as the loss. For the metrics, we will use accuracy.
After compiling the model, now we can train the model. After the model is trained, then we need to save the trained model. You should then have a new hdf5 file called `my_model.hdf5` in the same directory as your Python file.
model_TL.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])history_TL = model_TL.fit( train_generator, steps_per_epoch=10, epochs=20, verbose=1, validation_data = validation_generator)tf.keras.models.save_model(model_TL,'my_model.hdf5')
Now you’re done with the modelling process. You can save and close the Python file.
To create a web app with Streamlit, first thing that we need to do is creating a new Python file, let’s call it rps_app.py . In this Python file, first we need to load the trained model that we have saved before.
import tensorflow as tfmodel = tf.keras.models.load_model('my_model.hdf5')
The next step is to write a header and any other texts that you want to put into your web app. To write a header, simply use write attribute from Streamlit and then put # before your text. To write a simple text, we can also use write method and then proceed with your text without adding #
To let the user upload their own image to your web app, simply use file_uploader attribute from Streamlit library. For more detailed information regarding other options available on Streamlit, you can check it out at Streamlit API documentation page.
import streamlit as stst.write(""" # Rock-Paper-Scissor Hand Sign Prediction """ )st.write("This is a simple image classification web app to predict rock-paper-scissor hand sign")file = st.file_uploader("Please upload an image file", type=["jpg", "png"])
The next important step is to process the image the user has uploaded. The processing step including resizing the image to the same size as training and validation images. After resizing the image, then the loaded model should predict in which category this image belongs.
import cv2from PIL import Image, ImageOpsimport numpy as npdef import_and_predict(image_data, model): size = (150,150) image = ImageOps.fit(image_data, size, Image.ANTIALIAS) image = np.asarray(image) img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) img_resize = (cv2.resize(img, dsize=(75, 75), interpolation=cv2.INTER_CUBIC))/255. img_reshape = img_resize[np.newaxis,...] prediction = model.predict(img_reshape) return predictionif file is None: st.text("Please upload an image file")else: image = Image.open(file) st.image(image, use_column_width=True) prediction = import_and_predict(image, model) if np.argmax(prediction) == 0: st.write("It is a paper!") elif np.argmax(prediction) == 1: st.write("It is a rock!") else: st.write("It is a scissor!") st.text("Probability (0: Paper, 1: Rock, 2: Scissor") st.write(prediction)
After that, you need to save the Python file in the same directory as your previous Python file.
We basically all set right now! To check what our web app looks like, open your prompt, and then navigate to the working directory of your Python files. In the working directory, you can type the following command:
streamlit run rps_app.py
Now you will see from your prompt that you can check your web app on your localhost. If you wait a little bit, a new window will be launched shortly after you run your Streamlit app. Below is the screenshot of the simple image classification web app.
So far, you’ve built the web app locally on your computer. In order for other people to be able to use your web app, you can utilize Heroku.
Before we deploy the web app, we need to create three additional files in addition to Python files that we have created to build the app. These three files are:
requirements.txt: this is the text file that we need to create to tell Heroku to install the necessary Python packages needed to deploy our machine learning model. In this tutorial, we used four Python libraries to build the app: numpy, streamlit, tensorflow, and pillow. Hence, we need to specify the relevant version of those libraries in this text file.
tensorflow==2.0.0streamlit==0.62.0numpy==1.16.5pillow==6.2.0
If you are unsure about the version of the Python libraries that you are using, you can use ‘__version__’ attribute in your Python environment or type ‘conda list’ in your conda prompt.
setup.sh: this file is necessary to handle the server and port number of our app on Heroku.
mkdir -p ~/.streamlit/ echo "\ [server]\n\ port = $PORT\n\ enableCORS = false\n\ headless = true\n\ \n\ " > ~/.streamlit/config.toml
Procfile: this is the file of your configuration to tell Heroku how and which files to be executed.
web: sh setup.sh && streamlit run rps_app.py
Now that you have these three files, place them in the same directory as your Python files.
Next, let’s jump into Heroku.
If you already have Heroku account, you can skip this step. If you haven’t, then you can directly go to Heroku. There you’ll find a ‘Sign Up’ button, click that button and fill the necessary information. After that, you need to confirm your new Heroku account with your E-Mail.
After you have created a Heroku account, the next thing that you need to do is to install Heroku CLI (command-line interface). Next, open your command prompt and type the following command.
heroku login
This command will direct you to login with your Heroku account.
Next, move to the directory of your app files with the command prompt. In the directory of your app files, type the following command.
heroku create your_app_name
You can change the your_app_name with your preference as the app name. Next, you need to initiate an empty git repository by typing the following command.
git init
Next, you want to submit all of your app files to the empty repository that you’ve just created. To do this, you can type git add . command and then you need to push them by typing commit and push commands as follows.
git add .git commit -m "your message"git push heroku master
Now your app files will be deployed to Heroku with Heroku Git and after the process is completed, you will see the URL of your web app that can be accessed via the internet. The format of your web app URL is something like your_app_name.herokuapp.com.
Below is the example of a simple web app that has been deployed with Heroku.
And that’s it! Your image classification web app has been deployed!
If you want to see the code of the web app or other necessary files in this tutorial, you can see it on my GitHub. | [
{
"code": null,
"e": 539,
"s": 171,
"text": "It is no doubt that doing a data science and machine learning project, starting from collecting the data, processing the data, visualizing insights about the data, and developing a machine learning model to do a predictive task is a fun thing to do. What ... |
Implementing Spatial Transformer Network (STN) in TensorFlow | by Parth Rajesh Dedhia | Towards Data Science | Convolution Neural Networks apply a convolution filter, on the input image in the first layer, and then on the feature maps. The CNN’s have provided extra-ordinary results by using the same weights of the filter over several parts of the same image. The results were further boosted by adding a Max Pooling layer between the Convolution layers. This pooling layer not only reduced the parameters but also improved the performance of the CNN models.
This combination of CNN and the Pooling layer provides translational in-variance: can predict a particular object only if the object is moved around in the image. However, the orientation and shape of the object should not change much. This becomes a major drawback of CNN when used in a real-world setting.
The first idea that comes to my mind is to find some black-box that could transform the image to an ideal standard so that the same classification could be re-used. Deep Mind did the same thing, they proposed a module called Spatial Transformer Network, which performs transformation to an input image. This model can be regarded as an attention module to any spatial input. Let’s have a look at the nuts and bolts of this algorithm.
This blog post is structured as follows:
Essential NumPy Operations
Image Transformations
Bi-linear interpolation
Model Design
Results and Visualization
Conclusion
The background of NumPy advance indexing makes it easier to understand Bi-Linear interpolation. If you are aware of this concept, feel free to skip this section.
>>> x = np.random.randint(10, size=8)>>> x[[1,2,5]]array([5, 6, 2])
Internal working of the above operation:
Find the value of x[1], x[2], and x[5]
Arrange them in the order in which numbers 1, 2, and 5 appear in the input list.
Return the results
This may seem very easy, when taking about a rank-1 array. Let’s see an example of a rank-2 matrix.
>>> xarray([[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23]])>>> x[2,3]15
Till now stuff was pretty common, let’s send array rather then two numbers for indexing.
>>> x[[1,2,3], [3,2,3]]array([ 9, 14, 21])
Internal working of the above operation:
Finds values of x[1,3], x[2,2], and x[3,3]
Arrange them at the index location of the input list.
Return the results
Note: If the two lists are of different lengths, it will throw an IndexError.
However, in the above example we saw that the 2D array sent a 1D output. Let’s take this a step further.
>>> a = [[1,2], [3,0]]>>> b = [[0,1], [2,3]]>>> x[a, b]array([[ 6, 13], [20, 3]])
We will discuss the internal working for one of the element of the output, rest can be derived.
Element 2 in array a is at location [0, 1]
Element 1 in the array b is at the location [0, 1]
The element in the output array is x[2, 1] and is located at [0, 1]
Some conclusion based on the above analysis:
The shape of the output array is decided by the shape of the input indexed array.
If two arrays are sent for indexing then they should always have the same shape.
That’s it for understanding the NumPy indexing. Though we will use this later in the post, understanding it here will help to focus on the idea behind Spatial Transformer Network.
Image transformations when applied to an image will change the image and produce an output. There are many transformation operations like translation, rotation, scaling, shear, and a combination of all of the above-affine transformation. Some other transformations include projective and plate-spline transformation.
Definitions
Input Image: Image on which transformation is to be applied.
Output Image: Result of transformation on an input image.
Pixel index/indices: The location of the pixel in the input image.
The matrix defined adjacent to the image is applied to the input image to produce the transformed output. I won’t be explaining the derivation as to why these matrices produce such transformation, but you can find it here.
What we need to remember is that we need a set of six numbers, which are applied to the input image, and will produce a transformed output image. But we need to understand how these transformations are applied so we will take an input image of size 300 x 300. We will apply, scale transformation in the steps below, but the same method is used for all other transformation.
Note: Transformation happens at the pixel level. We map each pixel in the output image to a pixel of the input image and copy the pixel values.
We want to find out which pixel from the input image shall be mapped to the output image at [100, 100]
We create an array x = np.asarray([100, 100, 1]) . Note, that an extra dimension is added to the input image.
Transformation matrix theta = np.asarray([[0.5, 0, 0], [0, 0.5, 0]])
Now apply matmul operation: theta @ x and get the value as array([50., 50.])
This means that the pixel value at [50, 50] in the input image will be copied to [100, 100] in the output image.
Note: The extra dimension is added to convert the coordinates from Cartesian to Homogeneous coordinates. If you are unaware of the theory, then just add the extra dimension and move ahead.
From the above maths, we can apply any affine transformation. But on contemplating the calculation done above, one would observe that we sometimes get floating-point point numbers, and pixel indices are always integers. To solve this, we use bi-linear interpolation described in the next section.
We have previously observed that the mapping of a pixel from an output image to the input image produces floating-point values, and this makes it difficult to find the pixel value at the output location. Methods like bi-cubic, bilinear, and nearest-neighbor interpolation methods are used, but we will restrict our discussion to bi-linear interpolation.
In the above image, P (a floating-point index) is the pixel index obtained after the matmul operation is applied to the output image pixel index. The set of Qxγ’s represents the pixel intensities at nearest integral pixel indices(set of all the four [x,y]). The pixel intensity value at P is calculated by the weighted average of distances from the nearest Q’s. The R1 and R2 are an intermediate representation and will help with the maths. Also, note that x2 — x1 and y2 — y1 is 1 as the distance between neighboring pixels is 1.
The denominator in all of the above equations will be 1. So the final pixel intensities at P would be given by:
The interpolated value of intensity at point P will be mapped to the outer image pixel index. We will use this formula in the NumPy implementation below.
To find the pixel intensity in the output image, one approach is to apply a for loop for each pixel index and apply the transformation and interpolate the pixel intensity at that location. However, this will be an in-efficient approach to calculate values, we will instead use the meshgrid and linspace function of NumPy. If you are unsure what they do, print out the values at intermediate steps.
The homogeneous_co_ordinates is the set of all the output image pixel indices converted to homogeneous format (ones are added to the vector). Then we apply the transformation via the matmul operation and re-arrange the output. We then separate the x and y transformed_co_ordinates and scale them to the size of image height and width. Once again, this x and y obtained after transformation correspond to the input image pixel index which will be mapped to the output image. However, these x and y are floating points and cannot directly be mapped to a pixel intensity and interpolation will be applied.
In the gist above, the x, y represent the transformed coordinates (floating-point numbers). The x0 and y0 represent the pixel index closest to but less than x and y and x1 and y1 represent the pixel index closest to but greater than x and y. The valid combinations formed by x0, x1, y0, and y1 represent the four closest integer pixel locations around x and y. The pixel intensities at these values can be equated to Qxγ.
The img contains the desired image that is to be transformed, and it should be of size [height, width]. Our objective is to find the pixel value at P, and the naive approach to solve is for each of the x and y pair, we find the corresponding 4-pixel intensities and apply the weighted average formula discussed in the previous section. However, this approach is an in-efficient one.
We instead form 4 images, where one image contains all the set of pixel values which could be found at [x0, y0], and similarly for others. The NumPy’s advance indexing which we had discussed in the first section becomes handy here. Anyone index at Ia corresponds to theQ11 for all the possible sets of floating pixel values between that index and the adjacent one. Hence, while extrapolating for a particular index, we can find the Q11 from the corresponding pixel indices at Ia. Similar operations are performed for the other 3 Q’s.
Now we directly apply the formula for bi-linear interpolation we had discussed in the previous section and find the weights for all the transformed x and y coordinates in wa, wb, wc, and wd. Now, all we are left to do is the weighted average of Ia, Ib, Ic, and Id.
Note: If you are unsure how the above set of operations performed the transformation, read the code keeping one particular location in mind, and you will discover the magic behind it. However, the best way to understand would be to visualize the intermediate images Ia, Ib, Ic, and Id by running the code.
Fun Fact: If you are keen like me and like to visualize the intermediate representation, then always convert the dtype to np.uint8. Not doing that will destroy your sleep.
If you are here with me, then pat yourself!!!
Now we have one thing remaining, each input image may need a different transformation. How do we decide which transform to apply and what should be the numbers in the corresponding transformation matrix?
The next section will help you with that.
There is an infinite number of possible transformations that could be applied to the input image and get a transformed image. To solve this, we use a set of Convolution or Dense layers and obtain the transformation matrix by re-shaping the last dense layer. We will then send this transformation matrix along with the input image to a function that will perform the bi-linear interpolation. The image obtained after transformation can be then used for the desired task.
This Spatial Transformer Module introduced by the authors at Deep Mind is categorized into three modules — Localisation Net, Grid Generator, and Sampler. However, for easy implementation, I combine the last two modules into a single module called BilinearInterpolation. The Localization net takes input an image and the BilinearInterpolation takes to input the input image and the transformation matrix obtained from the Localization net. Both of these modules are implemented by sub-classing tf.keras.layers.Layer.
Many different sets of operations could be applied to the localization net, of which I have given one set of operations. You can change them in your implementation. Only the last two layers — dense and reshape, should be always used.
The BilinearInterpolation layer takes two parameters i.e., height and width of the output map. So by changing the size of this height and width, you can produce the transformed image of a smaller size. This layer not only performs the spatial transformation, but it can also reduce the size of the image, thus performing down-sampling, without losing essential data.
If you read the above TensorFlow implemented BilinearInterpolation layer with the NumPy implementation, you can see most of the implementation remains the same. The only difference is that TensorFlow does not support direct advance indexing as elegantly as NumPy does. Hence there is a function advance_indexing which will do the operation for you.
Tada !! We have build a Spatial Transformer Module. Let’s integrate it with a Network.
From the above gist we have seen how easily these two layers can be added to our network and provide us the transformation. Now, instead of applying them at the first layer, we can replace any of the max-pooling layers with the STN. However, the localization layer needs to change as the input image may change. This flexibility allows us to use the STN module on a feature map instead of an input image.
Fun Fact: The visualizations generated in the second section are generated by using this bi-linear interpolation layer by sending fixed theta and images
The model took around 12 seconds per epoch on Colab GPU to train. The training accuracy was 99.77% and the testing accuracy was 98.86% and the model was trained for 100 epochs. However, instead of using the MNIST dataset, I have used the AffNist dataset where the images are of size 40 x 40.
In the above image, the first row of each of the rows is the input image and the second row is the image obtained after the STN network transformation on that image. We can see how the number comes to the center and also get scaled and rotated in some cases. Hence, we can conclude STN performs different transformation operation, and the values of transformation matrix are derived from the input image, thus applied only to that image.
The entire code has been posted on the repository below, feel free to clone the code and try to run the visualizations:
github.com
We have build Spatial Transformer Module, a differentiable layer, which can substitute the max-pooling layer in the contemporary networks. Since it transforms the input image/features, it acts like attention like layer to the images/features. Though this module requires a lot of background from traditional computer Vision, the elegance of this mechanism can be seen from the visualizations shown above.
I have also written a post on Capsule Network, which also dwells on the drawbacks of the Max Pooling layers and generates rich features, which in-turn generate interpretable visualizations.
M. Jaderberg, K. Simonyan, A. Zisserman, K. Kavukcuoglu, Spatial Transformer Networks, CVPR, 2015 | [
{
"code": null,
"e": 621,
"s": 172,
"text": "Convolution Neural Networks apply a convolution filter, on the input image in the first layer, and then on the feature maps. The CNN’s have provided extra-ordinary results by using the same weights of the filter over several parts of the same image. The r... |
PHP 7 - Constant Arrays | Array constants can now be defined using the define() function. In PHP 5.6, they could only be defined using const keyword.
<?php
//define a array using define function
define('animals', [
'dog',
'cat',
'bird'
]);
print(animals[1]);
?>
It produces the following browser output −
cat
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2201,
"s": 2077,
"text": "Array constants can now be defined using the define() function. In PHP 5.6, they could only be defined using const keyword."
},
{
"code": null,
"e": 2343,
"s": 2201,
"text": "<?php\n //define a array using define function\n defin... |
What does Interface consist of in Java | An interface can be defined using the interface keyword. It contains variables and methods like a class but the methods in an interface are abstract by default unlike a class. An interface is primarily used to implement abstraction and it cannot be instantiated.
A program that demonstrates an interface in Java is given as follows:
Live Demo
interface AnimalSound {
abstract void sound();
}
class CatSound implements AnimalSound {
public void sound() {
System.out.println("Cat Sound: Meow");
}
}
class DogSound implements AnimalSound {
public void sound() {
System.out.println("Dog Sound: Bark");
}
}
class CowSound implements AnimalSound {
public void sound() {
System.out.println("Cow Sound: Moo");
}
}
public class Demo {
public static void main(String[] args) {
AnimalSound a = new CatSound();
a.sound();
}
}
Cat Sound: Meow | [
{
"code": null,
"e": 1325,
"s": 1062,
"text": "An interface can be defined using the interface keyword. It contains variables and methods like a class but the methods in an interface are abstract by default unlike a class. An interface is primarily used to implement abstraction and it cannot be inst... |
Jupyter - Converting Notebooks | Jupyter notebook files have .ipynb extension. Notebook is rendered in web browser by the notebook app. It can be exported to various file formats by using download as an option in the file menu. Jupyter also has a command line interface in the form of nbconvert option. By default, nbconvert exports the notebook to HTML format. You can use the following command for tis purpose −
jupyter nbconvert mynotebook.ipynb
This will convert mynotebook.ipynb to the mynotebook.html. Other export format is specified with `--to` clause.
Note that other options include ['asciidoc', 'custom', 'html', 'latex', 'markdown', 'notebook', 'pdf', 'python', 'rst', 'script', 'slides']
HTML includes 'basic' and 'full' templates. You can specify that in the command line as shown below −
jupyter nbconvert --to html --template basic mynotebook.ipynb
LaTex is a document preparation format used specially in scientific typesetting. Jupyter includes 'base', 'article' and 'report' templates.
jupyter nbconvert --to latex –template report mynotebook.ipynb
To generate PDF via latex, use the following command −
jupyter nbconvert mynotebook.ipynb --to pdf
Notebook can be exported to HTML slideshow. The conversion uses Reveal.js in the background. To serve the slides by an HTTP server, add --postserve on the command-line. To make slides that does not require an internet connection, just place the Reveal.js library in the same directory where your_talk.slides.html is located.
jupyter nbconvert myslides.ipynb --to slides --post serve
The markdown option converts notebook to simple markdown output. Markdown cells are unaffected, and code cells indented 4 spaces.
--to markdown
You can use rst option to convert notebook to Basic reStructuredText output. It is useful as a starting point for embedding notebooks in Sphinx docs.
--to rst
This is the simplest way to get a Python (or other language, depending on the kernel) script out of a notebook.
--to script
22 Lectures
49 mins
Bigdata Engineer
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3041,
"s": 2660,
"text": "Jupyter notebook files have .ipynb extension. Notebook is rendered in web browser by the notebook app. It can be exported to various file formats by using download as an option in the file menu. Jupyter also has a command line interface in the form of n... |
Functions in C programming | A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions.
You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division is such that each function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.
The C standard library provides numerous built-in functions that your program can call. For example, strcat() to concatenate two strings, memcpy() to copy one memory location to another location, and many more functions.
A function can also be referred as a method or a sub-routine or a procedure, etc.
The general form of a function definition in C programming language is as follows –
return_type function_name( parameter list ) {
body of the function
}
A function definition in C programming consists of a function header and a function body. Here are all the parts of a function −
Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.
Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.
Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature.
Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature.
Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.
Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.
Function Body − The function body contains a collection of statements that define what the function does.
Function Body − The function body contains a collection of statements that define what the function does.
/* function returning the max between two numbers */
int max(int num1, int num2) {
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately.
A function declaration has the following parts −
return_type function_name( parameter list );
For the above defined function max(), the function declaration is as follows −
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so the following is also a valid declaration −
int max(int, int);
While creating a C function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task.
When a program calls a function, the program control is transferred to the called function. A called function performs a defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns the program control back to the main program.
To call a function, you simply need to pass the required parameters along with the function name, and if the function returns a value, then you can store the returned value. For example −
Live Demo
#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
int main () {
/* local variable definition */
int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
ret = max(a, b);
printf( "Max value is : %d\n", ret );
return 0;
}
/* function returning the max between two numbers */
int max(int num1, int num2) {
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Max value is : 200 | [
{
"code": null,
"e": 1255,
"s": 1062,
"text": "A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions."
},
{
"code": null,
"e": 1456,
"s": 1255,
... |
Sort an array of string of dates in ascending order - GeeksforGeeks | 03 Nov, 2021
Given an array of strings dates[], the task is to sort these dates in ascending order. Note: Each date is of the form dd mmm yyyy where:
Domain of dd is [0-31].
Domain of mmm is [Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec].
And, yyyy is a four digit integer.
Examples:
Input: dates[] = {“01 Mar 2015”, “11 Apr 1996”, “22 Oct 2007”} Output: 11 Apr 1996 22 Oct 2007 01 Mar 2015Input: dates[] = {“03 Jan 2018”, “02 Jan 2018”, “04 Jan 2017”} Output: 04 Jan 2017 02 Jan 2018 03 Jan 2018
Approach: Extract the days, months and years as sub-strings from the string then compare two strings by years, if years for two dates are equal then compare their months. If months are also equal than the days will decide which date appears earlier in the calendar.Below is the implementation of the above approach:
CPP
Python3
// C++ program to sort the dates in a string array#include <bits/stdc++.h>using namespace std; // Map to store the numeric value of each month depending on// its occurrence i.e. Jan = 1, Feb = 2 and so on.unordered_map<string, int> monthsMap; // Function which initializes the monthsMapvoid sort_months(){ monthsMap["Jan"] = 1; monthsMap["Feb"] = 2; monthsMap["Mar"] = 3; monthsMap["Apr"] = 4; monthsMap["May"] = 5; monthsMap["Jun"] = 6; monthsMap["Jul"] = 7; monthsMap["Aug"] = 8; monthsMap["Sep"] = 9; monthsMap["Oct"] = 10; monthsMap["Nov"] = 11; monthsMap["Dec"] = 12;} // Comparator function to sort an array of datesbool comp(string a, string b){ // Comparing the years string str1 = a.substr(7, 5); string str2 = b.substr(7, 5); if (str1.compare(str2) != 0) { if (str1.compare(str2) < 0) return true; return false; } // Comparing the months string month_sub_a = a.substr(3, 3); string month_sub_b = b.substr(3, 3); // Taking numeric value of months from monthsMap int month_a = monthsMap[month_sub_a]; int month_b = monthsMap[month_sub_b]; if (month_a != month_b) { return month_a < month_b; } // Comparing the days string day_a = a.substr(0, 2); string day_b = b.substr(0, 2); if (day_a.compare(day_b) < 0) return true; return false;} // Utility function to print the contents// of the arrayvoid printDates(string dates[], int n){ for (int i = 0; i < n; i++) { cout << dates[i] << endl; }} // Driver codeint main(){ string dates[] = { "24 Jul 2017", "25 Jul 2017", "11 Jun 1996", "01 Jan 2019", "12 Aug 2005", "01 Jan 1997" }; int n = sizeof(dates) / sizeof(dates[0]); // Order the months sort_months(); // Sort the dates sort(dates, dates + n, comp); // Print the sorted dates printDates(dates, n);}
# Python3 program to sort the dates in a string array # Map to store the numeric value of each month depending on# its occurrence i.e. Jan = 1, Feb = 2 and so on.monthsMap=dict() # Function which initializes the monthsMapdef sort_months(): monthsMap["Jan"] = 1 monthsMap["Feb"] = 2 monthsMap["Mar"] = 3 monthsMap["Apr"] = 4 monthsMap["May"] = 5 monthsMap["Jun"] = 6 monthsMap["Jul"] = 7 monthsMap["Aug"] = 8 monthsMap["Sep"] = 9 monthsMap["Oct"] = 10 monthsMap["Nov"] = 11 monthsMap["Dec"] = 12 def cmp(date): date=date.split() return int(date[2]),monthsMap[date[1]],int(date[0]), # Utility function to print the contents# of the arraydef printDates(dates, n): for i in range(n): print(dates[i]) # Driver codeif __name__ == '__main__': dates = [ "24 Jul 2017", "25 Jul 2017", "11 Jun 1996", "01 Jan 2019", "12 Aug 2005", "01 Jan 1997" ] n = len(dates) # Order the months sort_months() # Sort the dates dates.sort(key=cmp) # Print the sorted dates printDates(dates, n) # This code is contributed by Amartya Ghosh
11 Jun 1996
01 Jan 1997
12 Aug 2005
24 Jul 2017
25 Jul 2017
01 Jan 2019
Time Complexity: O(N * log(N)) Auxiliary Space: O(1)
pankajsharmagfg
amartyaghoshgfg
Sorting Quiz
Arrays
C++ Programs
Data Structures
Sorting
Data Structures
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Maximum and minimum of an array using minimum number of comparisons
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": 24202,
"s": 24174,
"text": "\n03 Nov, 2021"
},
{
"code": null,
"e": 24341,
"s": 24202,
"text": "Given an array of strings dates[], the task is to sort these dates in ascending order. Note: Each date is of the form dd mmm yyyy where: "
},
{
"code": nu... |
HTML | Marquee height attribute - GeeksforGeeks | 14 Feb, 2022
The Marquee height attribute in HTML is used to set the height of marquee in pixels or percentage value.Syntax:
<marquee height="px/%" >
Attribute value:
px: Define the height value of marquee.
%: Define the height value of marquee.
Note : The <marquee> height attribute is not supported by HTML5.
Example:
html
<!DOCTYPE html><html> <head> <title>HTML | Marquee height attribute</title> <style> .main { text-align: center; } </style></head> <body> <h1 style="color:green; text-align:center;"> GeeksforGeeks </h1> <div class="main"> <marquee height=25px bgcolor="Green" direction="left" loop=""> Left </marquee> <marquee height=50px bgcolor="Green" direction="right" loop=""> Right </marquee> </div></body> </html>
Output:
Supported Browsers: The browsers supported by HTML Marquee height attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
hritikbhatnagar2182
ManasChhabra2
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
REST API (Introduction)
Design a web page using HTML and CSS
Angular File Upload
Form validation using jQuery
How to auto-resize an image to fit a div container using CSS?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Top 10 Angular Libraries For Web Developers | [
{
"code": null,
"e": 24814,
"s": 24786,
"text": "\n14 Feb, 2022"
},
{
"code": null,
"e": 24928,
"s": 24814,
"text": "The Marquee height attribute in HTML is used to set the height of marquee in pixels or percentage value.Syntax: "
},
{
"code": null,
"e": 24953,
"... |
SymPy - Matrices | In Mathematics, a matrix is a two dimensional array of numbers, symbols or expressions. Theory of matrix manipulation deals with performing arithmetic operations on matrix objects, subject to certain rules.
Linear transformation is one of the important applications of matrices. Many scientific fields, specially related to Physics use matrix related applications.
SymPy package has matrices module that deals with matrix handling. It includes Matrix class whose object represents a matrix.
Note: If you want to execute all the snippets in this chapter individually, you need to import the matrix module as shown below −
>>> from sympy.matrices import Matrix
Example
>>> from sympy.matrices import Matrix
>>> m=Matrix([[1,2,3],[2,3,1]])
>>> m
$\displaystyle \left[\begin{matrix}1 & 2 & 3\\2 & 3 & 1\end{matrix}\right]$
On executing the above command in python shell, following output will be generated −
[1 2 3 2 3 1]
Matrix is created from appropriately sized List objects. You can also obtain a matrix by distributing list items in specified number of rows and columns.
>>> M=Matrix(2,3,[10,40,30,2,6,9])
>>> M
$\displaystyle \left[\begin{matrix}10 & 40 & 30\\2 & 6 & 9\end{matrix}\right]$
On executing the above command in python shell, following output will be generated −
[10 40 30 2 6 9]
Matrix is a mutable object. The matrices module also provides ImmutableMatrix class for obtaining immutable matrix.
The shape property of Matrix object returns its size.
>>> M.shape
The output for the above code is as follows −
(2,3)
The row() and col() method respectively returns row or column of specified number.
>>> M.row(0)
$\displaystyle \left[\begin{matrix}10 & 40 & 30\end{matrix}\right]$
The output for the above code is as follows −
[10 40 30]
>>> M.col(1)
$\displaystyle \left[\begin{matrix}40\\6\end{matrix}\right]$
The output for the above code is as follows −
[40 6]
Use Python's slice operator to fetch one or more items belonging to row or column.
>>> M.row(1)[1:3]
[6, 9]
Matrix class has row_del() and col_del() methods that deletes specified row/column from given matrix −
>>> M=Matrix(2,3,[10,40,30,2,6,9])
>>> M.col_del(1)
>>> M
On executing the above command in python shell, following output will be generated −
Matrix([[10, 30],[ 2, 9]])
You can apply style to the output using the following command −
$\displaystyle \left[\begin{matrix}10 & 30\\2 & 9\end{matrix}\right]$
You get the following output after executing the above code snippet −
[10 30 2 9]
>>> M.row_del(0)
>>> M
$\displaystyle \left[\begin{matrix}2 & 9\end{matrix}\right]$
You get the following output after executing the above code snippet −
[2 9]
Similarly, row_insert() and col_insert() methods add rows or columns at specified row or column index
>>> M1=Matrix([[10,30]])
>>> M=M.row_insert(0,M1)
>>> M
$\displaystyle \left[\begin{matrix}10 & 30\\2 & 9\end{matrix}\right]$
You get the following output after executing the above code snippet −
[10 40 30 2 9]
>>> M2=Matrix([40,6])
>>> M=M.col_insert(1,M2)
>>> M
$\displaystyle \left[\begin{matrix}10 & 40 & 30\\2 & 6 & 9\end{matrix}\right]$
You get the following output after executing the above code snippet −
[10 40 30 6 9]
Usual operators +, - and * are defined for performing addition, subtraction and multiplication.
>>> M1=Matrix([[1,2,3],[3,2,1]])
>>> M2=Matrix([[4,5,6],[6,5,4]])
>>> M1+M2
$\displaystyle \left[\begin{matrix}5 & 7 & 9\\9 & 7 & 5\end{matrix}\right]$
You get the following output after executing the above code snippet −
[5 7 9 9 7 5]
>>> M1-M2
$\displaystyle \left[\begin{matrix}-3 & -3 & -3\\-3 & -3 & -3\end{matrix}\right]$
You get the following output after executing the above code snippet −
[- 3 -3 -3 -3 -3 -3]
Matrix multiplication is possible only if - The number of columns of the 1st matrix must equal the number of rows of the 2nd matrix. - And the result will have the same number of rows as the 1st matrix, and the same number of columns as the 2nd matrix.
>>> M1=Matrix([[1,2,3],[3,2,1]])
>>> M2=Matrix([[4,5],[6,6],[5,4]])
>>> M1*M2
$\displaystyle \left[\begin{matrix}31 & 29\\29 & 31\end{matrix}\right]$
The output for the above code is as follows −
[31 29 29 31]
>>> M1.T
$\displaystyle \left[\begin{matrix}1 & 3\\2 & 2\\3 & 1\end{matrix}\right]$
The following output is obtained after executing the code −
[1 3 2 2 3 1]
To calculate a determinant of matrix, use det() method. A determinant is a scalar value that can be computed from the elements of a square matrix.0
>>> M=Matrix(3,3,[10,20,30,5,8,12,9,6,15])
>>> M
$\displaystyle \left[\begin{matrix}10 & 20 & 30\\5 & 8 & 12\\9 & 6 & 15\end{matrix}\right]$
The output for the above code is as follows −
[10 20 30 5 8 12 9 6 15]
>>> M.det()
The output for the above code is as follows −
-120
SymPy provides many special type of matrix classes. For example, Identity matrix, matrix of all zeroes and ones, etc. These classes are named as eye, zeros and ones respectively. Identity matrix is a square matrix with elements falling on diagonal are set to 1, rest of the elements are 0.
Example
from sympy.matrices import eye eye(3)
Output
Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
$\displaystyle \left[\begin{matrix}1 & 0 & 0\\0 & 1 & 0\\0 & 0 & 1\end{matrix}\right]$
The output for the above code is as follows −
[1 0 0 0 1 0 0 0 1]
In diag matrix, elements on diagonal are initialized as per arguments provided.
>>> from sympy.matrices import diag
>>> diag(1,2,3)
$\displaystyle \left[\begin{matrix}1 & 0 & 0\\0 & 2 & 0\\0 & 0 & 3\end{matrix}\right]$
The output for the above code is as follows −
[1 0 0 0 2 0 0 0 3]
All elements in zeros matrix are initialized to 0.
>>> from sympy.matrices import zeros
>>> zeros(2,3)
$\displaystyle \left[\begin{matrix}0 & 0 & 0\\0 & 0 & 0\end{matrix}\right]$
The output for the above code is as follows −
[0 0 0 0 0 0]
Similarly, ones is matrix with all elements set to 1.
>>> from sympy.matrices import ones
>>> ones(2,3)
$\displaystyle \left[\begin{matrix}1 & 1 & 1\\1 & 1 & 1\end{matrix}\right]$
The output for the above code is as follows −
[1 1 1 1 1 1]
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2226,
"s": 2019,
"text": "In Mathematics, a matrix is a two dimensional array of numbers, symbols or expressions. Theory of matrix manipulation deals with performing arithmetic operations on matrix objects, subject to certain rules."
},
{
"code": null,
"e": 2384,
... |
Difference between process.stdout.write and console.log in Node.js - GeeksforGeeks | 07 Oct, 2021
Both process.stdout.write and console.log in NodeJS have basic functionality to display messages on the console. Basically console.log implement process.stdout.write while process.stdout.write is a buffer/stream that will directly output in our console.
Difference between process.stdout.write and console.log in Node.js are:
We can not write more than one string. For example:process.stdout.write("Hello","World");Output: This will give a type error.
We can write more than one string. For example:console.log("Hello", "World");Output: This will print Hello World in the console.
We can not make associations. For example:process.stdout.write("Hello %s", "All");Output: This will give a type error.
We can make associations. For example:console.log("Hello %s", "All");Output: This will print Hello All in the console.
Example: Below example is to show to use of process.stdout.write
Javascript
<script> // For process.std.out process.stdout.write("Hello"); process.stdout.write("World"); process.stdout.write("!!!");</script>
Output:
HelloWorld!!!
Example: Below example is to show to use of console.log
Javascript
<script> // For console.log console.log("Hello"); console.log("World"); console.log("!!!");</script>
Output:
Hello
World
!!!
Node.js-Basics
Picked
Technical Scripter 2020
Node.js
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to build a basic CRUD app with Node.js and ReactJS ?
How to connect Node.js with React.js ?
Mongoose Populate() Method
Express.js req.params Property
How to Convert CSV to JSON file having Comma Separated values in Node.js ?
Node.js Export Module
JWT Authentication with Node.js
Mongoose find() Function
How to Install a local module using npm?
Difference between dependencies, devDependencies and peerDependencies | [
{
"code": null,
"e": 24531,
"s": 24503,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 24785,
"s": 24531,
"text": "Both process.stdout.write and console.log in NodeJS have basic functionality to display messages on the console. Basically console.log implement process.stdout.wri... |
Vim - Registers | Vim provides many registers. We can use these registers as multiple clipboards. This feature is really useful while working with multiple files. In this chapter, we will discuss following items −
Copy text in register
Paste text from register
List available registers
Register types
For copying, we can use normal yank command i.e. yy and to store it in register we can use following syntax −
“<register-name><command>
For instance, to copy text in register “a” use following command −
“ayy
To paste text from register use −
“<register-name>p
For instance, below command copies text from register “a” −
“ap
To list all available registers use following command
:registers
Vim supports following types of registers −
Unnamed register is denoted by “”. Vim stores deleted or copied text in this register
We can use 26 named registers; we can use a-z or A-Z. By default vim doesn’t uses these registers.
If we use lower case register name then contents will be overwritten and if we use uppercase name then contents will be appended in that register.
We can use 0 to 9 named registers. Vim fills these registers with text from yank and delete command.
Numbered register 0 contains the text from the most recent yank command.
Numbered register 1 contains the text deleted by the most recent delete or change command
Following are the default registers −
Name of the current file
Name of the alternate file for the current window
Most recently executed command
Contains the last inserted text
Last used register
46 Lectures
5.5 hours
Jason Cannon
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2166,
"s": 1970,
"text": "Vim provides many registers. We can use these registers as multiple clipboards. This feature is really useful while working with multiple files. In this chapter, we will discuss following items −"
},
{
"code": null,
"e": 2188,
"s": 2166,... |
How to Create Image Lightbox Gallery using HTML CSS and JavaScript ? - GeeksforGeeks | 15 Dec, 2021
A lightbox gallery is basically used to view the gallery images in detail specifically. You can code the JavaScript to do so but also we can use some downloaded JS and CSS. In this article, we will download the lightbox and attach the JS and CSS files into our code. For our own design satisfaction, we can also use the CSS code as we want. We will divide the task into three sections. In the first section, we will create the structure in the second section we sill add som CSS for our own purpose. In the last section, we will link the downloaded JS snd CSS files.We have to download the lightbox, we can download that from the link: https://github.com/lokesh/lightbox2/releases
Creating Structure: In this section, we will code only in HTML to create a normal HTML gallery.
HTML Code:
HTML
<!DOCTYPE html><html> <head> <title>Lightbox Gallery</title></head> <body> <h2>GeeksforGeeks</h2> <b>A Computer Science Portal for Geeks</b> <div class="gallery"> <a href="https://media.geeksforgeeks.org/wp-content/uploads/20200318142254/html9.png"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200318143104/html10.png"> </a> <a href="https://media.geeksforgeeks.org/wp-content/uploads/20200318142245/CSS8.png"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200318143101/CSS9.png"> </a> <a href="https://media.geeksforgeeks.org/wp-content/uploads/20200318142240/Bootstrap5.png"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200318143058/Bootstrap6.png"> </a> <a href="https://media.geeksforgeeks.org/wp-content/uploads/20200318142257/JavaScript2.png"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200318143106/JavaScript3.png"> </a> <a href="https://media.geeksforgeeks.org/wp-content/uploads/20200318142303/jquery.png"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200318143108/jquery4.png"> </a> <a href="https://media.geeksforgeeks.org/wp-content/uploads/20200318142309/php7.png"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200318143112/php8.png"> </a> </div></body> </html>
Design Structure: In this section, we will add some CSS property to make image gallery attractive.
CSS Code:
CSS
<style> body { text-align: center; } h2 { color: green; } .gallery { margin: 10px 40px; } .gallery img { width: 200px; height: 50px; transition: 1s; padding: 5px; } .gallery img:hover { filter: drop-shadow(4px 4px 6px gray); transform: scale(1.1); }</style>
Final Solution: In this section you have to link the downloaded CSS and JS file into your code. You can simply link the downloaded file by unzipping the file. For the CSS file, use the <link> tag with href attribute for the address of CSS and for JS file use the <script> tag with src attribute for the code. At last we have to put data-lightbox=”mygallery” attribute inside the <a> tag. Next and previous button will automatically attached during JS file attachment.
Final Code:
HTML
<!DOCTYPE html><html> <head> <title>Lightbox Gallery</title> <link rel="stylesheet" type="text/css" href="lightbox2/dist/css/lightbox.min.css"> <script src="lightbox2/dist/js/lightbox-plus-jquery.min.js"> </script> <style> body { text-align: center; } h2 { color: green; } .gallery { margin: 10px 40px; } .gallery img { width: 200px; height: 50px; transition: 1s; padding: 5px; } .gallery img:hover { filter: drop-shadow(4px 4px 6px gray); transform: scale(1.1); } </style></head> <body> <h2>GeeksforGeeks</h2> <b>A Computer Science Portal for Geeks</b> <div class="gallery"> <a href="https://media.geeksforgeeks.org/wp-content/uploads/20200318142254/html9.png" data-lightbox="mygallery"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200318143104/html10.png"> </a> <a href="https://media.geeksforgeeks.org/wp-content/uploads/20200318142245/CSS8.png" data-lightbox="mygallery"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200318143101/CSS9.png"> </a> <a href="https://media.geeksforgeeks.org/wp-content/uploads/20200318142240/Bootstrap5.png" data-lightbox="mygallery"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200318143058/Bootstrap6.png"> </a> <a href="https://media.geeksforgeeks.org/wp-content/uploads/20200318142257/JavaScript2.png" data-lightbox="mygallery"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200318143106/JavaScript3.png"> </a> <a href="https://media.geeksforgeeks.org/wp-content/uploads/20200318142303/jquery.png" data-lightbox="mygallery"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200318143108/jquery4.png"> </a> <a href="https://media.geeksforgeeks.org/wp-content/uploads/20200318142309/php7.png" data-lightbox="mygallery"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200318143112/php8.png"> </a> </div></body> </html>
Output:
sumitgumber28
sweetyty
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property | [
{
"code": null,
"e": 39276,
"s": 39248,
"text": "\n15 Dec, 2021"
},
{
"code": null,
"e": 39957,
"s": 39276,
"text": "A lightbox gallery is basically used to view the gallery images in detail specifically. You can code the JavaScript to do so but also we can use some downloaded JS... |
Java JDBC - Update a Column in a Table - GeeksforGeeks | 08 Dec, 2020
Java has its own API which JDBC API which uses JDBC drivers for database connections. JDBC API provides the applications-to-JDBC connection and JDBC driver provides a manager-to-driver connection. Following are the 5 important steps to connect java application to our database using JDBC.
Registering the Java class
Creating a Connection
Creating a Statement
Executing queries
Closing connection
Note: Load mysqlconnector.jar into your program.
Steps:
Download MySQLConnect/J (JDBC connector jar file) from the following link https://dev.mysql.com/downloads/connector/j
Select platform-independent in select OS option
Copy mysql-connector-java-5.1.34-bin.jar file in your project
Right-click on it , select Build Path-> Configure Build path -> libraries -> Add JARS
In JAR selection window, select mysql-connector-java-5.1.34-bin.jar library under your project
Click OK
Create a Database, add a table with records using MySQL cmd.
Java
// Update a Column in a Table // dont forget to import below packageimport java.sql.*; public class Database { // url that points to mysql database, 'db' is database // name static final String url = "jdbc:mysql://localhost:3306/db"; public static void main(String[] args) throws ClassNotFoundException { try { // this Class.forName() method is user for // driver registration with name of the driver // as argument i have used MySQL driver Class.forName("com.mysql.jdbc.Driver"); // getConnection() establishes a connection. It // takes url that points to your database, // username and password of MySQL connections as // arguments Connection conn = DriverManager.getConnection( url, "root", "1234"); // create.Statement() creates statement object // which is responsible for executing queries on // table Statement stmt = conn.createStatement(); // Executing the query, student is the table // name and RollNo is the new column String query = "ALTER TABLE student RENAME COLUMN roll_no TO RollNo"; // executeUpdate() is used for INSERT, UPDATE, // DELETE statements.It returns number of rows // affected by the execution of the statement int result = stmt.executeUpdate(query); // if result is greater than 0, it means values // has been added if (result > 0) System.out.println( "table successfully updated."); else System.out.println("unable to update"); // closing connection conn.close(); } catch (SQLException e) { System.out.println(e); } }}
JDBC
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Exceptions in Java
StringBuilder Class in Java with Examples
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
How to Iterate HashMap in Java? | [
{
"code": null,
"e": 23892,
"s": 23864,
"text": "\n08 Dec, 2020"
},
{
"code": null,
"e": 24181,
"s": 23892,
"text": "Java has its own API which JDBC API which uses JDBC drivers for database connections. JDBC API provides the applications-to-JDBC connection and JDBC driver provide... |
How to group an array of objects by key in JavaScript | Suppose, we have an array of objects containing data about some cars like this −
const arr = [
{
'make': 'audi',
'model': 'r8',
'year': '2012'
}, {
'make': 'audi',
'model': 'rs5',
'year': '2013'
}, {
'make': 'ford',
'model': 'mustang',
'year': '2012'
}, {
'make': 'ford',
'model': 'fusion',
'year': '2015'
}, {
'make': 'kia',
'model': 'optima',
'year': '2012'
},
];
We are required to write a JavaScript function that takes in one such array of objects. The function should then group the objects together based on their 'make' property.
Therefore, the output should look something like this −
const output = {
'audi': [
{
'model': 'r8',
'year': '2012'
}, {
'model': 'rs5',
'year': '2013'
},
],
'ford': [
{
'model': 'mustang',
'year': '2012'
}, {
'model': 'fusion',
'year': '2015'
}
],
'kia': [
{
'model': 'optima',
'year': '2012'
}
]
};
The code for this will be −
const arr = [
{
'make': 'audi',
'model': 'r8',
'year': '2012'
}, {
'make': 'audi',
'model': 'rs5',
'year': '2013'
}, {
'make': 'ford',
'model': 'mustang',
'year': '2012'
}, {
'make': 'ford',
'model': 'fusion',
'year': '2015'
}, {
'make': 'kia',
'model': 'optima',
'year': '2012'
},
];
const groupByMake = (arr = []) => {
let result = [];
result = arr.reduce((r, a) => {
r[a.make] = r[a.make] || [];
r[a.make].push(a);
return r;
}, Object.create(null));
return result;
};
console.log(groupByMake(arr));
And the output in the console will be −
{
audi: [
{ make: 'audi', model: 'r8', year: '2012' },
{ make: 'audi', model: 'rs5', year: '2013' }
],
ford: [
{ make: 'ford', model: 'mustang', year: '2012' },
{ make: 'ford', model: 'fusion', year: '2015' }
],
kia: [ { make: 'kia', model: 'optima', year: '2012' } ]
} | [
{
"code": null,
"e": 1143,
"s": 1062,
"text": "Suppose, we have an array of objects containing data about some cars like this −"
},
{
"code": null,
"e": 1536,
"s": 1143,
"text": "const arr = [\n {\n 'make': 'audi',\n 'model': 'r8',\n 'year': '2012'\n }, {\n ... |
How to make an Android device vibrate programmatically using Kotlin? | This example demonstrates how to make an Android device vibrate programmatically using Kotlin.
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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:background="#008080"
android:padding="5dp"
android:text="TutorialsPoint"
android:textColor="#fff"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="@android:color/holo_blue_dark"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.os.VibrationEffect
import android.os.Vibrator
import androidx.appcompat.app.AppCompatActivity
@Suppress("DEPRECATION")
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
val v = (getSystemService(Context.VIBRATOR_SERVICE) as Vibrator)
// Vibrate for 500 milliseconds
// Vibrate for 500 milliseconds
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
v.vibrate(VibrationEffect.createOneShot(500,
VibrationEffect.DEFAULT_AMPLITUDE))
}
else {
v.vibrate(500)
}
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.q11">
<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 the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.
TRY THIS IS ON OWN DEVICE FOR BETTER RESULTS | [
{
"code": null,
"e": 1157,
"s": 1062,
"text": "This example demonstrates how to make an Android device vibrate programmatically using Kotlin."
},
{
"code": null,
"e": 1286,
"s": 1157,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all ... |
Check if element is present in tuple of tuples in Python | Python Tuples can be nested. We can have a tuple whose elements are also tuples. In this article we will see how to find out if a given value is present as an element in a tuple of tuples.
The any function can be used to check if a given value is present as an element in any of the subtuples that are present in the tuple with help of for loop. We put the entire condition for checking in an if and else clause.
Live Demo
Atuple = [('Mon',10),('Tue',8),('Wed',8),('Thu',5)]
#Given tuple
print("Given tuple: ",Atuple)
# Use any
if any('Tue' in i for i in Atuple):
print("present")
else :
print("Not present")
if any(3 in i for i in Atuple):
print("present")
else :
print("Not present")
Running the above code gives us the following result −
Given tuple: [('Mon', 10), ('Tue', 8), ('Wed', 8), ('Thu', 5)]
present
Not present
The chain function in itertools module returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. So we use it with the given tuple expanding all its content and checking for the presence of the required value using the if clause.
Live Demo
import itertools
Atuple = (('Mon',10),('Tue',8),('Wed',8),('Thu',5))
#Given tuple
print("Given tuple: ",Atuple)
# Use chain
if ('Wed' in itertools.chain(*Atuple)) :
print("Wed is present")
else :
print("Wed is not present")
if (11 in itertools.chain(*Atuple)) :
print("11 is present")
else :
print("11 is not present")
Running the above code gives us the following result −
Given tuple: (('Mon', 10), ('Tue', 8), ('Wed', 8), ('Thu', 5))
Wed is present
11 is not present | [
{
"code": null,
"e": 1251,
"s": 1062,
"text": "Python Tuples can be nested. We can have a tuple whose elements are also tuples. In this article we will see how to find out if a given value is present as an element in a tuple of tuples."
},
{
"code": null,
"e": 1475,
"s": 1251,
"t... |
Next higher number with same number of set bits - GeeksforGeeks | 29 Oct, 2021
Given a number x, find next number with same number of 1 bits in it’s binary representation.For example, consider x = 12, whose binary representation is 1100 (excluding leading zeros on 32 bit machine). It contains two logic 1 bits. The next higher number with two logic 1 bits is 17 (100012).Algorithm:When we observe the binary sequence from 0 to 2n – 1 (n is # of bits), right most bits (least significant) vary rapidly than left most bits. The idea is to find right most string of 1’s in x, and shift the pattern to right extreme, except the left most bit in the pattern. Shift the left most bit in the pattern (omitted bit) to left part of x by one position. An example makes it more clear,
x = 156
10
x = 10011100
(2)
10011100
00011100 - right most string of 1's in x
00000011 - right shifted pattern except left most bit ------> [A]
00010000 - isolated left most bit of right most 1's pattern
00100000 - shiftleft-ed the isolated bit by one position ------> [B]
10000000 - left part of x, excluding right most 1's pattern ------> [C]
10100000 - add B and C (OR operation) ------> [D]
10100011 - add A and D which is required number 163
(10)After practicing with few examples, it easy to understand. Use the below given program for generating more sets.Program Design:We need to note few facts of binary numbers. The expression x & -x will isolate right most set bit in x (ensuring x will use 2’s complement form for negative numbers). If we add the result to x, right most string of 1’s in x will be reset, and the immediate ‘0’ left to this pattern of 1’s will be set, which is part [B] of above explanation. For example if x = 156, x & -x will result in 00000100, adding this result to x yields 10100000 (see part D). We left with the right shifting part of pattern of 1’s (part A of above explanation).There are different ways to achieve part A. Right shifting is essentially a division operation. What should be our divisor? Clearly, it should be multiple of 2 (avoids 0.5 error in right shifting), and it should shift the right most 1’s pattern to right extreme. The expression (x & -x) will serve the purpose of divisor. An EX-OR operation between the number X and expression which is used to reset right most bits, will isolate the rightmost 1’s pattern.A Correction Factor:Note that we are adding right most set bit to the bit pattern. The addition operation causes a shift in the bit positions. The weight of binary system is 2, one shift causes an increase by a factor of 2. Since the increased number (rightOnesPattern in the code) being used twice, the error propagates twice. The error needs to be corrected. A right shift by 2 positions will correct the result.The popular name for this program is same number of one bits.
C++
Java
Python 3
C#
PHP
Javascript
#include<iostream> using namespace std; typedef unsigned int uint_t; // this function returns next higher number with same number of set bits as x.uint_t snoob(uint_t x){ uint_t rightOne; uint_t nextHigherOneBit; uint_t rightOnesPattern; uint_t next = 0; if(x) { // right most set bit rightOne = x & -(signed)x; // reset the pattern and set next higher bit // left part of x will be here nextHigherOneBit = x + rightOne; // nextHigherOneBit is now part [D] of the above explanation. // isolate the pattern rightOnesPattern = x ^ nextHigherOneBit; // right adjust pattern rightOnesPattern = (rightOnesPattern)/rightOne; // correction factor rightOnesPattern >>= 2; // rightOnesPattern is now part [A] of the above explanation. // integrate new pattern (Add [D] and [A]) next = nextHigherOneBit | rightOnesPattern; } return next;} int main(){ int x = 156; cout<<"Next higher number with same number of set bits is "<<snoob(x); getchar(); return 0;}
// Java Implementation on above approachclass GFG{ // this function returns next higher// number with same number of set bits as x.static int snoob(int x){ int rightOne, nextHigherOneBit, rightOnesPattern, next = 0; if(x > 0){ // right most set bit rightOne = x & -x; // reset the pattern and set next higher bit // left part of x will be here nextHigherOneBit = x + rightOne; // nextHigherOneBit is now part [D] of the above explanation. // isolate the pattern rightOnesPattern = x ^ nextHigherOneBit; // right adjust pattern rightOnesPattern = (rightOnesPattern)/rightOne; // correction factor rightOnesPattern >>= 2; // rightOnesPattern is now part [A] of the above explanation. // integrate new pattern (Add [D] and [A]) next = nextHigherOneBit | rightOnesPattern;} return next;} // Driver codepublic static void main (String[] args){ int x = 156; System.out.println("Next higher number with same" + "number of set bits is "+snoob(x));}} // This code is contributed by mits
# This function returns next# higher number with same# number of set bits as x.def snoob(x): next = 0 if(x): # right most set bit rightOne = x & -(x) # reset the pattern and # set next higher bit # left part of x will # be here nextHigherOneBit = x + int(rightOne) # nextHigherOneBit is # now part [D] of the # above explanation. # isolate the pattern rightOnesPattern = x ^ int(nextHigherOneBit) # right adjust pattern rightOnesPattern = (int(rightOnesPattern) / int(rightOne)) # correction factor rightOnesPattern = int(rightOnesPattern) >> 2 # rightOnesPattern is now part # [A] of the above explanation. # integrate new pattern # (Add [D] and [A]) next = nextHigherOneBit | rightOnesPattern return next # Driver Codex = 156print("Next higher number with " + "same number of set bits is", snoob(x)) # This code is contributed by Smita
// C# Implementation on above approachusing System;class GFG{ // this function returns next higher// number with same number of set bits as x.static int snoob(int x){ int rightOne, nextHigherOneBit, rightOnesPattern, next = 0; if(x > 0) { // right most set bit rightOne = x & -x; // reset the pattern and set next higher bit // left part of x will be here nextHigherOneBit = x + rightOne; // nextHigherOneBit is now part [D] // of the above explanation. // isolate the pattern rightOnesPattern = x ^ nextHigherOneBit; // right adjust pattern rightOnesPattern = (rightOnesPattern) / rightOne; // correction factor rightOnesPattern >>= 2; // rightOnesPattern is now part [A] // of the above explanation. // integrate new pattern (Add [D] and [A]) next = nextHigherOneBit | rightOnesPattern; } return next;} // Driver codestatic void Main(){ int x = 156; Console.WriteLine("Next higher number with same" + "number of set bits is " + snoob(x));}} // This code is contributed by mits
<?php // This function returns next higher number// with same number of set bits as x.function snoob($x){ $next = 0; if($x) { // right most set bit $rightOne = $x & - $x; // reset the pattern and set next higher // bit left part of x will be here $nextHigherOneBit = $x + $rightOne; // nextHigherOneBit is now part [D] of // the above explanation. // isolate the pattern $rightOnesPattern = $x ^ $nextHigherOneBit; // right adjust pattern $rightOnesPattern = intval(($rightOnesPattern) / $rightOne); // correction factor $rightOnesPattern >>= 2; // rightOnesPattern is now part [A] // of the above explanation. // integrate new pattern (Add [D] and [A]) $next = $nextHigherOneBit | $rightOnesPattern; } return $next;} // Driver Code$x = 156;echo "Next higher number with same " . "number of set bits is " . snoob($x); // This code is contributed by ita_c?>
<script> // this function returns next higher // number with same number of set bits as x. function snoob(x) { let rightOne, nextHigherOneBit, rightOnesPattern, next = 0; if(x > 0) { // right most set bit rightOne = x & -x; // reset the pattern and set next higher bit // left part of x will be here nextHigherOneBit = x + rightOne; // nextHigherOneBit is now part [D] of the above explanation. // isolate the pattern rightOnesPattern = x ^ nextHigherOneBit; // right adjust pattern rightOnesPattern = (rightOnesPattern)/rightOne; // correction factor rightOnesPattern >>= 2; // rightOnesPattern is now part [A] of the above explanation. // integrate new pattern (Add [D] and [A]) next = nextHigherOneBit | rightOnesPattern; } return next; } // Driver code let x = 156; document.write("Next higher number with same " + "number of set bits is "+snoob(x)); // This code is contributed by avanitrachhadiya2155 </script>
Output:
Next higher number with same number of set bits is 163
Time Complexity: O(1)
Auxiliary Space: O(1)
Usage: Finding/Generating subsets.Variations:
Write a program to find a number immediately smaller than given, with same number of logic 1 bits? (Pretty simple)How to count or generate the subsets available in the given set?
Write a program to find a number immediately smaller than given, with same number of logic 1 bits? (Pretty simple)
How to count or generate the subsets available in the given set?
References:
A nice presentation here.Hackers Delight by Warren (An excellent and short book on various bit magic algorithms, a must for enthusiasts)C A Reference Manual by Harbison and Steele (A good book on standard C, you can access code part of this post here).
A nice presentation here.
Hackers Delight by Warren (An excellent and short book on various bit magic algorithms, a must for enthusiasts)
C A Reference Manual by Harbison and Steele (A good book on standard C, you can access code part of this post here).
– Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Smitha Dinesh Semwal
ukasp
Mithun Kumar
shubham_singh
avanitrachhadiya2155
souravmahato348
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Cyclic Redundancy Check and Modulo-2 Division
Count set bits in an integer
Little and Big Endian Mystery
How to swap two numbers without using a temporary variable?
Program to find whether a given number is power of 2
Binary representation of a given number
Bit Fields in C | [
{
"code": null,
"e": 34514,
"s": 34486,
"text": "\n29 Oct, 2021"
},
{
"code": null,
"e": 35212,
"s": 34514,
"text": "Given a number x, find next number with same number of 1 bits in it’s binary representation.For example, consider x = 12, whose binary representation is 1100 (excl... |
How to Sort CSV by a single column in Python ? | To sort CSV by a single column, use the sort_values() method. Set the column using which you want to sort in the sort_values() method.
At first, let’s read our CSV file “SalesRecords.csv”with DataFrame −
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv")
Sort according to a single column “Car” −
dataFrame.sort_values("Car", axis=0, ascending=True,inplace=True, na_position='first')
Next, sort according to a single column “Reg_Price” −
dataFrame.sort_values("Reg_Price", axis=0, ascending=True,inplace=True, na_position='first')
Following is the code
import pandas as pd
# DataFrame to read our input CS file
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv")
print("\nInput CSV file = \n", dataFrame)
# sorting according to Car column
dataFrame.sort_values("Car", axis=0, ascending=True,inplace=True, na_position='first')
print("\nSorted CSV file (according to Car Names) = \n", dataFrame)
# sorting according to Reg_Price column
dataFrame.sort_values("Reg_Price", axis=0, ascending=True,inplace=True, na_position='first')
print("\nSorted CSV file (according to Registration Price) = \n", dataFrame)
This will produce the following output
Input CSV file =
Car Date_of_Purchase Reg_Price
0 BMW 10/10/2020 1000
1 Audi 10/12/2020 750
2 Lexus 10/17/2020 1250
3 Jaguar 10/16/2020 1500
4 Mustang 10/19/2020 1100
5 Lamborghini 10/22/2020 1000
Sorted CSV file (according to Car Names) =
Car Date_of_Purchase Reg_Price
1 Audi 10/12/2020 750
0 BMW 10/10/2020 1000
3 Jaguar 10/16/2020 1500
5 Lamborghini 10/22/2020 1000
2 Lexus 10/17/2020 1250
4 Mustang 10/19/2020 1100
Sorted CSV file (according to Registration Price) =
Car Date_of_Purchase Reg_Price
1 Audi 10/12/2020 750
0 BMW 10/10/2020 1000
5 Lamborghini 10/22/2020 1000
4 Mustang 10/19/2020 1100
2 Lexus 10/17/2020 1250
3 Jaguar 10/16/2020 1500 | [
{
"code": null,
"e": 1197,
"s": 1062,
"text": "To sort CSV by a single column, use the sort_values() method. Set the column using which you want to sort in the sort_values() method."
},
{
"code": null,
"e": 1266,
"s": 1197,
"text": "At first, let’s read our CSV file “SalesRecords... |
Convert double primitive type to a Double object in Java | To convert double primitive type to a Double object, you need to use Double constructor.
Let’s say the following is our double primitive.
// double primitive
double val = 23.78;
To convert it to a Double object, use Double constructor.
// Double object
Double ob = new Double(val);
Live Demo
public class Demo {
public static void main(String args[]) {
// double primitive
double val = 23.78;
// Double object
Double ob = new Double(val);
System.out.println(ob);
}
}
23.78 | [
{
"code": null,
"e": 1151,
"s": 1062,
"text": "To convert double primitive type to a Double object, you need to use Double constructor."
},
{
"code": null,
"e": 1200,
"s": 1151,
"text": "Let’s say the following is our double primitive."
},
{
"code": null,
"e": 1240,
... |
AB Sample Size Calculation in R. Some useful tools in R for calculating... | by Frank Hopkins | Towards Data Science | Performing ad-hoc analysis for stakeholders can be time consuming. Furthermore, there are a few questions that I get asked on a reasonably frequent basis. So I have been spending some time developing some tools for my “non-technical” colleagues to use in R.
One of the most commonly asked questions is “How big of a sample do I need to achieve significance?”, which is often followed by “How long do I need to run my experiment for?”. For this reason, I have developed some simple code for people to use when they need to answer these questions. All the user needs to do is pass some baseline numbers into some functions I have created and they can determine their sample size requirements and experiment duration on an ad-hoc basis.
Luckily, by knowing a few simple pieces of information the pwr() package in R can answer these two questions with a fair amount of ease. Pwr() helps you perform power analysis prior to conducting an experiment, which enables you to determine how big your sample size should be per experimental condition.
The four quantities required to compute power analysis have an intimate relationship and we are able to compute any one of these values if we have the remaining inputs:
1. sample size (n)
2. effect size
3. significance level (alpha)= P(Type I error) = probability of finding an effect that is not there
4. power = 1 — P(Type II error) = probability of finding an effect that is there
As your significance level (3) and power (4) are typically fixed values, as long as you can input the effects sizes (2) for your control and variant, you can determine your required sample size (1).
Thankfully, the ES.h() function in the pwr() package computes our effect size for us to pass into power analyses. We will typically know the current conversion rate/performance of our control condition but the effect of the variant is almost by definition an unknown. However, we can calculate an expected effect size, given a desired uplift. Once these effects are computed they are passed into the pwr.p.test() function which will compute our sample size, providing n is left blank. To make this sort of analysis user friendly, I have wrapped both aforementioned functions into a new function called sample_size_calculator().
Furthermore, as we will use this information to then calculate the number of days needed to run the experiment, I have created a days_calculator() function too, which will use the output from our sample size calculation:
sample_size_calculator <- function(control, uplift){variant <- (uplift + 1) * controlbaseline <- ES.h(control, variant)sample_size_output <- pwr.p.test(h = baseline,n = ,sig.level = 0.05,power = 0.8)if(variant >= 0){return(sample_size_output)}else{paste("N/A")}}days_calculator <- function(sample_size_output, average_daily_traffic){days_required <- c(sample_size_output * 2)/(average_daily_traffic)if(days_required >= 0){paste("It will take this many days to reach significance with your current traffic:", round(days_required, digits = 0))}else{paste("N/A")}}
If you are using this tool, you simply specify your control conversion rate and desired uplift:
control <- 0.034567uplift <- 0.01
And run the sample_size_calculator() function:
sample_size_calculator(control, uplift)sample_size_output <- sample_size_output$nsample_size_output
You will then get your required sample size output given these values (remember this sample size requirement is per variant):
[n]230345
Now we have this information we can determine how long the experiment needs to run for. All that you will need to input is your average daily traffic:
average_daily_traffic <- 42000
Run the days_calculator() function:
days_calculator(sample_size_output, average_daily_traffic)
And you will get the following output:
[1] It will take this many days to reach significance with your current traffic: 36
Although this code is only relevant if you are conducting an experiment with an AB design (i.e with only two experimental conditions), the functions presented can be amended to calculate the required sample size given multiple experimental conditions, using the pwr.anova.test() function within sample_size_calculator(), replacing pwr.2p.test().
Power analysis is an imperative aspect of any experimental design. It allows analysts to determine the required sample size needed to detect a statistically significant effect of a given size, with a given degree of confidence. Conversely, it also facilitates the detection an effect of a given size with a given level of confidence, under sample-size constraints. If the probability is low, it could be advisable to alter the experimental design of your experiment or to minimise certain numerical values that are input into your power analyses.
Used in conjunction with one another, calculating both your required sample and experimentation duration can be incredibly useful information to provide to stakeholders. Obtaining this information can help them efficiently plan their experimentation road-maps. Furthermore, these predetermined numbers can aid in determining the feasibility of certain experiments or whether the uplifts desired are too idealistic. | [
{
"code": null,
"e": 429,
"s": 171,
"text": "Performing ad-hoc analysis for stakeholders can be time consuming. Furthermore, there are a few questions that I get asked on a reasonably frequent basis. So I have been spending some time developing some tools for my “non-technical” colleagues to use in ... |
Elias Delta Decoding in Python - GeeksforGeeks | 28 Nov, 2021
In this article, we are going to implement Elias Delta Decoding using python.
Peter Elias devised the Elias delta code, which is a universal system for encoding positive integers.
Syntax:
Elias Delta Encoding(X)= Elias Gamma encoding (1+floor(log2(X))) + Binary representation of X without MSB.
Import required libraries and read the encoded binary string from the user.
Read/Count the number of zero’s from the most significant bit until you see the first ‘1’ and store it in a variable named ‘L’
Syntax:
L=0
while True:
if not x[L] == '0':
break
L= L + 1
Consider that ‘L’ as 1st digit and read L more bits and drop all bits until current L bit.
Take out the remaining bits and prepend ‘1’ in the Most significant bit.
Syntax:
x.insert(0,’1′)
Convert the final binary into integer which gives us the original number.
Let the input encoded string is 01111
Step1: Read/Count the number of zeros from most significant bit until you see the first ‘1’ and store it in ‘L’ until you see the first ‘1’
In our case, L=1
Step2: Consider that ‘1’ as first digit read L more bits (1 more bit) and drop everything.
01111= 11
Step3: Takeout the remaining bits and prepend with ‘1’ in MSB.
111
Step4: Convert the final binary string into integer which gives us 7.
Below is the implementation.
Example 1: Example to produce Elias Delta Decoding value corresponding to some value.
Python3
import math def Elias_Delta_Decoding(x): x = list(x) L = 0 while True: if not x[L] == '0': break L = L + 1 # Reading L more bits and dropping ALL x = x[2*L+1:] # Prepending with 1 in MSB x.reverse() x.insert(0, '1') n = 0 # Converting binary to integer for i in range(len(x)): if x[i] == '1': n = n+math.pow(2, i) return int(n) x = '01111'print(Elias_Delta_Decoding(x))
Output:
7
Example 2: Example to produce Elias Delta Decoding value corresponding to some value.p
Python
import math def Elias_Delta_Decoding(x): x = list(x) L=0 while True: if not x[L] == '0': break L= L + 1 # Reading L more bits and dropping ALL x=x[2*L+1:] # Prepending with 1 in MSB x.insert(0,'1') x.reverse() n=0 # Converting binary to integer for i in range(len(x)): if x[i]=='1': n=n+math.pow(2,i) return int(n) x = '0111100'print(Elias_Delta_Decoding(x))
Output:
28
Picked
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python | [
{
"code": null,
"e": 23927,
"s": 23899,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 24005,
"s": 23927,
"text": "In this article, we are going to implement Elias Delta Decoding using python."
},
{
"code": null,
"e": 24107,
"s": 24005,
"text": "Peter Elias ... |
Creating Tables in SQL. Understanding the syntax is very simple... | by Jason Lee | Towards Data Science | Understanding the syntax is very simple in SQL. It follows an easy structure that allows us to reuse syntax for different variables. Here are some basic syntax for creating tables.
CREATE DATABASE database_name;
CREATE TABLE movies( movie_name VARCHAR(200), movie_year INTEGER, country VARCHAR(100), genre VARCHAR NOT NULL, PRIMARY KEY (movie_name, movie_year));
State column name, the type of the column and length within the parenthesis. You can state NOT NULL to make sure it is always filled.
INSERT INTO movies VALUES('SE7EN', 1995, 'USA', 'Mystic, Crime'),('INSTERSTELLAR', 2014, 'USA', 'Science Fiction'),('The Green Mile', 1999, 'USA', 'Drama'),('The Godfather', 1972, 'USA', 'CRIME')
If you enter a value which is not the correct type or if empty, and it is NOT NULL, SQL will throw an error.
If you forgot to add a value you can update it, with UPDATE.
UPDATE moviesSET country = 'USA'WHERE movie_name = 'The Godfather' AND movie_year = 1972;
You can update and set an item to a default.
ALTER TABLE moviesALTER COLUMN country SET DEFAULT 'USA';
Test the DEFAULT option. Now, whenever you reference DEFAULT you will get the USA.
INSERT INTO movies VALUES('test', 2010, DEFAULT, 'test')
ALTER TABLE moviesADD COLUMN director VARCHAR(150)
If you want to add a new value for any column you can use UPDATE.
UPDATE moviesSET director = 'Christopher Nolan'WHERE movie_name = 'Interstellar';
If you want to delete a row you can reference it by using WHERE.
DELETE FROM moviesWHERE movie_name = 'test'
ALTER TABLE moviesDROP director;
There is another way you can drop an item and it’s called DROP CASCADE.
DROP CASCADE → Drops the item selected and everything else that is dependent on it. For example, if we used DROP CASCADE on the entire movie's database everything will be deleted. | [
{
"code": null,
"e": 353,
"s": 172,
"text": "Understanding the syntax is very simple in SQL. It follows an easy structure that allows us to reuse syntax for different variables. Here are some basic syntax for creating tables."
},
{
"code": null,
"e": 384,
"s": 353,
"text": "CREAT... |
Working with Documents - Python .docx Module - GeeksforGeeks | 03 Jan, 2021
Prerequisite: Working with .docx module
Word documents contain formatted text wrapped within three object levels. The lowest level- run objects, middle level- paragraph objects, and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module. Pip command to install this module is:
pip install python-docx
Python docx module allows users to manipulate docs by either manipulating the existing one or creating a new empty document and manipulating it. It is a powerful tool as it helps you to manipulate the document to a very large extend.
Now, to use the python-docx module you have to import it as docx.
# Import docx NOT python-docx
import docx
Then to create an instance of the word document. We will use the Document() method of the docx module.
Syntax: docx.Document(String path)
Parameter:
String path: It is an optional parameter. It specifies the path of the file to be open. If it is left empty then a new empty document file is created.
And to save the document we will use save() method of the docx module.
Syntax: doc.save(String path_to_document)
Parameter:
String path_to_document: It is the file name by which document will be saved. You can even put the path to where you want to save it.
Example 1: Opening a new document.
Python3
# Import docx NOT python-docximport docx # Create an instance of a word documentdoc = docx.Document() # Now save the document to a location doc.save('gfg.docx')
Output:
Example 2: Opening a previously created document and again saving it with a different name.
Python3
# Import docx NOT python-docximport docx # Opening a previously created documentdoc = docx.Document('gfg.docx') # Now save the document to a location doc.save('gfg-copy.docx')
Output:
Python Docx-module
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python | [
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n03 Jan, 2021"
},
{
"code": null,
"e": 24252,
"s": 24212,
"text": "Prerequisite: Working with .docx module"
},
{
"code": null,
"e": 24616,
"s": 24252,
"text": "Word documents contain formatted text wrapped with... |
How to Quickly Create and Unpack Lists with Pandas | by Byron Dolon | Towards Data Science | Pre-processing and “data wrangling” take up a lot of time, but it’s not always the most fun part of a data analysis project.
Having to unpack a list comes up a lot when it comes to reformatting your initial data. Fortunately, Pandas comes with a lot of vectorized solutions to common problems, so we won’t have to stress too hard about unpacking lists in a DataFrame.
In this piece, we’ll be looking at two things:
How to use df.explode() to unnest a column with list-like values in a DataFrame;
How to use Series.str.split() to create a list from a string.
We’ll be using a modified version of this video game sales data, so you can download the csv file if you want to follow along. This time, I included the code to get the initial tables for each of the examples at the very bottom. I’d suggest going through the piece first, and then copying the code to get the inputs to try out the examples after.
Our initial table looks like this:
The goal is to separate all the values in the “Genre” column, so that each row only has one value. In terms of database normalization, this would be a step towards fulfilling the “first normal form”, where each column only contains atomic (non-divisible) values.
To do so, all we need to do is use the df.explode() function. We only need to pass one argument, which is the name of the column with the list like values.
Our code is like this.
df2 = df2.explode('Genre').drop_duplicates()
A subset of the resulting DataFrame looks like this:
Now we have a table with all the different Genres of each Publisher. We also made sure to only have unique values by passing .drop_duplicates() on the DataFrame.
You’ll notice that the index value from the original DataFrame was kept for each of the rows, which goes to show that all the df.explode() function does is separate elements in the iterable while keeping all other row values the same. We could also easily pass .reset_index() if we wanted new index values.
In the last problem, we worked with a DataFrame that had a column full of lists. However, oftentimes you’ll be working with data that doesn’t fit neatly into pre-defined Pandas functions. For example, say we have a similar table to the last problem’s that looked like this:
Can you spot the difference?
We still have a bunch of values in the “Genre” column, but they’re no longer in a Python list. The df.explode() function wouldn’t work, because as per its documentation:
This routine (df.explode) will explode list-likes including lists, tuples, Series, and np.ndarray.
We currently have multiple items for each column value, but they are not in the “list-like” format. All we have is a bunch of really long strings.
To combine the sub-strings into a list, we’ll make use of a simple line of code to convert the string into a list:
df3['Genre'] = df3['Genre'].str.split(',')
Here, we used the Series.str.split() method on the “Genre” column to create a list. As its name suggests, this method splits a string on a separator that you specify, which in our case is a comma. If you don’t pass anything into split(), the method will attempt to split a string on whitespace, but our strings don’t have any.
The resulting table looks like this:
Now we have a table almost identical to the previous one, except this time all the different values are in a list.
All we have to do now is run the same line of code as in the first problem:
df3 = df3.explode('Genre')
I hope you found this quick look at df.melt useful for your work with Pandas! If you need to create or unpack lists in your DataFrames, you can make use of the Series.str.split() and df.explode() methods respectively.
As promised, here’s the code to set up the two examples:
import pandas as pddf = pd.read_csv('vgsales.csv').dropna()df['Year'] = df['Year'].astype(int)# problem 1df2 = df.groupby('Publisher')['Genre'].apply(','.join).reset_index()df2 = df2.loc[(df2['Publisher']=='Nintendo') | (df2['Publisher']=='Ubisoft') | (df2['Publisher']=='Activision')]df2['Genre'] = df2['Genre'].str.strip().str.split(',')# problem 2df3 = df.groupby('Publisher')['Genre'].apply(','.join).reset_index()df3 = df3.loc[(df3['Publisher']=='Infogrames') | (df3['Publisher']=='Wanadoo')]
You can see I used the .loc[] function to set out some conditions for my DataFrames, so if you’re not familiar with using it already, you can check out this piece:
towardsdatascience.com
I also used .apply() here, which is a simple way to perform a function along an axis of a DataFrame. For a different way to edit a DataFrame row by row (which I would suggest using only when you have a problem that doesn’t have a vectorized Pandas solution), check out this piece:
towardsdatascience.com
Good luck on your adventures with Pandas! | [
{
"code": null,
"e": 297,
"s": 172,
"text": "Pre-processing and “data wrangling” take up a lot of time, but it’s not always the most fun part of a data analysis project."
},
{
"code": null,
"e": 540,
"s": 297,
"text": "Having to unpack a list comes up a lot when it comes to refor... |
PyQt5 QDateEdit - Getting Style Sheet - GeeksforGeeks | 07 Jul, 2020
In this article we will see how we can get the style sheet to the date edit. Setting style sheet makes the date edit look unique with the help of style sheet we can set color, border and many other things to the date edit. We can set style sheet with the help of setStyleSheet method.
In order to do this we use styleSheet method with the QDateEdit object
Syntax : date.styleSheet()
Argument : It takes no argument
Return : It returns string
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QDateEdit widget date = QDateEdit(self) # setting geometry of the date edit date.setGeometry(100, 100, 200, 40) # alignment a_flag = Qt.AlignCenter # setting alignment of date date.setAlignment(a_flag) # setting style sheet date.setStyleSheet("QDateEdit" "{" "border : 2px solid black;" "background : white;" "padding : 5px;" "}" "QDateEdit::up-arrow" "{" "border : 2px solid black;" "background-color : lightgreen;" "}" "QDateEdit::down-arrow" "{" "border : 2px solid black;" "background-color : red;" "}" ) # creating a label label = QLabel("GeeksforGeeks", self) # setting geometry label.setGeometry(100, 150, 250, 60) # making label multiline label.setWordWrap(True) # getting style sheet value = date.styleSheet() # setting text to the label label.setText("Style Sheet : " + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python PyQt-QDateEdit
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python | [
{
"code": null,
"e": 24121,
"s": 24093,
"text": "\n07 Jul, 2020"
},
{
"code": null,
"e": 24406,
"s": 24121,
"text": "In this article we will see how we can get the style sheet to the date edit. Setting style sheet makes the date edit look unique with the help of style sheet we ca... |
How to assign multiple values to a same variable in Python? | In Python, if you try to do something like
a = b = c = [0,3,5]
a[0] = 10
You'll end up with the same values in
a, b, and c: [10, 3, 5]
This is because all three variables here point to the same value. If you modify this value, you'll get the change reflected in all names, ie, a,b and c. To create a new object and assign it, you can use the copy module.
a = [0,3,5]
import copy
b = copy.deepcopy(a)
a[0] = 5
print(a)
print(b)
This will give the output −
[5,3,5]
[0,3,5] | [
{
"code": null,
"e": 1105,
"s": 1062,
"text": "In Python, if you try to do something like"
},
{
"code": null,
"e": 1135,
"s": 1105,
"text": "a = b = c = [0,3,5]\na[0] = 10"
},
{
"code": null,
"e": 1173,
"s": 1135,
"text": "You'll end up with the same values in... |
C | Operators | Question 10 - GeeksforGeeks | 10 Nov, 2020
What is the output of following program?
#include <stdio.h> int main(){ int a = 1; int b = 1; int c = a || --b; int d = a-- && --b; printf("a = %d, b = %d, c = %d, d = %d", a, b, c, d); return 0;}
(A) a = 0, b = 1, c = 1, d = 0(B) a = 0, b = 0, c = 1, d = 0
(C) a = 1, b = 1, c = 1, d = 1(D) a = 0, b = 0, c = 0, d = 0Answer: (B)Explanation: Let us understand the execution line by line.Initial values of a and b are 1.
// Since a is 1, the expression --b
// is not executed because
// of the short-circuit property
// of logical or operator
// So c becomes 1, a and b remain 1
int c = a || --b;
// The post decrement operator --
// returns the old value in current expression
// and then updates the value. So the
// value of expression a-- is 1. Since the
// first operand of logical and is 1,
// shortcircuiting doesn't happen here. So
// the expression --b is executed and --b
// returns 0 because it is pre-increment.
// The values of a and b become 0, and
// the value of d also becomes 0.
int d = a-- && --b;
Quiz of this Question
akhil11199914
C-Operators
Operators
C Quiz
Operators
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C | Dynamic Memory Allocation | Question 5
C | Advanced Pointer | Question 2
C | Advanced Pointer | Question 1
C Quiz - 107 | Question 2
C | Data Types | Question 2
C Quiz - 101 | Question 5
C Quiz - 104 | Question 5
C | Structure & Union | Question 2
C Quiz - 110 | Question 5
C | Structure & Union | Question 5 | [
{
"code": null,
"e": 24194,
"s": 24166,
"text": "\n10 Nov, 2020"
},
{
"code": null,
"e": 24235,
"s": 24194,
"text": "What is the output of following program?"
},
{
"code": "#include <stdio.h> int main(){ int a = 1; int b = 1; int c = a || --b; int d = a-- && --b;... |
iconv command in Linux with Examples - GeeksforGeeks | 15 Apr, 2019
iconv command is used to convert some text in one encoding into another encoding. If no input file is provided then it reads from standard input. Similarly, if no output file is given then it writes to standard output. If no from-encoding or to-encoding is provided then it uses current local’s character encoding.
Syntax:
iconv [options] [-f from-encoding] [-t to-encoding] [inputfile]...
Options:
-f from-encoding, –from-code=from-encoding : Use from-encoding for input characters.
-t to-encoding, –to-code=to-encoding : Use to-encoding for output characters.
-l, –list : List all known character set encodings.
-c : Silently discard characters that cannot be converted instead of terminating when encountering such characters.
-o outputfile, –output=outputfile : Use outputfile for output.
–verbose : Print progress information on standard error when processing multiple files.
Note:
If the string //IGNORE is appended to to-encoding, characters that cannot be converted are discarded and an error is printed after conversion.
If the string //TRANSLIT is appended to to-encoding, characters that cannot be represented in the target character set, it can be approximated through one or several similar looking characters.
Examples:
To convert from UTF-8 to ASCII :echo abc ß ? € à?ç | iconv -f UTF-8 -t ASCII//TRANSLIT
echo abc ß ? € à?ç | iconv -f UTF-8 -t ASCII//TRANSLIT
Print the list of all character set encodings :iconv -l
iconv -l
Reading and writing from a file :iconv -f UTF-8 -t ASCII//TRANSLIT -o out.txt in.txt
iconv -f UTF-8 -t ASCII//TRANSLIT -o out.txt in.txt
linux-command
Linux-text-processing-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
nohup Command in Linux with Examples
scp command in Linux with Examples
chown command in Linux with Examples
Array Basics in Shell Scripting | Set 1
mv command in Linux with examples
Basic Operators in Shell Scripting
SED command in Linux | Set 2
Docker - COPY Instruction
Named Pipe or FIFO with example C program | [
{
"code": null,
"e": 24406,
"s": 24378,
"text": "\n15 Apr, 2019"
},
{
"code": null,
"e": 24721,
"s": 24406,
"text": "iconv command is used to convert some text in one encoding into another encoding. If no input file is provided then it reads from standard input. Similarly, if no ... |
Tryit Editor v3.7 | HTML Input types
Tryit: input type = checkbox | [
{
"code": null,
"e": 27,
"s": 10,
"text": "HTML Input types"
}
] |
Batch Script - Local Variables in Functions | Local variables in functions can be used to avoid name conflicts and keep variable changes local to the function. The SETLOCAL command is first used to ensure the command processor takes a backup of all environment variables. The variables can be restored by calling ENDLOCAL command. Changes made in between are local to the current batch script. ENDLOCAL is automatically called when the end of the batch file is reached, i.e. by calling GOTO:EOF.
Localizing variables with SETLOCAL allows using variable names within a function freely without worrying about name conflicts with variables used outside the function.
Following example shows how local variables can be used in functions.
@echo off
set str = Outer
echo %str%
CALL :SetValue str
echo %str%
EXIT /B %ERRORLEVEL%
:SetValue
SETLOCAL
set str = Inner
set "%~1 = %str%"
ENDLOCAL
EXIT /B 0
In the above program, the variable ‘str’ is being localized in the function SetValue. Thus even though the str value is being returned back to the main function, the value of str in the main function will not be replaced by the value being returned from the function.
The above command produces the following output.
Outer
Outer
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2619,
"s": 2169,
"text": "Local variables in functions can be used to avoid name conflicts and keep variable changes local to the function. The SETLOCAL command is first used to ensure the command processor takes a backup of all environment variables. The variables can be restor... |
Python 3 - String isnumeric() Method | The isnumeric() method checks whether the string consists of only numeric characters. This method is present only on unicode objects.
Note − Unlike Python 2, all strings are represented in Unicode in Python 3. Given below is an example illustrating it.
Following is the syntax for isnumeric() method −
str.isnumeric()
NA
This method returns true if all characters in the string are numeric, false otherwise.
The following example shows the usage of isnumeric() method.
#!/usr/bin/python3
str = "this2016"
print (str.isnumeric())
str = "23443434"
print (str.isnumeric())
When we run above program, it produces the following result −
False
True
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2474,
"s": 2340,
"text": "The isnumeric() method checks whether the string consists of only numeric characters. This method is present only on unicode objects."
},
{
"code": null,
"e": 2593,
"s": 2474,
"text": "Note − Unlike Python 2, all strings are represen... |
Python | Plotting Google Map using folium package - GeeksforGeeks | 08 Jun, 2021
Folium is built on the data wrangling strengths of the Python ecosystem and the mapping strengths of the Leaflet.js (JavaScript) library. Simply, manipulate your data in Python, then visualize it on a leaflet map via Folium. Folium makes it easy to visualize data that’s been manipulated in Python, on an interactive Leaflet map. This library has a number of built-in tilesets from OpenStreetMap, Mapbox etc.Command to install folium module :
pip install folium
Code #1 : To create a Base Map.
Python3
# import folium packageimport folium # Map method of folium return Map object # Here we pass coordinates of Gfg# and starting Zoom level = 12my_map1 = folium.Map(location = [28.5011226, 77.4099794], zoom_start = 12 ) # save method of Map object will create a mapmy_map1.save(" my_map1.html " )
Output :
Code #2 : Add a circular marker with popup text.
Python3
# import folium packageimport folium my_map2 = folium.Map(location = [28.5011226, 77.4099794], zoom_start = 12) # CircleMarker with radiusfolium.CircleMarker(location = [28.5011226, 77.4099794], radius = 50, popup = ' FRI ').add_to(my_map2) # save as htmlmy_map2.save(" my_map2.html ")
Output :
Code #3 : Add a simple_marker for parachute style marker with pop-up text.
Python3
# import folium packageimport folium my_map3 = folium.Map(location = [28.5011226, 77.4099794], zoom_start = 15) # Pass a string in popup parameterfolium.Marker([28.5011226, 77.4099794], popup = ' Geeksforgeeks.org ').add_to(my_map3) my_map3.save(" my_map3.html ")
Output :
Code #4 : Add a line to the map
Python3
# import folium packageimport folium my_map4 = folium.Map(location = [28.5011226, 77.4099794], zoom_start = 12) folium.Marker([28.704059, 77.102490], popup = 'Delhi').add_to(my_map4) folium.Marker([28.5011226, 77.4099794], popup = 'GeeksforGeeks').add_to(my_map4) # Add a line to the map by using line method .# it connect both coordinates by the line# line_opacity implies intensity of the line folium.PolyLine(locations = [(28.704059, 77.102490), (28.5011226, 77.4099794)], line_opacity = 0.5).add_to(my_map4) my_map4.save("my_map4.html")
Output :
surinderdawra388
python-modules
python-utility
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": 26609,
"s": 26581,
"text": "\n08 Jun, 2021"
},
{
"code": null,
"e": 27054,
"s": 26609,
"text": "Folium is built on the data wrangling strengths of the Python ecosystem and the mapping strengths of the Leaflet.js (JavaScript) library. Simply, manipulate your d... |
at Command in Linux with Examples - GeeksforGeeks | 03 Jul, 2020
at command is a command-line utility that is used to schedule a command to be executed at a particular time in the future. Jobs created with at command are executed only once. The at command can be used to execute any program or mail at any time in the future. It executes commands at a particular time and accepts times of the form HH:MM to run a job at a specific time of day. The following expression like noon, midnight, teatime, tomorrow, next week, next Monday, etc. could be used with at command to schedule a job.
Syntax:
at [OPTION...] runtime
For Ubuntu/Debian :
sudo apt-get update
sudo apt-get install at
For CentOS/Fedora :
sudo yum install at
1. Command to list the user’s pending jobs:
at -l
or
atq
2. Schedule a job for the coming Monday at a time twenty minutes later than the current time:
at Monday +20 minutes
3. Schedule a job to run at 1:45 Aug 12 2020:
at 1:45 081220
4. Schedule a job to run at 3pm four days from now:
at 3pm + 4 days
5. Schedule a job to shutdown the system at 4:30 today:
# echo "shutdown -h now" | at -m 4:30
6. Schedule a job to run five hour from now:
at now +5 hours
7. at -r or atrm command is used to deletes job , here used to deletes job 11 .
at -r 11
or
atrm 11
linux-command
Linux-system-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux | [
{
"code": null,
"e": 25675,
"s": 25647,
"text": "\n03 Jul, 2020"
},
{
"code": null,
"e": 26197,
"s": 25675,
"text": "at command is a command-line utility that is used to schedule a command to be executed at a particular time in the future. Jobs created with at command are execute... |
How to calculate minutes between two dates in JavaScript ? - GeeksforGeeks | 20 Jun, 2019
Given two dates and the task is to get the number of minutes between them using JavaScript.
Approach:
Initialize both Date object.
Subtract older date from the new date. It will give the number of milliseconds from 1 January, 1970.
Convert milliseconds to minutes .
Example 1: This example uses the current date and next newYear date to get the difference of dates in minutes.
<!DOCTYPE HTML> <html> <head> <title> How to get the minutes between two dates in JavaScript ? </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;"> </p> <button onClick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;"> </p> <!-- Script to calculate difference between two dates --> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); // Declare dates var today = new Date(); var newYear = new Date("01-01-2020"); // Display the dates up.innerHTML = "Today's Date= "+ today.toLocaleDateString() + "<br> newYear's Date = " + newYear.toLocaleDateString(); // Function to calculate difference // between two dates function GFG_Fun() { var dif = (newYear - today); var dif = Math.round((dif/1000)/60); down.innerHTML = "Minutes left = " + dif; } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Example 2: This example uses the 2019 newYear and 2020 newYear date to get the difference in minutes.
<!DOCTYPE HTML> <html> <head> <title> How to get the minutes between two dates in JavaScript ? </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;"> </p> <button onClick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;"> </p> <!-- Script to calculate difference between two dates --> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); // Declare dates var newYear1 = new Date("01-01-2019"); var newYear2 = new Date("01-01-2020"); // Display the dates up.innerHTML = "First Date= "+ newYear1.toLocaleDateString() + "<br> Second Date = " + newYear2.toLocaleDateString(); // Function to calculate difference // between two dates function GFG_Fun() { var dif = (newYear2 - newYear1); var dif = Math.round((dif/1000)/60); down.innerHTML = "Minutes left = " + dif; } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
javascript-date
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26545,
"s": 26517,
"text": "\n20 Jun, 2019"
},
{
"code": null,
"e": 26637,
"s": 26545,
"text": "Given two dates and the task is to get the number of minutes between them using JavaScript."
},
{
"code": null,
"e": 26647,
"s": 26637,
"text":... |
How to Install PIL on Linux? - GeeksforGeeks | 30 Sep, 2021
PIL is an acronym for Python Image Library. It is also called Pillow. It is one of the most famous libraries for manipulating images using the python programming language. It is a free and open-source Python library.
Step 1: Open up the Linux terminal and type the following command and hit enter.
pip install pillow
Output:
installing PIL
Step 2: To check if PIL is successfully installed, open up the python terminal by typing python3 in the terminal. This will open up the python3 interactive console now type the following command to check the current version of the PIL.
import PIL
PIL.__version__
This will output the currently installed version of the PIL.
Output:
PIL version
Aptitude is just a frontend version of the apt command that we used to install packages. Aptitude is an interactive package manager, it provides a list of all the matching packages that we want to install. It also finds and installs all the required dependencies for the package.
Step 1: Run the following command to install the PIL using Aptitude.
sudo aptitude install python3-pil
Output:
installing pil using aptitude
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Align Text in HTML?
How to filter object array based on attributes?
Java Tutorial
How to Install FFmpeg on Windows?
How to integrate Git Bash with Visual Studio Code?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Anaconda on Windows?
How to Install Pygame on Windows ?
How to Install and Run Apache Kafka on Windows? | [
{
"code": null,
"e": 25851,
"s": 25823,
"text": "\n30 Sep, 2021"
},
{
"code": null,
"e": 26068,
"s": 25851,
"text": "PIL is an acronym for Python Image Library. It is also called Pillow. It is one of the most famous libraries for manipulating images using the python programming l... |
PyQt5 QSpinBox - Finding children using child type - GeeksforGeeks | 19 May, 2020
In this article we will see how we can find all the children of spin box using the child type, child type is the quality of child for example push button type is QPushButton. Spin box is made of two child one is line edit whose type is QLineEdit and other is those up and down button whose type are QValidator.
In order to do this we use findChildren method
Syntax : spin_box.findChildren(child_type)
Argument : It takes child type as argument
Return : It returns the list of child objects, if no child is found it return empty list
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating spin box self.spin = QSpinBox(self) # setting geometry to spin box self.spin.setGeometry(100, 100, 250, 40) # setting range to the spin box self.spin.setRange(0, 999999) # setting prefix to spin self.spin.setPrefix("Prefix ") # setting suffix to spin self.spin.setSuffix(" Suffix") # getting children using child type children = self.spin.findChildren(QValidator) # creating a label label = QLabel(self) # making it multi line label.setWordWrap(True) # setting its geometry label.setGeometry(100, 200, 200, 60) # setting text to the label label.setText(str(children)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python PyQt-SpinBox
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": 26097,
"s": 26069,
"text": "\n19 May, 2020"
},
{
"code": null,
"e": 26408,
"s": 26097,
"text": "In this article we will see how we can find all the children of spin box using the child type, child type is the quality of child for example push button type is Q... |
Tensorflow.js tf.layers addWeight() Method - GeeksforGeeks | 22 Apr, 2022
Tensorflow.js is an open-source library that is developed by Google for running machine learning models as well as deep learning neural networks in the browser or node environment.
The .addWeight() function is used add a variable of weight to the stated layer.
Syntax:
addWeight(name, shape, dtype?, initializer?,
regularizer?, trainable?, constraint?)
Parameters:
name: It is the stated name of new variable of weight and is of type string.
shape: It is the stated shape of the weight. It is of type (null | number)[].
dtype: It is the stated datatype of the weight. It is optional and can be of type float32, int32, bool, complex64, or string.
initializer: It is the stated initializer instance. It is optional and is of type tf.initializers.Initializer.
regularizer: It is the stated regularizer instance. It is optional and is of type Regularizer.
trainable: It states if the weight should be instructed through backprop or not by presuming that the layer itself is similarly trainable. It is optional and is of type boolean.
constraint: It is an optional trainable and is of type tf.constraints.Constraint.
Return Value: It returns LayerVariable.
Example 1:
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Creating a modelconst model = tf.sequential(); // Adding a layermodel.add(tf.layers.dense({units: 2, inputShape: [1]})); // Calling addWeight() methodconst res = model.layers[0].addWeight('wt_var', [1, 5], 'int32', tf.initializers.ones()); // Printing outputconsole.log(res);model.layers[0].getWeights()[0].print();
Output:
{
"dtype": "int32",
"shape": [
1,
5
],
"id": 1582,
"originalName": "wt_var",
"name": "wt_var_2",
"trainable_": true,
"constraint": null,
"val": {
"kept": false,
"isDisposedInternal": false,
"shape": [
1,
5
],
"dtype": "int32",
"size": 5,
"strides": [
5
],
"dataId": {
"id": 2452
},
"id": 2747,
"rankType": "2",
"trainable": true,
"name": "wt_var_2"
}
}
Tensor
[[0.139703, 0.9717236],]
Here, getWeights() method is used to print the weights of the layer specified.
Example 2:
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Creating a modelconst model = tf.sequential(); // Adding a layermodel.add(tf.layers.dense({units: 2, inputShape: [1]}));model.add(tf.layers.dense({units: 3})); // Calling addWeight() methodconst res1 = model.layers[0].addWeight('w_v', [1.2, 1.3], 'float32', tf.initializers.zeros(), true); const res2 = model.layers[1].addWeight('wv', ["a", "b"], 'int32', tf.initializers.ones(), false); // Printing outputsconsole.log(res1);console.log(res2);model.layers[0].getWeights()[0].print();model.layers[1].getWeights()[0].print();
Output:
{
"dtype": "float32",
"shape": [
1.2,
1.3
],
"id": 7,
"originalName": "w_v",
"name": "w_v",
"trainable_": true,
"constraint": null,
"val": {
"kept": false,
"isDisposedInternal": false,
"shape": [
1.2,
1.3
],
"dtype": "float32",
"size": 1.56,
"strides": [
1.3
],
"dataId": {
"id": 4
},
"id": 9,
"rankType": "2",
"trainable": true,
"name": "w_v"
}
}
{
"dtype": "int32",
"shape": [
"a",
"b"
],
"id": 8,
"originalName": "wv",
"name": "wv",
"trainable_": true,
"constraint": null,
"val": {
"kept": false,
"isDisposedInternal": false,
"shape": [
"a",
"b"
],
"dtype": "int32",
"size": null,
"strides": [
"b"
],
"dataId": {
"id": 5
},
"id": 11,
"rankType": "2",
"trainable": true,
"name": "wv"
}
}
Tensor
[[0.835237, 0.960075],]
Tensor
[[0.4747705 , -0.6734858, 1.1417971],
[-0.8185477, 0.1940626 , -0.98313 ]]
Here, tf.initializers.zeros() method is used to produce tensors that are initialized to zero and tf.initializers.ones() method is used to produce tensors that are initialized to one.
Reference: https://js.tensorflow.org/api/latest/#tf.layers.Layer.addWeight
Picked
Tensorflow.js
TensorFlow.js-Classes
TensorFlow.js-layers
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 26545,
"s": 26517,
"text": "\n22 Apr, 2022"
},
{
"code": null,
"e": 26726,
"s": 26545,
"text": "Tensorflow.js is an open-source library that is developed by Google for running machine learning models as well as deep learning neural networks in the browser or ... |
Implementation of Wilson Primality test - GeeksforGeeks | 09 Apr, 2021
Given a number N, the task is to check if it is prime or not using Wilson Primality Test. Print ‘1’ isf the number is prime, else print ‘0’.Wilson’s theorem states that a natural number p > 1 is a prime number if and only if
(p - 1) ! ≡ -1 mod p
OR (p - 1) ! ≡ (p-1) mod p
Examples:
Input: p = 5
Output: Yes
(p - 1)! = 24
24 % 5 = 4
Input: p = 7
Output: Yes
(p-1)! = 6! = 720
720 % 7 = 6
Below is the implementation of Wilson Primality Test
C++
Java
Python3
C#
Javascript
// C++ implementation to check if a number is// prime or not using Wilson Primality Test#include <bits/stdc++.h>using namespace std; // Function to calculate the factoriallong fact(const int& p){ if (p <= 1) return 1; return p * fact(p - 1);} // Function to check if the// number is prime or notbool isPrime(const int& p){ if (p == 4) return false; return bool(fact(p >> 1) % p);} // Driver codeint main(){ cout << isPrime(127); return 0;}
// Java implementation to check if a number is // prime or not using Wilson Primality Testpublic class Main{ // Function to calculate the factorial public static long fact(int p) { if (p <= 1) return 1; return p * fact(p - 1); } // Function to check if the // number is prime or not public static long isPrime(int p) { if (p == 4) return 0; return (fact(p >> 1) % p); } public static void main(String[] args) { if(isPrime(127) == 0) { System.out.println(0); } else{ System.out.println(1); } }} // This code is contributed by divyesh072019
# Python3 implementation to check if a number is# prime or not using Wilson Primality Test # Function to calculate the factorialdef fact(p): if (p <= 1): return 1 return p * fact(p - 1) # Function to check if the# number is prime or notdef isPrime(p): if (p == 4): return 0 return (fact(p >> 1) % p) # Driver codeif (isPrime(127) == 0): print(0)else: print(1) # This code is contributed by rag2127
// C# implementation to check if a number is // prime or not using Wilson Primality Testusing System;class GFG { // Function to calculate the factorial static long fact(int p) { if (p <= 1) return 1; return p * fact(p - 1); } // Function to check if the // number is prime or not static long isPrime(int p) { if (p == 4) return 0; return (fact(p >> 1) % p); } static void Main() { if(isPrime(127) == 0) { Console.WriteLine(0); } else{ Console.WriteLine(1); } }} // This code is contributed by divyeshrabadiya07
<script> // Javascript implementation to check if a number is // prime or not using Wilson Primality Test // Function to calculate the factorial function fact(p) { if (p <= 1) return 1; return p * fact(p - 1); } // Function to check if the // number is prime or not function isPrime(p) { if (p == 4) return false; if(fact(p >> 1) % p == 0) { return 0; } return 1; } document.write(isPrime(127)); // This code is contributed by suresh07.</script>
1
How does it work?
We can quickly check result for p = 2 or p = 3.For p > 3: If p is composite, then its positive divisors are among the integers 1, 2, 3, 4, ... , p-1 and it is clear that gcd((p-1)!,p) > 1, so we can not have (p-1)! = -1 (mod p).Now let us see how it is exactly -1 when p is a prime. If p is a prime, then all numbers in [1, p-1] are relatively prime to p. And for every number x in range [2, p-2], there must exist a pair y such that (x*y)%p = 1. So
We can quickly check result for p = 2 or p = 3.
For p > 3: If p is composite, then its positive divisors are among the integers 1, 2, 3, 4, ... , p-1 and it is clear that gcd((p-1)!,p) > 1, so we can not have (p-1)! = -1 (mod p).
Now let us see how it is exactly -1 when p is a prime. If p is a prime, then all numbers in [1, p-1] are relatively prime to p. And for every number x in range [2, p-2], there must exist a pair y such that (x*y)%p = 1. So
[1 * 2 * 3 * ... (p-1)]%p
= [1 * 1 * 1 ... (p-1)] // Group all x and y in [2..p-2]
// such that (x*y)%p = 1
= (p-1)
divyesh072019
divyeshrabadiya07
rag2127
suresh07
factorial
Modular Arithmetic
Prime Number
Algorithms
Mathematical
Mathematical
Prime Number
Modular Arithmetic
factorial
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
How to write a Pseudo Code?
Understanding Time Complexity with Simple Examples
Introduction to Algorithms
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 25913,
"s": 25885,
"text": "\n09 Apr, 2021"
},
{
"code": null,
"e": 26138,
"s": 25913,
"text": "Given a number N, the task is to check if it is prime or not using Wilson Primality Test. Print ‘1’ isf the number is prime, else print ‘0’.Wilson’s theorem states... |
GATE | GATE-CS-2014-(Set-1) | Question 40 - GeeksforGeeks | 28 Jun, 2021
Given the following two statements:
S1: Every table with two single-valued
attributes is in 1NF, 2NF, 3NF and BCNF.
S2: AB->C, D->E, E->C is a minimal cover for
the set of functional dependencies
AB->C, D->E, AB->E, E->C.
Which one of the following is CORRECT?
(A) S1 is TRUE and S2 is FALSE.(B) Both S1 and S2 are TRUE.(C) S1 is FALSE and S2 is TRUE.(D) Both S1 and S2 are FALSE.Answer: (A)Explanation:
S1: Every table with two single-valued
attributes is in 1NF, 2NF, 3NF and BCNF.
A relational schema R is in BCNF iff in Every non-trivial Functional Dependency X->Y, X is Super Key. If we can prove the relation is in BCNF then by default it would be in 1NF, 2NF, 3NF also.
Let R(AB) be a two attribute relation, then
If {A->B} exists then BCNF since {A}+ = AB = RIf {B->A} exists then BCNF since {B}+ = AB = RIf {A->B,B->A} exists then BCNF since A and B both are Super Key now.If {No non trivial Functional Dependency} then default BCNF.
If {A->B} exists then BCNF since {A}+ = AB = R
If {B->A} exists then BCNF since {B}+ = AB = R
If {A->B,B->A} exists then BCNF since A and B both are Super Key now.
If {No non trivial Functional Dependency} then default BCNF.
Hence it’s proved that a Relation with two single – valued attributes is in BCNF hence its also in 1NF, 2NF, 3NF.
Hence S1 is true.
S2: AB->C, D->E, E->C is a minimal cover for
the set of functional dependencies
AB->C, D->E, AB->E, E->C.
As we know Minimal Cover is the process of eliminating redundant Functional Dependencies and Extraneous attributes in Functional Dependency Set.
So each dependency of F = {AB->C, D->E, AB->E, E->C} should be implied in minimal cover.
As we can see AB->E is not covered in minimal cover since {AB}+ = ABC in the given cover {AB->C, D->E, E->C}
Hence, S2 is false.
This explanation has been contributed by Manish Rai.
Learn more about Normal forms here:
Database Normalization | IntroductionDatabase Normalization | Normal FormsQuiz of this Question
GATE-CS-2014-(Set-1)
GATE-GATE-CS-2014-(Set-1)
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": 25695,
"s": 25667,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 25731,
"s": 25695,
"text": "Given the following two statements:"
},
{
"code": null,
"e": 25944,
"s": 25731,
"text": " S1: Every table with two single-valued \n attri... |
Function Overloading in JavaScript - GeeksforGeeks | 01 Sep, 2021
Unlike the other programming languages, JavaScript Does not support Function Overloading. Here is a small code which shows that JavaScript does not support Function Overloading.
Javascript
function foo(arg1) { console.log(arg1);} /* The above function will be overwritten by the function below, and the below function will be executed for any number and any type of arguments */function foo(arg1, arg2) { console.log(arg1, arg2);} // Driver codefoo("Geeks")
Output:
Geeks undefined
The reason for the “undefined” in the output is: In JavaScript if two functions are defined with same name then the last defined function will overwrite the former function. So in this case the foo(arg1) was overwritten by foo(arg1,arg2), but we only passed one Argument (“Geeks”) to the function. It means that the second argument is undefined, So when we tried to print the second argument, it is printed as “undefined”.
We have seen that function Overloading is not support in JavaScript, but we can implement the function Overloading on our own, which is pretty much complex when it comes to more number and more type of arguments. The following code will help you to understand how to implement function Overloading in JavaScript.
Javascript
// Creating a class "foo"class foo { // Creating an overloadable method/function. overloadableFunction() { // Define three overloaded functions var function1 = function (arg1) { console.log("Function1 called with" + " arguments : " + arg1); return arg1; }; var function2 = function (arg1, arg2) { console.log("Function2 called with" + " arguments : " + arg1 + " and " + arg2); return arg1 + arg2; }; var function3 = function (arg1) { var concatenated__arguments = " ", temp = " " // Concatenating all the arguments // and storing them into a string for (var i = 0; i < arg1.length; i++) { concatenated__arguments = concatenated__arguments + arg1[i] } /* Just ignore this loop and temp variable, we are using this loop to concatenate arguments with a space between them */ for (var i = 0; i < arg1.length; i++) { temp = temp + " " + arg1[i] } console.log("Function3 called with this" + " array as an argument : [" + temp + "]"); console.log("Output of log is : ") // Returns concatenated argument string return concatenated__arguments; }; /* Here with the help of the length of the arguments and the type of the argument passed ( in this case an Array ) we determine which function to be executed */ if (arguments.length === 1 && Array.isArray(arguments[0])) { return function3(arguments[0]); } else if (arguments.length === 2) { return function2(arguments[0], arguments[1]); } else if (arguments.length === 1 && !Array.isArray(arguments[0])) { return function1(arguments[0]); } }} // Driver Code // Instantiate an object of the "foo" classvar object = new foo(); // Call the overloaded functions using the// function overloadableFunction(...)// We are passing 1 argument so executes function1console.log(object.overloadableFunction("Geeks")); // We are passing two arguments so executes function2console.log(object.overloadableFunction("Geeks", "for")); // We are passing an array so executes function3console.log(object.overloadableFunction( ["Geeks", "for", "Geeks"]));
Output:
Function1 called with arguments : Geeks
Geeks
Function2 called with arguments : Geeks and for
Geeksfor
Function3 called with this array as an argument : [ Geeks for Geeks]
GeeksforGeeks
Output of log is :
GeeksforGeeks
Explanation: In the above program, when different number of arguments are passed to the same function, then based on the number and type of arguments, the arguments will be passed to the respective function. In this case, we have used three different functions (function1, function2, function3) for function Overloading.
adnanirshad158
akshaysingh98088
ruhelaa48
sooda367
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26545,
"s": 26517,
"text": "\n01 Sep, 2021"
},
{
"code": null,
"e": 26724,
"s": 26545,
"text": "Unlike the other programming languages, JavaScript Does not support Function Overloading. Here is a small code which shows that JavaScript does not support Functio... |
Python exit commands: quit(), exit(), sys.exit() and os._exit() - GeeksforGeeks | 31 Dec, 2019
The functions quit(), exit(), sys.exit() and os._exit() have almost same functionality as they raise the SystemExit exception by which the Python interpreter exits and no stack traceback is printed.We can catch the exception to intercept early exits and perform cleanup activities; if uncaught, the interpreter exits as usual.
When we run a program in Python, we simply execute all the code in file, from top to bottom. Scripts normally exit when the interpreter reaches the end of the file, but we may also call for the program to exit explicitly with the built-in exit functions.
quit()It works only if the site module is imported so it should not be used in production code. Production code means the code is being used by the intended audience in a real-world situation. This function should only be used in the interpreter.It raises the SystemExit exception behind the scenes. If you print it, it will give a message:Example:# Python program to demonstrate# quit() for i in range(10): # If the value of i becomes # 5 then the program is forced # to quit if i == 5: # prints the quit message print(quit) quit() print(i)Output:0
1
2
3
4
Use quit() or Ctrl-D (i.e. EOF) to exit
exit()exit() is defined in site.py and it works only if the site module is imported so it should be used in the interpreter only. It is like a synonym of quit() to make the Python more user-friendly. It too gives a message when printed:Example:# Python program to demonstrate# exit() for i in range(10): # If the value of i becomes # 5 then the program is forced # to exit if i == 5: # prints the exit message print(exit) exit() print(i)Output:0
1
2
3
4
Use exit() or Ctrl-D (i.e. EOF) to exit
sys.exit([arg])Unlike quit() and exit(), sys.exit() is considered good to be used in production code for the sys module is always available. The optional argument arg can be an integer giving the exit or another type of object. If it is an integer, zero is considered “successful termination”.Note: A string can also be passed to the sys.exit() method.Example – A program which stops execution if age is less than 18.# Python program to demonstrate# sys.exit() import sys age = 17 if age < 18: # exits the program sys.exit("Age less than 18") else: print("Age is not less than 18")Output:An exception has occurred, use %tb to see the full traceback.
SystemExit: Age less than 18
os._exit(n)os._exit() method in Python is used to exit the process with specified status without calling cleanup handlers, flushing stdio buffers, etc.Note: This method is normally used in child process after os.fork() system call. The standard way to exit the process is sys.exit(n) method.# Python program to explain os._exit() method # importing os module import os # Create a child process # using os.fork() method pid = os.fork() # pid greater than 0 # indicates the parent process if pid > 0: print("\nIn parent process") # Wait for the completion # of child process and # get its pid and # exit status indication using # os.wait() method info = os.waitpid(pid, 0) # os.waitpid() method returns a tuple # first attribute represents child's pid # while second one represents # exit status indication # Get the Exit code # used by the child process # in os._exit() method # firstly check if # os.WIFEXITED() is True or not if os.WIFEXITED(info[1]) : code = os.WEXITSTATUS(info[1]) print("Child's exit code:", code) else : print("In child process") print("Process ID:", os.getpid()) print("Hello ! Geeks") print("Child exiting..") # Exit with status os.EX_OK # using os._exit() method # The value of os.EX_OK is 0 os._exit(os.EX_OK)Output:In child process
Process ID: 25491
Hello ! Geeks
Child exiting..
In parent process
Child's exit code: 0
quit()It works only if the site module is imported so it should not be used in production code. Production code means the code is being used by the intended audience in a real-world situation. This function should only be used in the interpreter.It raises the SystemExit exception behind the scenes. If you print it, it will give a message:Example:# Python program to demonstrate# quit() for i in range(10): # If the value of i becomes # 5 then the program is forced # to quit if i == 5: # prints the quit message print(quit) quit() print(i)Output:0
1
2
3
4
Use quit() or Ctrl-D (i.e. EOF) to exit
It works only if the site module is imported so it should not be used in production code. Production code means the code is being used by the intended audience in a real-world situation. This function should only be used in the interpreter.
It raises the SystemExit exception behind the scenes. If you print it, it will give a message:
Example:
# Python program to demonstrate# quit() for i in range(10): # If the value of i becomes # 5 then the program is forced # to quit if i == 5: # prints the quit message print(quit) quit() print(i)
Output:
0
1
2
3
4
Use quit() or Ctrl-D (i.e. EOF) to exit
exit()exit() is defined in site.py and it works only if the site module is imported so it should be used in the interpreter only. It is like a synonym of quit() to make the Python more user-friendly. It too gives a message when printed:Example:# Python program to demonstrate# exit() for i in range(10): # If the value of i becomes # 5 then the program is forced # to exit if i == 5: # prints the exit message print(exit) exit() print(i)Output:0
1
2
3
4
Use exit() or Ctrl-D (i.e. EOF) to exit
exit() is defined in site.py and it works only if the site module is imported so it should be used in the interpreter only. It is like a synonym of quit() to make the Python more user-friendly. It too gives a message when printed:
Example:
# Python program to demonstrate# exit() for i in range(10): # If the value of i becomes # 5 then the program is forced # to exit if i == 5: # prints the exit message print(exit) exit() print(i)
Output:
0
1
2
3
4
Use exit() or Ctrl-D (i.e. EOF) to exit
sys.exit([arg])Unlike quit() and exit(), sys.exit() is considered good to be used in production code for the sys module is always available. The optional argument arg can be an integer giving the exit or another type of object. If it is an integer, zero is considered “successful termination”.Note: A string can also be passed to the sys.exit() method.Example – A program which stops execution if age is less than 18.# Python program to demonstrate# sys.exit() import sys age = 17 if age < 18: # exits the program sys.exit("Age less than 18") else: print("Age is not less than 18")Output:An exception has occurred, use %tb to see the full traceback.
SystemExit: Age less than 18
Unlike quit() and exit(), sys.exit() is considered good to be used in production code for the sys module is always available. The optional argument arg can be an integer giving the exit or another type of object. If it is an integer, zero is considered “successful termination”.
Note: A string can also be passed to the sys.exit() method.
Example – A program which stops execution if age is less than 18.
# Python program to demonstrate# sys.exit() import sys age = 17 if age < 18: # exits the program sys.exit("Age less than 18") else: print("Age is not less than 18")
Output:
An exception has occurred, use %tb to see the full traceback.
SystemExit: Age less than 18
os._exit(n)os._exit() method in Python is used to exit the process with specified status without calling cleanup handlers, flushing stdio buffers, etc.Note: This method is normally used in child process after os.fork() system call. The standard way to exit the process is sys.exit(n) method.# Python program to explain os._exit() method # importing os module import os # Create a child process # using os.fork() method pid = os.fork() # pid greater than 0 # indicates the parent process if pid > 0: print("\nIn parent process") # Wait for the completion # of child process and # get its pid and # exit status indication using # os.wait() method info = os.waitpid(pid, 0) # os.waitpid() method returns a tuple # first attribute represents child's pid # while second one represents # exit status indication # Get the Exit code # used by the child process # in os._exit() method # firstly check if # os.WIFEXITED() is True or not if os.WIFEXITED(info[1]) : code = os.WEXITSTATUS(info[1]) print("Child's exit code:", code) else : print("In child process") print("Process ID:", os.getpid()) print("Hello ! Geeks") print("Child exiting..") # Exit with status os.EX_OK # using os._exit() method # The value of os.EX_OK is 0 os._exit(os.EX_OK)Output:In child process
Process ID: 25491
Hello ! Geeks
Child exiting..
In parent process
Child's exit code: 0
os._exit() method in Python is used to exit the process with specified status without calling cleanup handlers, flushing stdio buffers, etc.
Note: This method is normally used in child process after os.fork() system call. The standard way to exit the process is sys.exit(n) method.
# Python program to explain os._exit() method # importing os module import os # Create a child process # using os.fork() method pid = os.fork() # pid greater than 0 # indicates the parent process if pid > 0: print("\nIn parent process") # Wait for the completion # of child process and # get its pid and # exit status indication using # os.wait() method info = os.waitpid(pid, 0) # os.waitpid() method returns a tuple # first attribute represents child's pid # while second one represents # exit status indication # Get the Exit code # used by the child process # in os._exit() method # firstly check if # os.WIFEXITED() is True or not if os.WIFEXITED(info[1]) : code = os.WEXITSTATUS(info[1]) print("Child's exit code:", code) else : print("In child process") print("Process ID:", os.getpid()) print("Hello ! Geeks") print("Child exiting..") # Exit with status os.EX_OK # using os._exit() method # The value of os.EX_OK is 0 os._exit(os.EX_OK)
Output:
In child process
Process ID: 25491
Hello ! Geeks
Child exiting..
In parent process
Child's exit code: 0
Among above four exit functions, sys.exit() is preferred mostly, because the exit() and quit() functions cannot be used in production code while os._exit() is for special cases only when immediate exit is required.
python-utility
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": 25819,
"s": 25791,
"text": "\n31 Dec, 2019"
},
{
"code": null,
"e": 26146,
"s": 25819,
"text": "The functions quit(), exit(), sys.exit() and os._exit() have almost same functionality as they raise the SystemExit exception by which the Python interpreter exits... |
SELECT INTO statement in SQL - GeeksforGeeks | 13 Aug, 2019
SELECT INTO statement in SQL is generally used for bulk copy purposes. We could copy the whole data from one table into another table using a single command.
Note:The queries are executed in SQL SERVER and they may not work in many online SQL editors so better use an offline editor.
Syntax:
SELECT column1, column2..... INTO TARGET_TABLE from SOURCE_TABLE
TARGET_TABLE should have the same schema and data types as that of SOURCE_TABLE.
Let’s first create a table GFG_Employees:
create table GFG_Employees
(
id int,
name varchar(20),
email varchar(max),
department varchar(20)
) ;
insert into GFG_EMPLOyees values(1, 'Jessie', 'jessie23@gmail.com', 'Development');
insert into GFG_EMPLOyees values(2, 'Praveen', 'praveen_dagger@yahoo.com', 'HR');
insert into GFG_EMPLOyees values(3, 'Bisa', 'dragonBall@gmail.com', 'Sales');
insert into GFG_EMPLOyees values(4, 'Rithvik', 'msvv@hotmail.com', 'IT');
insert into GFG_EMPLOyees values(5, 'Suraj', 'srjsunny@gmail.com', 'Quality Assurance');
insert into GFG_EMPLOyees values(6, 'Om', 'OmShukla@yahoo.com', 'IT');
insert into GFG_EMPLOyees values(7, 'Naruto', 'uzumaki@konoha.com', 'Development');
Query-1: To copy all the data from GFG_Employees into backUpEmployee table.
SELECT * INTO backUpEmployee from GFG_Employees;
Output:
Select * from backUpEmployee;
Query-2: Use ‘where’ clause to copy only some rows from GFG_Employees into backUp2 table.
SELECT * INTO backUp2 from GFG_Employees where department in ('Development', 'IT');
Output:
Select * from backUp2;
Query-3: To copy only some columns from GFG_Employees into backUp3 table specify them in the query.
SELECT id, name INTO backUp3 from GFG_Employees;
Output:
Select * from backUp3;
INSERT INTO SELECT vs SELECT INTO:Both the statements could be used to copy data from one table to another. But INSERT INTO SELECT could be used only if the target table exists whereas SELECT INTO statement could be used even if the target table doesn’t exist as it creates the target table if it doesn’t exist.
INSERT INTO tempTable select * from GFG_Employees;
HERE table tempTable should be present or created beforehand else throw an error.
SELECT * INTO backUpTable from GFG_Employees;
Here it’s not necessary to exist before as SELECT INTO creates table if the table doesn’t exist and then copies the data.
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
Introduction of B-Tree
CTE in SQL
Difference between Clustered and Non-clustered index
Data Preprocessing in Data Mining
How to find Nth highest salary from a table
SQL Interview Questions
SQL | ALTER (RENAME)
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL? | [
{
"code": null,
"e": 25127,
"s": 25099,
"text": "\n13 Aug, 2019"
},
{
"code": null,
"e": 25285,
"s": 25127,
"text": "SELECT INTO statement in SQL is generally used for bulk copy purposes. We could copy the whole data from one table into another table using a single command."
},... |
Tail command in Linux with examples - GeeksforGeeks | 19 Feb, 2021
It is the complementary of head command.The tail command, as the name implies, print the last N number of data of the given input. By default it prints the last 10 lines of the specified files. If more than one file name is provided then data from each file is precedes by its file name.
Syntax:
tail [OPTION]... [FILE]...
Let us consider two files having name state.txt and capital.txt contains all the names of the Indian states and capitals respectively.
$ cat state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Goa
Gujarat
Haryana
Himachal Pradesh
Jammu and Kashmir
Jharkhand
Karnataka
Kerala
Madhya Pradesh
Maharashtra
Manipur
Meghalaya
Mizoram
Nagaland
Odisha
Punjab
Rajasthan
Sikkim
Tamil Nadu
Telangana
Tripura
Uttar Pradesh
Uttarakhand
West Bengal
Without any option it display only the last 10 lines of the file specified.Example:
$ tail state.txt
Odisha
Punjab
Rajasthan
Sikkim
Tamil Nadu
Telangana
Tripura
Uttar Pradesh
Uttarakhand
West Bengal
Options:
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.
1. -n num: Prints the last ‘num’ lines instead of last 10 lines. num is mandatory to be specified in command otherwise it displays an error. This command can also be written as without symbolizing ‘n’ character but ‘-‘ sign is mandatory.
$ tail -n 3 state.txt
Uttar Pradesh
Uttarakhand
West Bengal
OR
$ tail -3 state.txt
Uttar Pradesh
Uttarakhand
West Bengal
Tail command also comes with an ‘+’ option which is not present in the head command. With this option tail command prints the data starting from specified line number of the file instead of end. For command: tail +n file_name, data will start printing from line number ‘n’ till the end of the file specified.
$ tail +25 state.txt
Telangana
Tripura
Uttar Pradesh
Uttarakhand
West Bengal
2. -c num: Prints the last ‘num’ bytes from the file specified. Newline count as a single character, so if tail prints out a newline, it will count it as a byte. In this option it is mandatory to write -c followed by positive or negative num depends upon the requirement. By +num, it display all the data after skipping num bytes from starting of the specified file and by -num, it display the last num bytes from the file specified.Note: Without positive or negative sign before num, command will display the last num bytes from the file specified.
With negative num
$ tail -c -6 state.txt
Bengal
OR
$ tail -c 6 state.txt
Bengal
With positive num
$ tail -c +263 state.txt
Nadu
Telangana
Tripura
Uttar Pradesh
Uttarakhand
3. -q: It is used if more than 1 file is given. Because of this command, data from each file is not precedes by its file name.
Without using -q option
$ tail state.txt capital.txt
state.txt
Odisha
Punjab
Rajasthan
Sikkim
Tamil Nadu
Telangana
Tripura
Uttar Pradesh
Uttarakhand
West Bengal
capital.txt
Dispur
Patna
Raipur
Panaji
Gandhinagar
Chandigarh
Shimla
Srinagar
Ranchi
With using -q option
$ tail -q state.txt capital.txt
Odisha
Punjab
Rajasthan
Sikkim
Tamil Nadu
Telangana
Tripura
Uttar Pradesh
Uttarakhand
West BengalDispur
Patna
Raipur
Panaji
Gandhinagar
Chandigarh
Shimla
Srinagar
Ranchi
Bengaluru
4. -f: This option is mainly used by system administration to monitor the growth of the log files written by many Unix program as they are running. This option shows the last ten lines of a file and will update when new lines are added. As new lines are written to the log, the console will update with the new lines. The prompt doesn’t return even after work is over so, we have to use the interrupt key to abort this command. In general, the applications writes error messages to log files. You can use the -f option to check for the error messages as and when they appear in the log file.
$ tail -f logfile
5. -v: By using this option, data from the specified file is always preceded by its file name.
$ tail -v state.txt
==> state.txt <==
Odisha
Punjab
Rajasthan
Sikkim
Tamil Nadu
Telangana
Tripura
Uttar Pradesh
Uttarakhand
West Bengal
6. –version: This option is used to display the version of tail which is currently running on your system.
$ tail --version
tail (GNU coreutils) 8.26
Packaged by Cygwin (8.26-1)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later .
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Written by Paul Rubin, David MacKenzie, Ian Lance Taylor,
and Jim Meyering.
Applications of tail Command
1. How to use tail with pipes(|): The tail command can be piped with many other commands of the unix. In the following example output of the tail command is given as input to the sort command with -r option to sort the last 7 state names coming from file state.txt in the reverse order.
$ tail -n 7 state.txt
Sikkim
Tamil Nadu
Telangana
Tripura
Uttar Pradesh
Uttarakhand
West Bengal
$ tail -n 7 state.txt | sort -r
West Bengal
Uttarakhand
Uttar Pradesh
Tripura
Telangana
Tamil Nadu
Sikkim
It can also be piped with one or more filters for additional processing. Like in the following example, we are using cat, head and tail command and whose output is stored in the file name list.txt using directive(>).
$ cat state.txt | head -n 20 | tail -n 5 > list.txt
$ cat list.txt
Manipur
Meghalaya
Mizoram
Nagaland
Odisha
What is happening in this command let’s try to explore it. First cat command gives all the data present in the file state.txt and after that pipe transfers all the output coming from cat command to the head command. Head command gives all the data from start(line number 1) to the line number 20 and pipe transfer all the output coming from head command to tail command. Now, tail command gives last 5 lines of the data and the output goes to the file name list.txt via directive operator.2. Print line between M and N linesYouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=1pD28tFgAb8" 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 Akash Gupta. 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-text-processing-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
UDP Server-Client implementation in C
Cat command in Linux with examples
touch command in Linux with Examples
echo command in Linux with Examples
Compiling with g++
scp command in Linux with Examples
ps command in Linux with Examples | [
{
"code": null,
"e": 25249,
"s": 25221,
"text": "\n19 Feb, 2021"
},
{
"code": null,
"e": 25537,
"s": 25249,
"text": "It is the complementary of head command.The tail command, as the name implies, print the last N number of data of the given input. By default it prints the last 10... |
Check for balanced parentheses in an expression | O(1) space - GeeksforGeeks | 06 Oct, 2021
Given a string of length n having parentheses in it, your task is to find whether given string has balanced parentheses or not. Please note there is constraint on space i.e. we are allowed to use only O(1) extra space.Also See : Check for balanced parenthesesExamples:
Input : (())[]
Output : Yes
Input : ))(({}{
Output : No
If k = 1, then we will simply keep a count variable c = 0, whenever we encounter an opening parentheses we will increment c and whenever we encounter a closing parentheses we will reduce the count of c, At any stage we shouldn’t have c < 0 and at the end we must have c = 0 for string to be balanced. Following is the idea of our algorithm for this problem. For any opening bracket say ‘[‘ we find its matching closing bracket ‘]’. Let’s say index of ‘[‘ was i and index of ‘]’ was j then following conditions must be true:
i < jfor all k such that i < k < j, for all the opening parentheses(index-k) it’s matching closing parentheses x must satisfy k < x < j and for all the closing parentheses(index-k) it’s matching opening parentheses x must satisfy i < x < k
i < j
for all k such that i < k < j, for all the opening parentheses(index-k) it’s matching closing parentheses x must satisfy k < x < j and for all the closing parentheses(index-k) it’s matching opening parentheses x must satisfy i < x < k
C++
Java
Python 3
C#
PHP
Javascript
// C++ code to check balanced parentheses with// O(1) space.#include <stdio.h>#include <stdlib.h> // Function1 to match closing bracketint matchClosing(char X[], int start, int end, char open, char close){ int c = 1; int i = start + 1; while (i <= end) { if (X[i] == open) c++; else if (X[i] == close) c--; if (c == 0) return i; i++; } return i;} // Function1 to match opening bracketint matchingOpening(char X[], int start, int end, char open, char close){ int c = -1; int i = end - 1; while (i >= start) { if (X[i] == open) c++; else if (X[i] == close) c--; if (c == 0) return i; i--; } return -1;} // Function to check balanced parenthesesbool isBalanced(char X[], int n){ // helper variables int i, j, k, x, start, end; for (i = 0; i < n; i++) { // Handling case of opening parentheses if (X[i] == '(') j = matchClosing(X, i, n - 1, '(', ')'); else if (X[i] == '{') j = matchClosing(X, i, n - 1, '{', '}'); else if (X[i] == '[') j = matchClosing(X, i, n - 1, '[', ']'); // Handling case of closing parentheses else { if (X[i] == ')') j = matchingOpening(X, 0, i, '(', ')'); else if (X[i] == '}') j = matchingOpening(X, 0, i, '{', '}'); else if (X[i] == ']') j = matchingOpening(X, 0, i, '[', ']'); // If corresponding matching // opening parentheses doesn't // lie in given interval return 0 if (j < 0 || j >= i) return false; // else continue continue; } // If corresponding closing parentheses // doesn't lie in given interval // return 0 if (j >= n || j < 0) return false; // if found, now check for each // opening and closing parentheses // in this interval start = i; end = j; for (k = start + 1; k < end; k++) { if (X[k] == '(') { x = matchClosing(X, k, end, '(', ')'); if (!(k < x && x < end)) { return false; } } else if (X[k] == ')') { x = matchingOpening(X, start, k, '(', ')'); if (!(start < x && x < k)) { return false; } } if (X[k] == '{') { x = matchClosing(X, k, end, '{', '}'); if (!(k < x && x < end)) { return false; } } else if (X[k] == '}') { x = matchingOpening(X, start, k, '{', '}'); if (!(start < x && x < k)) { return false; } } if (X[k] == '[') { x = matchClosing(X, k, end, '[', ']'); if (!(k < x && x < end)) { return false; } } else if (X[k] == ']') { x = matchingOpening(X, start, k, '[', ']'); if (!(start < x && x < k)) { return false; } } } } return true;} // Driver Codeint main(){ char X[] = "[()]()"; int n = 6; if (isBalanced(X, n)) printf("Yes\n"); else printf("No\n"); char Y[] = "[[()]])"; n = 7; if (isBalanced(Y, n)) printf("Yes\n"); else printf("No\n"); return 0;}
// Java code to check balanced parentheses with// O(1) space. class GFG { // Function1 to match closing bracket static int matchClosing(char X[], int start, int end, char open, char close) { int c = 1; int i = start + 1; while (i <= end) { if (X[i] == open) { c++; } else if (X[i] == close) { c--; } if (c == 0) { return i; } i++; } return i; } // Function1 to match opening bracket static int matchingOpening(char X[], int start, int end, char open, char close) { int c = -1; int i = end - 1; while (i >= start) { if (X[i] == open) { c++; } else if (X[i] == close) { c--; } if (c == 0) { return i; } i--; } return -1; } // Function to check balanced parentheses static boolean isBalanced(char X[], int n) { // helper variables int i, j = 0, k, x, start, end; for (i = 0; i < n; i++) { // Handling case of opening parentheses if (X[i] == '(') { j = matchClosing(X, i, n - 1, '(', ')'); } else if (X[i] == '{') { j = matchClosing(X, i, n - 1, '{', '}'); } else if (X[i] == '[') { j = matchClosing(X, i, n - 1, '[', ']'); } // Handling case of closing parentheses else { if (X[i] == ')') { j = matchingOpening(X, 0, i, '(', ')'); } else if (X[i] == '}') { j = matchingOpening(X, 0, i, '{', '}'); } else if (X[i] == ']') { j = matchingOpening(X, 0, i, '[', ']'); } // If corresponding matching // opening parentheses doesn't // lie in given interval return 0 if (j < 0 || j >= i) { return false; } // else continue continue; } // If corresponding closing parentheses // doesn't lie in given interval // return 0 if (j >= n || j < 0) { return false; } // if found, now check for each // opening and closing parentheses // in this interval start = i; end = j; for (k = start + 1; k < end; k++) { if (X[k] == '(') { x = matchClosing(X, k, end, '(', ')'); if (!(k < x && x < end)) { return false; } } else if (X[k] == ')') { x = matchingOpening(X, start, k, '(', ')'); if (!(start < x && x < k)) { return false; } } if (X[k] == '{') { x = matchClosing(X, k, end, '{', '}'); if (!(k < x && x < end)) { return false; } } else if (X[k] == '}') { x = matchingOpening(X, start, k, '{', '}'); if (!(start < x && x < k)) { return false; } } if (X[k] == '[') { x = matchClosing(X, k, end, '[', ']'); if (!(k < x && x < end)) { return false; } } else if (X[k] == ']') { x = matchingOpening(X, start, k, '[', ']'); if (!(start < x && x < k)) { return false; } } } } return true; } // Driver Code public static void main(String[] args) { char X[] = "[()]()".toCharArray(); int n = 6; if (isBalanced(X, n)) System.out.printf("Yes\n"); else System.out.printf("No\n"); char Y[] = "[[()]])".toCharArray(); n = 7; if (isBalanced(Y, n)) System.out.printf("Yes\n"); else System.out.printf("No\n"); }}//this code contributed by Rajput-Ji
# Python 3 code to check balanced# parentheses with O(1) space. # Function1 to match closing bracketdef matchClosing(X, start, end, open, close): c = 1 i = start + 1 while (i <= end): if (X[i] == open): c += 1 elif (X[i] == close): c -= 1 if (c == 0): return i i += 1 return i # Function1 to match opening bracketdef matchingOpening(X, start, end, open, close): c = -1 i = end - 1 while (i >= start): if (X[i] == open): c += 1 elif (X[i] == close): c -= 1 if (c == 0): return i i -= 1 return -1 # Function to check balanced# parenthesesdef isBalanced(X, n): for i in range(n): # Handling case of opening # parentheses if (X[i] == '('): j = matchClosing(X, i, n - 1, '(', ')') elif (X[i] == '{'): j = matchClosing(X, i, n - 1, '{', '}') elif (X[i] == '['): j = matchClosing(X, i, n - 1, '[', ']') # Handling case of closing # parentheses else : if (X[i] == ')'): j = matchingOpening(X, 0, i, '(', ')') elif (X[i] == '}'): j = matchingOpening(X, 0, i, '{', '}') elif (X[i] == ']'): j = matchingOpening(X, 0, i, '[', ']') # If corresponding matching opening # parentheses doesn't lie in given # interval return 0 if (j < 0 or j >= i): return False # else continue continue # If corresponding closing parentheses # doesn't lie in given interval, return 0 if (j >= n or j < 0): return False # if found, now check for each opening and # closing parentheses in this interval start = i end = j for k in range(start + 1, end) : if (X[k] == '(') : x = matchClosing(X, k, end, '(', ')') if (not(k < x and x < end)): return False elif (X[k] == ')'): x = matchingOpening(X, start, k, '(', ')') if (not(start < x and x < k)): return False if (X[k] == '{'): x = matchClosing(X, k, end, '{', '}') if (not(k < x and x < end)): return False elif (X[k] == '}'): x = matchingOpening(X, start, k, '{', '}') if (not(start < x and x < k)): return False if (X[k] == '['): x = matchClosing(X, k, end, '[', ']') if (not(k < x and x < end)): return False elif (X[k] == ']'): x = matchingOpening(X, start, k, '[', ']') if (not(start < x and x < k)): return False return True # Driver Codeif __name__ == "__main__": X = "[()]()" n = 6 if (isBalanced(X, n)): print("Yes") else: print("No") Y = "[[()]])" n = 7 if (isBalanced(Y, n)): print("Yes") else: print("No") # This code is contributed by ita_c
// C# code to check balanced parentheses with// O(1) space.using System;public class GFG { // Function1 to match closing bracket static int matchClosing(char []X, int start, int end, char open, char close) { int c = 1; int i = start + 1; while (i <= end) { if (X[i] == open) { c++; } else if (X[i] == close) { c--; } if (c == 0) { return i; } i++; } return i; } // Function1 to match opening bracket static int matchingOpening(char []X, int start, int end, char open, char close) { int c = -1; int i = end - 1; while (i >= start) { if (X[i] == open) { c++; } else if (X[i] == close) { c--; } if (c == 0) { return i; } i--; } return -1; } // Function to check balanced parentheses static bool isBalanced(char []X, int n) { // helper variables int i, j = 0, k, x, start, end; for (i = 0; i < n; i++) { // Handling case of opening parentheses if (X[i] == '(') { j = matchClosing(X, i, n - 1, '(', ')'); } else if (X[i] == '{') { j = matchClosing(X, i, n - 1, '{', '}'); } else if (X[i] == '[') { j = matchClosing(X, i, n - 1, '[', ']'); } // Handling case of closing parentheses else { if (X[i] == ')') { j = matchingOpening(X, 0, i, '(', ')'); } else if (X[i] == '}') { j = matchingOpening(X, 0, i, '{', '}'); } else if (X[i] == ']') { j = matchingOpening(X, 0, i, '[', ']'); } // If corresponding matching // opening parentheses doesn't // lie in given interval return 0 if (j < 0 || j >= i) { return false; } // else continue continue; } // If corresponding closing parentheses // doesn't lie in given interval // return 0 if (j >= n || j < 0) { return false; } // if found, now check for each // opening and closing parentheses // in this interval start = i; end = j; for (k = start + 1; k < end; k++) { if (X[k] == '(') { x = matchClosing(X, k, end, '(', ')'); if (!(k < x && x < end)) { return false; } } else if (X[k] == ')') { x = matchingOpening(X, start, k, '(', ')'); if (!(start < x && x < k)) { return false; } } if (X[k] == '{') { x = matchClosing(X, k, end, '{', '}'); if (!(k < x && x < end)) { return false; } } else if (X[k] == '}') { x = matchingOpening(X, start, k, '{', '}'); if (!(start < x && x < k)) { return false; } } if (X[k] == '[') { x = matchClosing(X, k, end, '[', ']'); if (!(k < x && x < end)) { return false; } } else if (X[k] == ']') { x = matchingOpening(X, start, k, '[', ']'); if (!(start < x && x < k)) { return false; } } } } return true; } // Driver Code public static void Main() { char []X = "[()]()".ToCharArray(); int n = 6; if (isBalanced(X, n)) Console.Write("Yes\n"); else Console.Write("No\n"); char []Y = "[[()]])".ToCharArray(); n = 7; if (isBalanced(Y, n)) Console.Write("Yes\n"); else Console.Write("No\n"); }}// This code contributed by Rajput-Ji
<?php// PHP code to check balanced parentheses// with O(1) space. // Function1 to match closing bracketfunction matchClosing($X, $start, $end, $open, $close){ $c = 1; $i = $start + 1; while ($i <= $end) { if ($X[$i] == $open) { $c++; } else if ($X[$i] == $close) { $c--; } if ($c == 0) { return $i; } $i++; } return $i;} // Function1 to match opening bracketfunction matchingOpening($X, $start, $end, $open, $close){ $c = -1; $i = $end - 1; while ($i >= $start) { if ($X[$i] == $open) { $c++; } else if ($X[$i] == $close) { $c--; } if ($c == 0) { return $i; } $i--; } return -1;} // Function to check balanced parenthesesfunction isBalanced($X, $n){ // helper variables $i; $j = 0; $k; $x; $start; $end; for ($i = 0; $i < $n; $i++) { // Handling case of opening parentheses if ($X[$i] == '(') { $j = matchClosing($X, $i, $n - 1, '(', ')'); } else if ($X[$i] == '{') { $j = matchClosing($X, $i, $n - 1, '{', '}'); } else if ($X[$i] == '[') { $j = matchClosing($X, $i, $n - 1, '[', ']'); } // Handling case of closing parentheses else { if ($X[$i] == ')') { $j = matchingOpening($X, 0, $i, '(', ')'); } else if ($X[$i] == '}') { $j = matchingOpening($X, 0, $i, '{', '}'); } else if ($X[$i] == ']') { $j = matchingOpening($X, 0, $i, '[', ']'); } // If corresponding matching opening parentheses // doesn't lie in given interval return 0 if ($j < 0 || $j >= $i) { return false; } // else continue continue; } // If corresponding closing parentheses // doesn't lie in given interval // return 0 if ($j >= $n || $j < 0) { return false; } // if found, now check for each opening // and closing parentheses in this interval $start = $i; $end = $j; for ($k = $start + 1; $k < $end; $k++) { if ($X[$k] == '(') { $x = matchClosing($X, $k, $end, '(', ')'); if (!($k < $x && $x < $end)) { return false; } } else if ($X[$k] == ')') { $x = matchingOpening($X, $start, $k, '(', ')'); if (!($start < $x && $x < $k)) { return false; } } if ($X[$k] == '{') { $x = matchClosing($X, $k, $end, '{', '}'); if (!($k < $x && $x < $end)) { return false; } } else if ($X[$k] == '}') { $x = matchingOpening($X, $start, $k, '{', '}'); if (!($start < $x && $x < $k)) { return false; } } if ($X[$k] == '[') { $x = matchClosing($X, $k, $end, '[', ']'); if (!($k < $x && $x < $end)) { return false; } } else if ($X[$k] == ']') { $x = matchingOpening($X, $start, $k, '[', ']'); if (!($start < $x && $x < $k)) { return false; } } } } return true;} // Driver Code$X = str_split("[()]()");$n = 6;if (isBalanced($X, $n)) echo("Yes\n");else echo("No\n"); $Y = str_split("[[()]])");$n = 7;if (isBalanced($Y, $n)) echo("Yes\n");else echo("No\n"); // This code contributed by Mukul Singh?>
<script>// Javascript code to check balanced parentheses with// O(1) space. // Function1 to match closing bracket function matchClosing(X,start,end,open,close) { let c = 1; let i = start + 1; while (i <= end) { if (X[i] == open) { c++; } else if (X[i] == close) { c--; } if (c == 0) { return i; } i++; } return i; } // Function1 to match opening bracket function matchingOpening(X,start,end,open,close) { let c = -1; let i = end - 1; while (i >= start) { if (X[i] == open) { c++; } else if (X[i] == close) { c--; } if (c == 0) { return i; } i--; } return -1; } // Function to check balanced parentheses function isBalanced(X,n) { // helper variables let i, j = 0, k, x, start, end; for (i = 0; i < n; i++) { // Handling case of opening parentheses if (X[i] == '(') { j = matchClosing(X, i, n - 1, '(', ')'); } else if (X[i] == '{') { j = matchClosing(X, i, n - 1, '{', '}'); } else if (X[i] == '[') { j = matchClosing(X, i, n - 1, '[', ']'); } // Handling case of closing parentheses else { if (X[i] == ')') { j = matchingOpening(X, 0, i, '(', ')'); } else if (X[i] == '}') { j = matchingOpening(X, 0, i, '{', '}'); } else if (X[i] == ']') { j = matchingOpening(X, 0, i, '[', ']'); } // If corresponding matching // opening parentheses doesn't // lie in given interval return 0 if (j < 0 || j >= i) { return false; } // else continue continue; } // If corresponding closing parentheses // doesn't lie in given interval // return 0 if (j >= n || j < 0) { return false; } // if found, now check for each // opening and closing parentheses // in this interval start = i; end = j; for (k = start + 1; k < end; k++) { if (X[k] == '(') { x = matchClosing(X, k, end, '(', ')'); if (!(k < x && x < end)) { return false; } } else if (X[k] == ')') { x = matchingOpening(X, start, k, '(', ')'); if (!(start < x && x < k)) { return false; } } if (X[k] == '{') { x = matchClosing(X, k, end, '{', '}'); if (!(k < x && x < end)) { return false; } } else if (X[k] == '}') { x = matchingOpening(X, start, k, '{', '}'); if (!(start < x && x < k)) { return false; } } if (X[k] == '[') { x = matchClosing(X, k, end, '[', ']'); if (!(k < x && x < end)) { return false; } } else if (X[k] == ']') { x = matchingOpening(X, start, k, '[', ']'); if (!(start < x && x < k)) { return false; } } } } return true; } // Driver Code let X="[()]()".split(""); let n = 6; if (isBalanced(X, n)) document.write("Yes<br>"); else document.write("No<br>"); let Y = "[[()]])".split(""); n = 7; if (isBalanced(Y, n)) document.write("Yes<br>"); else document.write("No<br>"); // This code is contributed by avanitrachhadiya2155</script>
Yes
No
Time Complexity: O(n3)
Auxiliary Space: O(1)
Rajput-Ji
ukasp
Code_Mech
Akanksha_Rai
avanitrachhadiya2155
arorakashish0911
C-String
expression-evaluation
Parentheses-Problems
Arrays
Strings
Arrays
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Longest Common Subsequence | DP-4
Python program to check if a string is palindrome or not | [
{
"code": null,
"e": 26449,
"s": 26421,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 26720,
"s": 26449,
"text": "Given a string of length n having parentheses in it, your task is to find whether given string has balanced parentheses or not. Please note there is constraint on ... |
How to hide elements defined as variables in jQuery ? - GeeksforGeeks | 07 Apr, 2021
In this article, we will learn how to hide elements defined as variables in jQuery. These can be done using two approaches.
Approach 1: In this approach, we will first select the element that has to be hidden and then assign it to a variable. We will then call the hide() method on the variable. This method will hide the element from the page.
Example:
HTML
<html><head> <script src="https://code.jquery.com/jquery-3.6.0.js"> </script> <script> $(document).ready(function () { $("button").click(function () { // Getting the element with the id // of "dsa" in a variable let dsaGFG = $("#dsa"); // Hiding the element using the // hide() method dsaGFG.hide(); }) }); </script></head> <body> <h1 style="color: green;"> GeeksforGeeks </h1> <p id="faang">FAANG</p> <p id="dsa">DSA</p> <p id="cp">CP</p> <p id="algo">ALGO</p> <button>Hide Element</button></body></html>
Output:
Approach 2: In this approach, we will first select the element that has to be hidden and then assign it to a variable. We will then call the addClass() method on the variable. This will add a CSS class that we will create next. This CSS class will contain the display property that is set to none, effectively hiding the element.
Example:
HTML
<html><head> <style> /* Define the class to be added */ .hiddenClass { /* Setting the display to none hides the element */ display: none; } </style> <script src="https://code.jquery.com/jquery-3.6.0.js"> </script> <script> $(document).ready(function () { $("button").click(function () { // Getting the element with the id // of "cp" in a variable let cpGFG = $("#cp"); // Hiding the element by adding a // class using the addClass() method cpGFG.addClass("hiddenClass"); }) }); </script></head><body> <h1 style="color: green;"> GeeksforGeeks </h1> <p id="faang">FAANG</p> <p id="dsa">DSA</p> <p id="cp">CP</p> <p id="algo">ALGO</p> <button>Hide Element</button></body></html>
Output:
CSS-Properties
HTML-Tags
jQuery-Methods
jQuery-Questions
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show and Hide div elements using radio buttons?
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
jQuery | removeAttr() with Examples
How to get the value in an input text box using jQuery ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 26954,
"s": 26926,
"text": "\n07 Apr, 2021"
},
{
"code": null,
"e": 27078,
"s": 26954,
"text": "In this article, we will learn how to hide elements defined as variables in jQuery. These can be done using two approaches."
},
{
"code": null,
"e": 27... |
JavaScript Object initializer - GeeksforGeeks | 08 Oct, 2021
Objects in JavaScript can be compared to real-life objects. They have properties and methods attached to them and properties are in the form of key-value pairs. Let us understand this with an example. In the real-world, a motorcycle is an object and it has properties like name, color, price, etc. It has some methods attached to it like start, brake, stop, etc. All motorcycles will have similar properties but the values will be different. This same concept is applied in programming and is known as Object Oriented Programming.
JavaScript objects can be initialized in various ways which are as follows.
Using object literalsUsing new Object() methodUsing Object.create() methodUsing constructor functions
Using object literals
Using new Object() method
Using Object.create() method
Using constructor functions
Let us understand all the methods –
Using Object Literals: Syntax:
var obj = { name: "value", .... }
Properties of JavaScript object can be accessed using a dot notation or bracket notation. For Example, obj.name or obj[‘name’] will give us the value.
Example:
Javascript
var person = { name: "Sarah", age: 20, gender: "female"};console.log(person);console.log(person.name + " is a " + person.age + " year old " + person.gender);console.log(person.name + " is a " + person.age + " year old " + person["gender"]);
Output:
Using new Object() method:
Syntax:
var obj = new Object();
obj.name = "value";
or
obj["name"] = "value";
The new Object() method will make a new JavaScript object whose properties can be initialized using dot or bracket notation.
Example:
Javascript
var Person = new Object();Person.name = "Sarah";Person['age'] = 20;Person.gender = "female"; console.log(Person);console.log(Person.name + " is a " + Person.age + " year old " + Person.gender);console.log(Person.name + " is a " + Person.age + " year old " + Person["gender"]);
Output:
Using Object.create() method:
Syntax:
var Obj = Object.create({});
Obj.name = "value";
or
Obj["name"] = "value";
The Object.create() method will make a new JavaScript Object whose properties can be initialized using dot or bracket notation.
Example:
Javascript
var Person = Object.create({})Person.name = "Sarah";Person["age"] = 20;Person.gender = "female"; console.log(Person);console.log(Person.name + " is a " + Person.age + " year old " + Person.gender);console.log(Person.name + " is a " + Person.age + " year old " + Person["gender"]);
Output:
Using Constructor functions:
Syntax:
function Obj(name) {
this.name = name;
}
var myobj = new Obj("my name");
In this method, constructor function is used to define the object and this is used to assign value to the properties. An instance of the object is created using new keyword.
Example:
Javascript
function Person(name, age, gender) { this.name = name; this.age = age; this.gender = gender; } var personOne = new Person("Sarah", 20, "gender"); console.log(personOne);console.log(personOne.name + " is a " + personOne.age + " year old " + personOne.gender);console.log(personOne.name + " is a " + personOne.age + " year old " + personOne["gender"]);
Output:
Supported Browser:
Chrome 1 and above
Edge 12 and above
Firefox 1 and above
Internet Explorer 1 and above
Opera 4 and above
Safari 1 and above
ysachin2314
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26545,
"s": 26517,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 27076,
"s": 26545,
"text": "Objects in JavaScript can be compared to real-life objects. They have properties and methods attached to them and properties are in the form of key-value pairs. Le... |
multimap::erase() in C++ STL - GeeksforGeeks | 18 Nov, 2020
multimap::erase() is a built-in function in C++ STL which is used to erase element from the container. It can be used to erase keys, elements at any specified position or a given range.Syntax for erasing a key:multimap_name.erase(key)
Parameters: The function accepts one mandatory parameter key which specifies the key to be erased in the multimap container.Return Value: The function does not return anything. It erases all the elements with the specified key.// C++ program to illustrate// multimap::erase(key)#include <bits/stdc++.h>using namespace std; int main(){ // initialize container multimap<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 2, 20 }); mp.insert({ 5, 50 }); // prints the elements cout << "The multimap before using erase() is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.begin(); itr != mp.end(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } // function to erase given keys mp.erase(1); mp.erase(2); // prints the elements cout << "\nThe multimap after applying erase() is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.crbegin(); itr != mp.crend(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } return 0;}Output:The multimap before using erase() is :
KEY ELEMENT
1 40
2 30
2 20
3 60
5 50
The multimap after applying erase() is :
KEY ELEMENT
5 50
3 60
Syntax for removing a position:multimap_name.erase(iterator position)
Parameters: The function accept one mandatory parameter position which specifies the iterator that is the reference to the position of the element to be erased.Return Value: The function does not returns anything.Program below illustrate the above syntax:// C++ program to illustrate// multimap::erase(position)#include <bits/stdc++.h>using namespace std; int main(){ // initialize container multimap<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 2, 20 }); mp.insert({ 5, 50 }); // prints the elements cout << "The multimap before using erase() is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.begin(); itr != mp.end(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } // function to erase given position auto it = mp.find(2); mp.erase(it); auto it1 = mp.find(5); mp.erase(it1); // prints the elements cout << "\nThe multimap after applying erase() is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.crbegin(); itr != mp.crend(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } return 0;}Output:The multimap before using erase() is :
KEY ELEMENT
1 40
2 30
2 20
3 60
5 50
The multimap after applying erase() is :
KEY ELEMENT
3 60
2 20
1 40
Syntax for erasing a given range:multimap_name.erase(iterator position1, iterator position2)
Parameters: The function accepts two mandatory parameters which are described below:position1 – specifies the iterator that is the reference to the element from which removal is to be done.position2 – specifies the iterator that is the reference to the element upto which removal is to be done.Return Value: The function does not returns anything. It removes all the elements in the given range of iterators.Program below illustrate the above syntax:// C++ program to illustrate// multimap::erase()#include <bits/stdc++.h>using namespace std; int main(){ // initialize container multimap<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 2, 20 }); mp.insert({ 5, 50 }); // prints the elements cout << "The multimap before using erase() is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.begin(); itr != mp.end(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } // function to erase in a given range // find() returns the iterator reference to // the position where the element is auto it1 = mp.find(2); auto it2 = mp.find(5); mp.erase(it1, it2); // prints the elements cout << "\nThe multimap after applying erase() is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.crbegin(); itr != mp.crend(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } return 0;}Output:The multimap before using erase() is :
KEY ELEMENT
1 40
2 30
2 20
3 60
5 50
The multimap after applying erase() is :
KEY ELEMENT
5 50
1 40
Syntax for erasing a key:multimap_name.erase(key)
Parameters: The function accepts one mandatory parameter key which specifies the key to be erased in the multimap container.Return Value: The function does not return anything. It erases all the elements with the specified key.// C++ program to illustrate// multimap::erase(key)#include <bits/stdc++.h>using namespace std; int main(){ // initialize container multimap<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 2, 20 }); mp.insert({ 5, 50 }); // prints the elements cout << "The multimap before using erase() is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.begin(); itr != mp.end(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } // function to erase given keys mp.erase(1); mp.erase(2); // prints the elements cout << "\nThe multimap after applying erase() is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.crbegin(); itr != mp.crend(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } return 0;}Output:The multimap before using erase() is :
KEY ELEMENT
1 40
2 30
2 20
3 60
5 50
The multimap after applying erase() is :
KEY ELEMENT
5 50
3 60
multimap_name.erase(key)
Parameters: The function accepts one mandatory parameter key which specifies the key to be erased in the multimap container.
Return Value: The function does not return anything. It erases all the elements with the specified key.
// C++ program to illustrate// multimap::erase(key)#include <bits/stdc++.h>using namespace std; int main(){ // initialize container multimap<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 2, 20 }); mp.insert({ 5, 50 }); // prints the elements cout << "The multimap before using erase() is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.begin(); itr != mp.end(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } // function to erase given keys mp.erase(1); mp.erase(2); // prints the elements cout << "\nThe multimap after applying erase() is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.crbegin(); itr != mp.crend(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } return 0;}
The multimap before using erase() is :
KEY ELEMENT
1 40
2 30
2 20
3 60
5 50
The multimap after applying erase() is :
KEY ELEMENT
5 50
3 60
Syntax for removing a position:multimap_name.erase(iterator position)
Parameters: The function accept one mandatory parameter position which specifies the iterator that is the reference to the position of the element to be erased.Return Value: The function does not returns anything.Program below illustrate the above syntax:// C++ program to illustrate// multimap::erase(position)#include <bits/stdc++.h>using namespace std; int main(){ // initialize container multimap<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 2, 20 }); mp.insert({ 5, 50 }); // prints the elements cout << "The multimap before using erase() is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.begin(); itr != mp.end(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } // function to erase given position auto it = mp.find(2); mp.erase(it); auto it1 = mp.find(5); mp.erase(it1); // prints the elements cout << "\nThe multimap after applying erase() is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.crbegin(); itr != mp.crend(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } return 0;}Output:The multimap before using erase() is :
KEY ELEMENT
1 40
2 30
2 20
3 60
5 50
The multimap after applying erase() is :
KEY ELEMENT
3 60
2 20
1 40
multimap_name.erase(iterator position)
Parameters: The function accept one mandatory parameter position which specifies the iterator that is the reference to the position of the element to be erased.
Return Value: The function does not returns anything.
Program below illustrate the above syntax:
// C++ program to illustrate// multimap::erase(position)#include <bits/stdc++.h>using namespace std; int main(){ // initialize container multimap<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 2, 20 }); mp.insert({ 5, 50 }); // prints the elements cout << "The multimap before using erase() is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.begin(); itr != mp.end(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } // function to erase given position auto it = mp.find(2); mp.erase(it); auto it1 = mp.find(5); mp.erase(it1); // prints the elements cout << "\nThe multimap after applying erase() is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.crbegin(); itr != mp.crend(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } return 0;}
The multimap before using erase() is :
KEY ELEMENT
1 40
2 30
2 20
3 60
5 50
The multimap after applying erase() is :
KEY ELEMENT
3 60
2 20
1 40
Syntax for erasing a given range:multimap_name.erase(iterator position1, iterator position2)
Parameters: The function accepts two mandatory parameters which are described below:position1 – specifies the iterator that is the reference to the element from which removal is to be done.position2 – specifies the iterator that is the reference to the element upto which removal is to be done.Return Value: The function does not returns anything. It removes all the elements in the given range of iterators.Program below illustrate the above syntax:// C++ program to illustrate// multimap::erase()#include <bits/stdc++.h>using namespace std; int main(){ // initialize container multimap<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 2, 20 }); mp.insert({ 5, 50 }); // prints the elements cout << "The multimap before using erase() is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.begin(); itr != mp.end(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } // function to erase in a given range // find() returns the iterator reference to // the position where the element is auto it1 = mp.find(2); auto it2 = mp.find(5); mp.erase(it1, it2); // prints the elements cout << "\nThe multimap after applying erase() is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.crbegin(); itr != mp.crend(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } return 0;}Output:The multimap before using erase() is :
KEY ELEMENT
1 40
2 30
2 20
3 60
5 50
The multimap after applying erase() is :
KEY ELEMENT
5 50
1 40
multimap_name.erase(iterator position1, iterator position2)
Parameters: The function accepts two mandatory parameters which are described below:
position1 – specifies the iterator that is the reference to the element from which removal is to be done.
position2 – specifies the iterator that is the reference to the element upto which removal is to be done.
Return Value: The function does not returns anything. It removes all the elements in the given range of iterators.
Program below illustrate the above syntax:
// C++ program to illustrate// multimap::erase()#include <bits/stdc++.h>using namespace std; int main(){ // initialize container multimap<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 2, 20 }); mp.insert({ 5, 50 }); // prints the elements cout << "The multimap before using erase() is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.begin(); itr != mp.end(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } // function to erase in a given range // find() returns the iterator reference to // the position where the element is auto it1 = mp.find(2); auto it2 = mp.find(5); mp.erase(it1, it2); // prints the elements cout << "\nThe multimap after applying erase() is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.crbegin(); itr != mp.crend(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } return 0;}
The multimap before using erase() is :
KEY ELEMENT
1 40
2 30
2 20
3 60
5 50
The multimap after applying erase() is :
KEY ELEMENT
5 50
1 40
arorakashish0911
CPP-Functions
cpp-multimap
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
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": "\n18 Nov, 2020"
},
{
"code": null,
"e": 30155,
"s": 25367,
"text": "multimap::erase() is a built-in function in C++ STL which is used to erase element from the container. It can be used to erase keys, elements at any specified posi... |
Count substrings with each character occurring at most k times - GeeksforGeeks | 07 May, 2021
Given a string S. Count number of substrings in which each character occurs at most k times. Assume that the string consists of only lowercase English alphabets.Examples:
Input : S = ab
k = 1
Output : 3
All the substrings a, b, ab have
individual character count less than 1.
Input : S = aaabb
k = 2
Output : 12
Substrings that have individual character
count at most 2 are: a, a, a, b, b, aa, aa,
ab, bb, aab, abb, aabb.
A simple solution is to first find all the substrings and then check if count of each character is at most k in each substring. Time complexity of this solution is O(n^3).An efficient solution is to maintain starting and ending point of substrings. Let us fix the starting point to an index i. Keep incrementing the ending point j one at a time. When changing the ending point update the count of corresponding character. Then check for this substring that whether each character has count at most k or not. If yes then increment answer by 1 else increment the starting point and reset ending point. The starting point is incremented because during last update on ending point character count exceed k and it will only increase further. So no subsequent substring with given fixed starting point will be a substring with each character count at most k. Implementation:
C++
Java
Python 3
C#
Javascript
// CPP program to count number of substrings// in which each character has count less// than or equal to k.#include <bits/stdc++.h> using namespace std; int findSubstrings(string s, int k){ // variable to store count of substrings. int ans = 0; // array to store count of each character. int cnt[26]; int i, j, n = s.length(); for (i = 0; i < n; i++) { // Initialize all characters count to zero. memset(cnt, 0, sizeof(cnt)); for (j = i; j < n; j++) { // increment character count cnt[s[j] - 'a']++; // check only the count of current character // because only the count of this // character is changed. The ending point is // incremented to current position only if // all other characters have count at most // k and hence their count is not checked. // If count is less than k, then increase ans // by 1. if (cnt[s[j] - 'a'] <= k) ans++; // if count is less than k, then break as // subsequent substrings for this starting // point will also have count greater than // k and hence are reduntant to check. else break; } } // return the final count of substrings. return ans;} // Driver codeint main(){ string S = "aaabb"; int k = 2; cout << findSubstrings(S, k); return 0;}
import java.util.Arrays; // Java program to count number of substrings// in which each character has count less// than or equal to k.class GFG { static int findSubstrings(String s, int k) { // variable to store count of substrings. int ans = 0; // array to store count of each character. int cnt[] = new int[26]; int i, j, n = s.length(); for (i = 0; i < n; i++) { // Initialize all characters count to zero. Arrays.fill(cnt, 0); for (j = i; j < n; j++) { // increment character count cnt[s.charAt(j) - 'a']++; // check only the count of current character // because only the count of this // character is changed. The ending point is // incremented to current position only if // all other characters have count at most // k and hence their count is not checked. // If count is less than k, then increase ans // by 1. if (cnt[s.charAt(j) - 'a'] <= k) { ans++; } // if count is less than k, then break as // subsequent substrings for this starting // point will also have count greater than // k and hence are reduntant to check. else { break; } } } // return the final count of substrings. return ans; } // Driver code static public void main(String[] args) { String S = "aaabb"; int k = 2; System.out.println(findSubstrings(S, k)); }} // This code is contributed by 29AjayKumar
# Python 3 program to count number of substrings# in which each character has count less# than or equal to k. def findSubstrings(s, k): # variable to store count of substrings. ans = 0 n = len(s) for i in range(n): # array to store count of each character. cnt = [0] * 26 for j in range(i, n): # increment character count cnt[ord(s[j]) - ord('a')] += 1 # check only the count of current character # because only the count of this # character is changed. The ending point is # incremented to current position only if # all other characters have count at most # k and hence their count is not checked. # If count is less than k, then increase # ans by 1. if (cnt[ord(s[j]) - ord('a')] <= k): ans += 1 # if count is less than k, then break as # subsequent substrings for this starting # point will also have count greater than # k and hence are reduntant to check. else: break # return the final count of substrings. return ans # Driver codeif __name__ == "__main__": S = "aaabb" k = 2 print(findSubstrings(S, k)) # This code is contributed by ita_c
// C# program to count number of substrings// in which each character has count less// than or equal to k.using System; class GFG{ public static int findSubstrings(string s, int k){ // variable to store count of substrings. int ans = 0; // array to store count of each character. int []cnt = new int[26]; int i, j, n = s.Length; for (i = 0; i < n; i++) { // Initialize all characters count to zero. Array.Clear(cnt, 0, cnt.Length); for (j = i; j < n; j++) { // increment character count cnt[s[j] - 'a']++; // check only the count of current character // because only the count of this // character is changed. The ending point is // incremented to current position only if // all other characters have count at most // k and hence their count is not checked. // If count is less than k, then increase ans // by 1. if (cnt[s[j] - 'a'] <= k) ans++; // if count is less than k, then break as // subsequent substrings for this starting // point will also have count greater than // k and hence are reduntant to check. else break; } } // return the final count of substrings. return ans;} // Driver codepublic static int Main(){ string S = "aaabb"; int k = 2; Console.WriteLine(findSubstrings(S, k)); return 0;}} // This code is contributed by SoM15242.
<script> // Javascript program to count number of substrings// in which each character has count less// than or equal to k. function findSubstrings(s, k){ // variable to store count of substrings. var ans = 0; // array to store count of each character. var cnt = Array(26); var i, j, n = s.length; for (i = 0; i < n; i++) { cnt = Array(26).fill(0); for (j = i; j < n; j++) { // increment character count cnt[(s[j].charCodeAt(0) - 'a'.charCodeAt(0))]++; // check only the count of current character // because only the count of this // character is changed. The ending point is // incremented to current position only if // all other characters have count at most // k and hence their count is not checked. // If count is less than k, then increase ans // by 1. if (cnt[(s[j].charCodeAt(0) - 'a'.charCodeAt(0))] <= k) ans++; // if count is less than k, then break as // subsequent substrings for this starting // point will also have count greater than // k and hence are reduntant to check. else break; } } // return the final count of substrings. return ans;} // Driver codevar S = "aaabb";var k = 2;document.write( findSubstrings(S, k)); // This code is contributed by rrrtnx.</script>
Output:
12
Time complexity: O(n^2) Auxiliary Space: O(1)Another efficient solution is to use sliding window technique. In which we will maintain two pointers left and right.We initialize left and the right pointer to 0, move the right pointer until the count of each alphabet is less than k, when the count is greater than we start incrementing left pointer and decrement the count of the corresponding alphabet, once the condition is satisfied we add (right-left + 1) to the answer. Implementation:
C++
Java
Python
C#
Javascript
// CPP program to count number of substrings// in which each character has count less// than or equal to k.#include<bits/stdc++.h> using namespace std; //function to find number of substring//in which each character has count less// than or equal to k. int find_sub(string s,int k){ int len=s.length(); int lp=0,rp=0; // initialize left and right pointer to 0 int ans=0; int hash_char[26]={0}; // an array to keep track of count of each alphabet for(;rp<len;rp++){ hash_char[s[rp]-'a']++; while(hash_char[s[rp]-'a']>k){ hash_char[s[lp]-'a']--; // decrement the count lp++; //increment left pointer } ans+=rp-lp+1; } return ans;} // Driver codeint main(){ string s="aaabb"; int k=2; cout<<find_sub(s,k)<<endl;}
// Java program to count number of substrings// in which each character has count less// than or equal to k.class GFG{ //function to find number of substring //in which each character has count less // than or equal to k. static int find_sub(String s, int k) { int len = s.length(); // initialize left and right pointer to 0 int lp = 0, rp = 0; int ans = 0; // an array to keep track of count of each alphabet int[] hash_char = new int[26]; for (; rp < len; rp++) { hash_char[s.charAt(rp) - 'a']++; while (hash_char[s.charAt(rp) - 'a'] > k) { // decrement the count hash_char[s.charAt(lp) - 'a']--; //increment left pointer lp++; } ans += rp - lp + 1; } return ans; } // Driver code public static void main(String[] args) { String S = "aaabb"; int k = 2; System.out.println(find_sub(S, k)); }} // This code is contributed by PrinciRaj1992
# Python3 program to count number of substrings# in which each character has count less# than or equal to k. # function to find number of substring# in which each character has count less# than or equal to k. def find_sub(s, k): Len = len(s) # initialize left and right pointer to 0 lp, rp = 0, 0 ans = 0 # an array to keep track of count of each alphabet hash_char = [0 for i in range(256)] for rp in range(Len): hash_char[ord(s[rp])] += 1 while(hash_char[ord(s[rp])] > k): hash_char[ord(s[lp])] -= 1 # decrement the count lp += 1 #increment left pointer ans += rp - lp + 1 return ans # Driver codes = "aaabb"k = 2;print(find_sub(s, k)) # This code is contributed by mohit kumar
// C# program to count number of substrings// in which each character has count less// than or equal to k.using System; class GFG{ //function to find number of substring //in which each character has count less // than or equal to k. static int find_sub(string s, int k) { int len = s.Length; // initialize left and right pointer to 0 int lp = 0,rp = 0; int ans = 0; // an array to keep track of count of each alphabet int []hash_char = new int[26]; for(;rp < len; rp++) { hash_char[s[rp] - 'a']++; while(hash_char[s[rp] - 'a'] > k) { // decrement the count hash_char[s[lp] - 'a']--; //increment left pointer lp++; } ans += rp - lp + 1; } return ans; } // Driver code static public void Main() { String S = "aaabb"; int k = 2; Console.WriteLine(find_sub(S, k)); }} // This code is contributed by Rajput-Ji
<script>// Javascript program to count number of substrings// in which each character has count less// than or equal to k. //function to find number of substring //in which each character has count less // than or equal to k. function find_sub(s,k) { let len = s.length; // initialize left and right pointer to 0 let lp = 0, rp = 0; let ans = 0; // an array to keep track of count of each alphabet let hash_char = new Array(26); for(let i = 0; i < hash_char.length; i++) { hash_char[i] = 0; } for (; rp < len; rp++) { hash_char[s[rp].charCodeAt(0) - 'a'.charCodeAt(0)]++; while (hash_char[s[rp].charCodeAt(0) - 'a'.charCodeAt(0)] > k) { // decrement the count hash_char[s[lp].charCodeAt(0) - 'a'.charCodeAt(0)]--; //increment left pointer lp++; } ans += rp - lp + 1; } return ans; } // Driver code let S = "aaabb"; let k = 2; document.write(find_sub(S, k)); // This code is contributed by avanitrachhadiya2155</script>
Output:
12
Time complexity: O(n) Auxiliary Space: O(1)
YouTubeGeeksforGeeks507K subscribersCount substrings with each character occurring at most k times | 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 / 3:07•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=cSa9ClP1Zo0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
shikharK
29AjayKumar
Rajput-Ji
SoumikMondal
ukasp
princiraj1992
mohit kumar 29
rrrtnx
avanitrachhadiya2155
frequency-counting
Strings
Technical Scripter
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Array of Strings in C++ (5 Different Ways to Create)
Different methods to reverse a string in C/C++
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Check whether two strings are anagram of each other
Length of the longest substring without repeating characters | [
{
"code": null,
"e": 26707,
"s": 26679,
"text": "\n07 May, 2021"
},
{
"code": null,
"e": 26880,
"s": 26707,
"text": "Given a string S. Count number of substrings in which each character occurs at most k times. Assume that the string consists of only lowercase English alphabets.Ex... |
Recursively apply a Function to a List in R Programming - rapply() function - GeeksforGeeks | 16 Jun, 2020
rapply() function in R Language is used to recursively apply a function to a list.
Syntax:rapply(object, f, classes = “ANY”, deflt = NULL, how = c(“unlist”, “replace”, “list”))
Parameters:
object: represents list or an expressionf: represents function to be applied recursivelyclasses: represents class name of the vector or “ANY” to match any of the classdeflt: represents default result when how is not “replace”how: represents modes
The modes in rapply() function are of 2 basic types. If how = “replace”, each element of the list object which is not itself is a list and has a class included in classes then each element of the list is replaced by the resulting value of the function f applied to the element.
If how = “list” or how = “unlist”, list object is copied and all non-list elements which are included in classes are replaced by the resulting value of the function f applied to the element and all other are replaced by deflt.
Example 1: Using replace mode
# Defining a listls <- list(a = 1:5, b = 100:110, c = c('a', 'b', 'c')) # Print whole listcat("Whole List: \n")print(ls) # Using replace modecat("Using replace mode:\n")rapply(ls, mean, how = "replace", classes = "integer")
Output:
Whole List:
$a
[1] 1 2 3 4 5
$b
[1] 100 101 102 103 104 105 106 107 108 109 110
$c
[1] "a" "b" "c"
Using replace mode:
$a
[1] 3
$b
[1] 105
$c
[1] "a" "b" "c"
Example 2: Using list mode
# Defining a listls <- list(a = 1:5, b = 100:110, c = c('a', 'b', 'c')) # Print whole listcat("Whole List: \n")print(ls) # Using list modecat("Using list mode:\n")rapply(ls, mean, how = "list", classes = "integer")
Output:
Whole List:
$a
[1] 1 2 3 4 5
$b
[1] 100 101 102 103 104 105 106 107 108 109 110
$c
[1] "a" "b" "c"
Using list mode:
$a
[1] 3
$b
[1] 105
$c
NULL
Example 3: Using unlist mode
# Defining a listls <- list(a = 1:5, b = 100:110, c = c('a', 'b', 'c')) # Print whole listcat("Whole List: \n")print(ls) # Using unlist modecat("Using unlist mode:\n")rapply(ls, mean, how = "unlist", classes = "integer")
Output:
Whole List:
$a
[1] 1 2 3 4 5
$b
[1] 100 101 102 103 104 105 106 107 108 109 110
$c
[1] "a" "b" "c"
Using unlist mode:
a b
3 105
R List-Function
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
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
R - if statement
How to filter R dataframe by multiple conditions? | [
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n16 Jun, 2020"
},
{
"code": null,
"e": 26570,
"s": 26487,
"text": "rapply() function in R Language is used to recursively apply a function to a list."
},
{
"code": null,
"e": 26664,
"s": 26570,
"text": "Syntax:... |
Increment ++ and decrement -- Operators in C++ | The increment operator ++ adds 1 to its operand, and the decrement operator -- subtracts 1 from its operand. So,
x = x+1; is the same as x++;
And similarly,
x = x-1; is the same as x--;
Both the increment and decrement operators can either precede (prefix) or follow (postfix) the operand.
x = x+1; can be written as ++x;
Note that, When an increment or decrement is used as part of an expression, there is an important difference in prefix and postfix forms. If you are using prefix form then increment or decrement will be done before resting of the expression, and if you are using postfix form, then increment or decrement will be done after the complete expression is evaluated.
In the prefix version (i.e., ++i), the value of i is incremented, and the value of the expression is the new value of i. So basically it first increments then assigns a value to the expression.
In the postfix version (i.e., i++), the value of i is incremented, but the value of the expression is the original value of i. So basically it first assigns a value to expression and then increments the variable.
Let's look at some code to get a better understanding −
#include<iostream>
using namespace std;
int main() {
int x = 3, y, z;
y = x++;
z = ++x;
cout << x << ", " << y << ", " << z;
return 0;
}
This would give us the output −
5, 3, 5
Why is this? Let's look at it in detail −
Initialize x to 3
Assign y the value we get by evaluating the expression x++, ie, the value of x before increment then increment x.
Increment x then assign z the value we get by evaluating the expression ++x, ie, value of x after the increment.
Print these values | [
{
"code": null,
"e": 1175,
"s": 1062,
"text": "The increment operator ++ adds 1 to its operand, and the decrement operator -- subtracts 1 from its operand. So,"
},
{
"code": null,
"e": 1204,
"s": 1175,
"text": "x = x+1; is the same as x++;"
},
{
"code": null,
"e": 121... |
Python | os.getenv() method - GeeksforGeeks | 20 May, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.getenv() method in Python returns the value of the environment variable key if it exists otherwise returns the default value.
Syntax: os.getenv(key, default = None)
Parameters:key: string denoting the name of environment variabledefault (optional) : string denoting the default value in case key does not exists. If omitted default is set to ‘None’.
Return Type: This method returns a string that denotes the value of the environment variable key. In case key does not exists it returns the value of default parameter.
Code #1: use of os.getenv() method
# Python program to explain os.getenv() method # importing os module import os # Get the value of 'HOME'# environment variablekey = 'HOME'value = os.getenv(key) # Print the value of 'HOME'# environment variableprint("Value of 'HOME' environment variable :", value) # Get the value of 'JAVA_HOME'# environment variablekey = 'JAVA_HOME'value = os.getenv(key) # Print the value of 'JAVA_HOME'# environment variableprint("Value of 'JAVA_HOME' environment variable :", value)
Value of 'HOME' environment variable : /home/ihritik
Value of 'JAVA_HOME' environment variable : /opt/jdk-10.0.1
Code #2: if key does not exist
# Python program to explain os.getenv() method # importing os module import os # Get the value of 'home'# environment variablekey = 'home'value = os.getenv(key) # Print the value of 'home'# environment variableprint("Value of 'home' environment variable :", value)
Value of 'home' environment variable : None
Code #3: Explicitly specifying default parameter
# Python program to explain os.getenv() method # importing os module import os # Get the value of 'home'# environment variablekey = 'home'value = os.getenv(key, "value does not exist") # Print the value of 'home'# environment variableprint("Value of 'home' environment variable :", value)
Value of 'home' environment variable : value does not exist
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python | [
{
"code": null,
"e": 24164,
"s": 24136,
"text": "\n20 May, 2019"
},
{
"code": null,
"e": 24383,
"s": 24164,
"text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable... |
Difference between an Iterator and ListIterator in Java | Java provided these two interfaces to traverse the data one by one stored in a collection. The internal implementation of iterator and list iterator makes them differ apart but the main agenda of both the iterators is the same.
The following are the important differences between Iterator and ListIterator.
JavaTester.java
Live Demo
import java.io.*;
import java.util.*;
public class JavaTester {
public static void main(String[] args){
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
//Iterator
Iterator itr = list.iterator();
System.out.println("Iterator traversal:");
while (itr.hasNext())
System.out.print(itr.next() + " ");
System.out.println();
// ListIterator
ListIterator i = list.listIterator();
System.out.println("ListIterator Forward traversal:");
while (i.hasNext()){
System.out.print(i.next() + " ");
System.out.println();
System.out.println("ListIterator Backward traversal : ");
}
while (i.hasPrevious()){
System.out.print(i.previous() + " ");
System.out.println();
}
}
}
Iterator traversal:
1 2 3 4 5
ListIterator Forward traversal:
1
ListIterator Backward traversal :
2
ListIterator Backward traversal :
3
ListIterator Backward traversal :
4
ListIterator Backward traversal :
5
ListIterator Backward traversal :
5
4
3
2
1 | [
{
"code": null,
"e": 1290,
"s": 1062,
"text": "Java provided these two interfaces to traverse the data one by one stored in a collection. The internal implementation of iterator and list iterator makes them differ apart but the main agenda of both the iterators is the same."
},
{
"code": nul... |
Error Handling in C programs - GeeksforGeeks | 02 Jun, 2017
Although C does not provide direct support to error handling (or exception handling), there are ways through which error handling can be done in C. A programmer has to prevent errors at the first place and test return values from the functions.A lot of C function calls return a -1 or NULL in case of an error, so quick test on these return values are easily done with for instance an ‘if statement’. For example, In Socket Programming, the returned value of the functions like socket(), listen() etc. are checked to see if there is an error or not.
Example: Error handling in Socket Programming
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}
Different methods of Error handling in C
Global Variable errno: When a function is called in C, a variable named as errno is automatically assigned a code (value) which can be used to identify the type of error that has been encountered. Its a global variable indicating the error occurred during any function call and defined in the header file errno.h.Different codes (values) for errno mean different types of errors. Below is a list of few different errno values and its corresponding meaning:errno value Error
1 /* Operation not permitted */
2 /* No such file or directory */
3 /* No such process */
4 /* Interrupted system call */
5 /* I/O error */
6 /* No such device or address */
7 /* Argument list too long */
8 /* Exec format error */
9 /* Bad file number */
10 /* No child processes */
11 /* Try again */
12 /* Out of memory */
13 /* Permission denied */
// C implementation to see how errno value is// set in the case of any error in C#include <stdio.h>#include <errno.h> int main(){ // If a file is opened which does not exist, // then it will be an error and corresponding // errno value will be set FILE * fp; // opening a file which does // not exist. fp = fopen("GeeksForGeeks.txt", "r"); printf(" Value of errno: %d\n ", errno); return 0;}Output:Value of errno: 2
Note: Here the errno is set to 2 which means – No such file or directory. On online IDE it may give errorno 13, which says permission denied.perror() and strerror(): The errno value got above indicate the types of error encountered.If it is required to show the error description, then there are two functions that can be used to display a text message that is associated with errorno. The functions are:perror: It displays the string you pass to it, followed by a colon, a space, and then the textual representation of the current errno value.Syntax:void perror (const char *str)
str: is a string containing a custom message
to be printed before the error message itself.strerror(): returns a pointer to the textual representation of the current errno value.Syntax:char *strerror (int errnum)
errnum: is the error number (errno).// C implementation to see how perror() and strerror()// functions are used to print the error messages.#include <stdio.h>#include <errno.h>#include <string.h> int main (){ FILE *fp; // If a file is opened which does not exist, // then it will be an error and corresponding // errno value will be set fp = fopen(" GeeksForGeeks.txt ", "r"); // opening a file which does // not exist. printf("Value of errno: %d\n ", errno); printf("The error message is : %s\n", strerror(errno)); perror("Message from perror"); return 0;}Output:On Personal desktop:Value of errno: 2
The error message is : No such file or directory
Message from perror: No such file or directory
On online IDE: Value of errno: 13
The error message is : Permission denied
Note: The function perror() displays a string passed to it, followed by a colon and the textual message of the current errno value.Exit Status: The C standard specifies two constants: EXIT_SUCCESS and EXIT_FAILURE, that may be passed to exit() to indicate successful or unsuccessful termination, respectively. These are macros defined in stdlib.h.// C implementation which shows the// use of EXIT_SUCCESS and EXIT_FAILURE.#include <stdio.h>#include <errno.h>#include <string.h>#include <stdlib.h> int main (){ FILE * fp; fp = fopen ("filedoesnotexist.txt", "rb"); if (fp == NULL) { printf("Value of errno: %d\n", errno); printf("Error opening the file: %s\n", strerror(errno)); perror("Error printed by perror"); exit(EXIT_FAILURE); printf("I will not be printed\n"); } else { fclose (fp); exit(EXIT_SUCCESS); printf("I will not be printed\n"); } return 0;}Output:Value of errno: 2
Error opening the file: No such file or directory
Error printed by perror: No such file or directory
Divide by Zero Errors: A common pitfall made by C programmers is not checking if a divisor is zero before a division command. Division by zero leads to undefined behavior, there is no C language construct that can do anything about it. Your best bet is to not divide by zero in the first place, by checking the denominator.// C program to check and rectify// divide by zero condition#include<stdio.h>#include <stdlib.h> void function(int); int main(){ int x = 0; function(x); return 0;} void function(int x){ float fx; if (x==0) { printf("Division by Zero is not allowed"); fprintf(stderr, "Division by zero! Exiting...\n"); exit(EXIT_FAILURE); } else { fx = 10 / x; printf("f(x) is: %.5f", fx); }}Output:Division by Zero is not allowed
Global Variable errno: When a function is called in C, a variable named as errno is automatically assigned a code (value) which can be used to identify the type of error that has been encountered. Its a global variable indicating the error occurred during any function call and defined in the header file errno.h.Different codes (values) for errno mean different types of errors. Below is a list of few different errno values and its corresponding meaning:errno value Error
1 /* Operation not permitted */
2 /* No such file or directory */
3 /* No such process */
4 /* Interrupted system call */
5 /* I/O error */
6 /* No such device or address */
7 /* Argument list too long */
8 /* Exec format error */
9 /* Bad file number */
10 /* No child processes */
11 /* Try again */
12 /* Out of memory */
13 /* Permission denied */
// C implementation to see how errno value is// set in the case of any error in C#include <stdio.h>#include <errno.h> int main(){ // If a file is opened which does not exist, // then it will be an error and corresponding // errno value will be set FILE * fp; // opening a file which does // not exist. fp = fopen("GeeksForGeeks.txt", "r"); printf(" Value of errno: %d\n ", errno); return 0;}Output:Value of errno: 2
Note: Here the errno is set to 2 which means – No such file or directory. On online IDE it may give errorno 13, which says permission denied.
errno value Error
1 /* Operation not permitted */
2 /* No such file or directory */
3 /* No such process */
4 /* Interrupted system call */
5 /* I/O error */
6 /* No such device or address */
7 /* Argument list too long */
8 /* Exec format error */
9 /* Bad file number */
10 /* No child processes */
11 /* Try again */
12 /* Out of memory */
13 /* Permission denied */
// C implementation to see how errno value is// set in the case of any error in C#include <stdio.h>#include <errno.h> int main(){ // If a file is opened which does not exist, // then it will be an error and corresponding // errno value will be set FILE * fp; // opening a file which does // not exist. fp = fopen("GeeksForGeeks.txt", "r"); printf(" Value of errno: %d\n ", errno); return 0;}
Output:
Value of errno: 2
Note: Here the errno is set to 2 which means – No such file or directory. On online IDE it may give errorno 13, which says permission denied.
perror() and strerror(): The errno value got above indicate the types of error encountered.If it is required to show the error description, then there are two functions that can be used to display a text message that is associated with errorno. The functions are:perror: It displays the string you pass to it, followed by a colon, a space, and then the textual representation of the current errno value.Syntax:void perror (const char *str)
str: is a string containing a custom message
to be printed before the error message itself.strerror(): returns a pointer to the textual representation of the current errno value.Syntax:char *strerror (int errnum)
errnum: is the error number (errno).// C implementation to see how perror() and strerror()// functions are used to print the error messages.#include <stdio.h>#include <errno.h>#include <string.h> int main (){ FILE *fp; // If a file is opened which does not exist, // then it will be an error and corresponding // errno value will be set fp = fopen(" GeeksForGeeks.txt ", "r"); // opening a file which does // not exist. printf("Value of errno: %d\n ", errno); printf("The error message is : %s\n", strerror(errno)); perror("Message from perror"); return 0;}Output:On Personal desktop:Value of errno: 2
The error message is : No such file or directory
Message from perror: No such file or directory
On online IDE: Value of errno: 13
The error message is : Permission denied
Note: The function perror() displays a string passed to it, followed by a colon and the textual message of the current errno value.
perror: It displays the string you pass to it, followed by a colon, a space, and then the textual representation of the current errno value.Syntax:void perror (const char *str)
str: is a string containing a custom message
to be printed before the error message itself.
void perror (const char *str)
str: is a string containing a custom message
to be printed before the error message itself.
strerror(): returns a pointer to the textual representation of the current errno value.Syntax:char *strerror (int errnum)
errnum: is the error number (errno).
char *strerror (int errnum)
errnum: is the error number (errno).
// C implementation to see how perror() and strerror()// functions are used to print the error messages.#include <stdio.h>#include <errno.h>#include <string.h> int main (){ FILE *fp; // If a file is opened which does not exist, // then it will be an error and corresponding // errno value will be set fp = fopen(" GeeksForGeeks.txt ", "r"); // opening a file which does // not exist. printf("Value of errno: %d\n ", errno); printf("The error message is : %s\n", strerror(errno)); perror("Message from perror"); return 0;}
Output:On Personal desktop:
Value of errno: 2
The error message is : No such file or directory
Message from perror: No such file or directory
On online IDE:
Value of errno: 13
The error message is : Permission denied
Note: The function perror() displays a string passed to it, followed by a colon and the textual message of the current errno value.
Exit Status: The C standard specifies two constants: EXIT_SUCCESS and EXIT_FAILURE, that may be passed to exit() to indicate successful or unsuccessful termination, respectively. These are macros defined in stdlib.h.// C implementation which shows the// use of EXIT_SUCCESS and EXIT_FAILURE.#include <stdio.h>#include <errno.h>#include <string.h>#include <stdlib.h> int main (){ FILE * fp; fp = fopen ("filedoesnotexist.txt", "rb"); if (fp == NULL) { printf("Value of errno: %d\n", errno); printf("Error opening the file: %s\n", strerror(errno)); perror("Error printed by perror"); exit(EXIT_FAILURE); printf("I will not be printed\n"); } else { fclose (fp); exit(EXIT_SUCCESS); printf("I will not be printed\n"); } return 0;}Output:Value of errno: 2
Error opening the file: No such file or directory
Error printed by perror: No such file or directory
// C implementation which shows the// use of EXIT_SUCCESS and EXIT_FAILURE.#include <stdio.h>#include <errno.h>#include <string.h>#include <stdlib.h> int main (){ FILE * fp; fp = fopen ("filedoesnotexist.txt", "rb"); if (fp == NULL) { printf("Value of errno: %d\n", errno); printf("Error opening the file: %s\n", strerror(errno)); perror("Error printed by perror"); exit(EXIT_FAILURE); printf("I will not be printed\n"); } else { fclose (fp); exit(EXIT_SUCCESS); printf("I will not be printed\n"); } return 0;}
Output:
Value of errno: 2
Error opening the file: No such file or directory
Error printed by perror: No such file or directory
Divide by Zero Errors: A common pitfall made by C programmers is not checking if a divisor is zero before a division command. Division by zero leads to undefined behavior, there is no C language construct that can do anything about it. Your best bet is to not divide by zero in the first place, by checking the denominator.// C program to check and rectify// divide by zero condition#include<stdio.h>#include <stdlib.h> void function(int); int main(){ int x = 0; function(x); return 0;} void function(int x){ float fx; if (x==0) { printf("Division by Zero is not allowed"); fprintf(stderr, "Division by zero! Exiting...\n"); exit(EXIT_FAILURE); } else { fx = 10 / x; printf("f(x) is: %.5f", fx); }}Output:Division by Zero is not allowed
// C program to check and rectify// divide by zero condition#include<stdio.h>#include <stdlib.h> void function(int); int main(){ int x = 0; function(x); return 0;} void function(int x){ float fx; if (x==0) { printf("Division by Zero is not allowed"); fprintf(stderr, "Division by zero! Exiting...\n"); exit(EXIT_FAILURE); } else { fx = 10 / x; printf("f(x) is: %.5f", fx); }}
Output:
Division by Zero is not allowed
This article is contributed by MAZHAR IMAM KHAN. 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.
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Function Pointer in C
Core Dump (Segmentation fault) in C/C++
fork() in C
rand() and srand() in C/C++
Substring in C++
Converting Strings to Numbers in C/C++
std::string class in C++
TCP Server-Client implementation in C | [
{
"code": null,
"e": 26169,
"s": 26141,
"text": "\n02 Jun, 2017"
},
{
"code": null,
"e": 26719,
"s": 26169,
"text": "Although C does not provide direct support to error handling (or exception handling), there are ways through which error handling can be done in C. A programmer ha... |
Maximum Sum Problem | Practice | GeeksforGeeks | A number n can be broken into three parts n/2, n/3 and n/4 (consider only integer part). Each number obtained in this process can be divided further recursively. Find the maximum sum that can be obtained by summing up the divided parts together.
Note: The maximum sum may be obtained without dividing n also.
Example 1:
Input:
n = 12
Output: 13
Explanation: Break n = 12 in three parts
{12/2, 12/3, 12/4} = {6, 4, 3}, now current
sum is = (6 + 4 + 3) = 13. Further breaking 6,
4 and 3 into parts will produce sum less than
or equal to 6, 4 and 3 respectively.
​Example 2:
Input:
n = 24
Output: 27
Explanation: Break n = 24 in three parts
{24/2, 24/3, 24/4} = {12, 8, 6}, now current
sum is = (12 + 8 + 6) = 26 . But recursively
breaking 12 would produce value 13.
So our maximum sum is 13 + 8 + 6 = 27.
Your Task:
You don't need to read input or print anything. Your task is to complete the function maxSum() which accepts an integer n and returns the maximum sum.
Expected Time Complexity: O(n)
Expected Auxiliary Space: O(n)
Constraints:
0 <= n <= 106
0
baibhavrajputt2 months ago
Java memoization solution
class Solution
{
public int maxSum(int n)
{
//code here.
int dp[] = new int[n+1];
for(int i=0 ; i<=n ; i++)
dp[i] = -1;
return soln(n , dp);
}
public int soln(int i , int dp[]){
if(i==0)
return 0;
if(dp[i] != -1)
return dp[i];
int by2 = soln(i/2 , dp);
int by3 = soln(i/3 , dp);
int by4 = soln(i/4 , dp);
return dp[i] = Math.max(i , by2+by3+by4);
}
}
0
raunakmishra12433 months ago
int maxSum(int n)
{
int dp[n+1];
dp[0]=0;
dp[1]=1;
for(int i=2;i<=n;i++)
{
dp[i]=max(i,dp[i/2]+dp[i/3]+dp[i/4]);
}
return dp[n];
}
};
+2
dhairyasavaner954 months ago
public int maxSum(int n)
{
if(n == 0) return 0;
int x = maxSum(n/2) + maxSum(n/3) + maxSum(n/4);
if( n <= x) return x;
else return n;
}
+1
chessnoobdj4 months ago
C++ dp tabulation
int maxSum(int n)
{
int dp[n+1] = {0};
for(int i=1; i<=n; i++)
dp[i] = max(i, dp[i/2]+dp[i/3]+dp[i/4]);
return dp[n];
}
+1
gauravtiwari30014 months ago
Simple Recursive approach without using Dynamic Programming:
int maxSum(int n)
{
//code here.
if(n<=1){return n;}
int path1 = maxSum(n/2);
int path2 = maxSum(n/3);
int path3 = maxSum(n/4);
return max(path1+ path2+ path3, n);
}
0
aakashmehta8805 months ago
int maxSum(int n)
{
vector<int> dp(n+1,0);
dp[0]=0,dp[1]=1;
for(int i=2;i<dp.size();i++)
dp[i]=max(i,dp[i/2]+dp[i/3]+dp[i/4]);
return dp[n];
}
-1
aakashmehta8805 months ago
int fun(int n,vector<int> &dp){
if(n==0 or n==1) return n;
if(dp[n]!=-1) return dp[n];
int x=fun(n/2,dp);
int y=fun(n/3,dp);
int z=fun(n/4,dp);
dp[n]=max(n,x+y+z);
return dp[n];
}
int maxSum(int n)
{
vector<int> dp(n+1,-1);
return fun(n,dp);
}
memoization
0
omkarsubhasishkhuntia7 months ago
int maxSum(int n) { //code here. int dp[n]; memset(dp,0,sizeof(dp)); dp[1]=1; dp[2]=1; int c=0; for(int i=3;i<=n;i++){ dp[i]=max(i/3,dp[i/3])+max(i/2,dp[i/2])+max(i/4,dp[i/4]); c=max(c,dp[i]); } return c; }
+1
bhaskarkumarpro7 months ago
int maxSum(int n) { //code here. if(n/2 + n/3 + n/4 > n) return maxSum(n/2)+maxSum(n/3)+maxSum(n/4); else return n; }
0
mzmlrafiqcse7 months ago
java
public int maxSum(int n) {
int dp[] = new int[n+1];
dp[0] = 0;
if(n > 1) dp[1] = 1;
for (int i=2; i<=n; i++)
dp[i] = Math.max(dp[i/2] + dp[i/3] + dp[i/4], i);
return dp[n];
}
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": 547,
"s": 238,
"text": "A number n can be broken into three parts n/2, n/3 and n/4 (consider only integer part). Each number obtained in this process can be divided further recursively. Find the maximum sum that can be obtained by summing up the divided parts together.\nNote: Th... |
How to update Node.js and NPM to next version ? - GeeksforGeeks | 11 Apr, 2022
Node.js is a cross-platform JavaScript environment that can be used for server-side scripting. Due to its non-blocking workflow, Node.js is popular among the web developers for building a dynamic web application. Node Package Manager also known as npm is the package manager for Node.js. It also serves as a command-line utility for interacting with the npm online repository for package installation, version management, and dependency management. It is important to have Node.js installed in order to use npm. Also, working with updated versions of Node.js and npm ensures better performance and added features. Follow the link to download and install Node.js: Download Node.js Update Node.js to the latest stable version: Node.js can be updated from the official Node.js website as well as through the command line using Node Version Manager(nvm). nvm was originally developed for Linux systems, however nvm can be installed separately for Windows system by the following steps:
Go to this siteInstall and unzip the nvm-setup.zip fileFrom cmd type nvm -v to ensure nvm is installed.
Go to this site
Install and unzip the nvm-setup.zip file
From cmd type nvm -v to ensure nvm is installed.
After installing nvm, the following can be done to update Node.js to the latest version:
nvm install <version>
Check the list of available Node.js version in the system using the following command:
nvm list
To use the desired version, use the following command:
nvm use <version>
Update npm: To update NPM, use the following command:
npm install -g npm
Output: Below is a demonstration for updating Node.js and npm versions for Linux systems. Install nvm in Linux:
# curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash OR # wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
Check if nvm is installed successfully
Open a new terminal
nvm -v
To install latest version of node, use the following command.
# nvm install node
or
# nvm install --lts
or
# nvm install
Check all the available version of node on the system:
# nvm ls
Use a particular version
# nvm use
Update npm to latest version:
# npm install -g npm
HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
prashantexploring
Node.js-Misc
Picked
CSS
HTML
Node.js
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to apply style to parent if it has child with CSS?
How to set space between the flexbox ?
Design a web page using HTML and CSS
Create a Responsive Navbar using ReactJS
Form validation using jQuery
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML | [
{
"code": null,
"e": 26497,
"s": 26469,
"text": "\n11 Apr, 2022"
},
{
"code": null,
"e": 27479,
"s": 26497,
"text": "Node.js is a cross-platform JavaScript environment that can be used for server-side scripting. Due to its non-blocking workflow, Node.js is popular among the web d... |
Left join and Right join in MS SQL Server - GeeksforGeeks | 15 Jul, 2020
Prerequisite – Introduction of MS SQL Server
1. Left Join :A join combines the set of two tables only. A left join is used when a user wants to extract the left table’s data only. Left join not only combines the left table’s rows but also the rows that match alongside the right table.
Syntax –
select select_list
from table1 left join table2 on join_predicate
(OR)
select *
from table1 right join table2
2. Right Join :Right join combines the data of the right table and the rows that match both the tables.
Syntax –
select select_list
from table1 right join table2 on join_predicate
(OR)
select *
from table1 right join table2
Example –The first table is the Course table which is considered the left table and the second table is the Student table which is considered the right table.
1. Left Join :Left join is applied to the tables Course and Student and the table below is the result set.
select name, course
from c.course left join s.student on c.age = s.age
The left table and its corresponding matching rows on the right table are displayed. If a user wants to display the rows only in the left table, where clause can be used in the query. Left join is usually used for a maximum of two tables but in case of SQL Server, it can be used for multiple tables too.2. Right Join :Right join is applied to the tables Course and Student and the table below is the result set.
select name, rollno
from c.course right join s.student on c.age = s.age
If the tables do not have common rows, it displays the rows as NULL. The right join can also be used for multiple tables.
DBMS-SQL
SQL-Server
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Deadlock in DBMS
Types of Functional dependencies in DBMS
KDD Process in Data Mining
Conflict Serializability in DBMS
Introduction of Relational Algebra in DBMS
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL?
MySQL | Group_CONCAT() Function | [
{
"code": null,
"e": 25549,
"s": 25521,
"text": "\n15 Jul, 2020"
},
{
"code": null,
"e": 25594,
"s": 25549,
"text": "Prerequisite – Introduction of MS SQL Server"
},
{
"code": null,
"e": 25835,
"s": 25594,
"text": "1. Left Join :A join combines the set of two ... |
Check whether given three numbers are adjacent primes - GeeksforGeeks | 12 May, 2022
Given three numbers and check whether they are adjacent primes are not. Three prime numbers are said to be adjacent primes if there is no prime between them.Examples :
Input : 2, 3, 5
Output : Yes
Explanation: 2, 3, 5 are adjacent primes.
Input : 11, 13, 19
Output : No
Explanation: 11, 13, 19 are not adjacent primes.
Because there exits 17 between 13 and 19 which
is prime.
Approach: We already know what is a prime number. Here we need to check whether the given three numbers are adjacent primes or not. First we check given three numbers are prime or not. After that we will find next prime of first number and second number. If satisfies the condition of adjacent primes then it is clear that given three numbers are adjacent primes otherwise not.
C++
Java
Python
C#
PHP
Javascript
// CPP program to check given three numbers are// primes are not. #include <bits/stdc++.h>using namespace std; // checks whether given number is prime or not.bool isPrime(int n){ // check if n is a multiple of 2 if (n % 2 == 0) return false; // if not, then just check the odds for (int i = 3; i * i <= n; i += 2) if (n % i == 0) return false; return true;} // return next prime numberint nextPrime(int start){ // start with next number. int next = start + 1; // breaks after finding next prime number while (!isPrime(next)) next++; return next;} // check given three numbers are adjacent primes are not.bool areAdjacentPrimes(int a, int b, int c){ // check given three numbers are primes are not. if (!isPrime(a) || !isPrime(b) || !isPrime(c)) return false; // find next prime of a int next = nextPrime(a); // If next is not same as 'a' if (next != b) return false; // If next is not same as 'c' if (nextPrime(b) != c) return false; return true;} // Driver code for above functionsint main(){ if (areAdjacentPrimes(11, 13, 19)) cout << "Yes"; else cout << "No"; return 0;}
// Java program to check given three numbers are// primes are not. import java.io.*;import java.util.*; class GFG{ public static boolean isPrime(int n) { // check if n is a multiple of 2 if (n % 2 == 0) return false; // if not, then just check the odds for (int i = 3; i * i <= n; i += 2) if (n % i == 0) return false; return true; } // return next prime number public static int nextPrime(int start) { // start with next number. int next = start + 1; // breaks after finding next prime number while (!isPrime(next)) next++; return next; } // check given three numbers are adjacent primes are not. public static boolean areAdjacentPrimes(int a, int b, int c) { // check given three numbers are primes are not. if (!isPrime(a) || !isPrime(b) || !isPrime(c)) return false; // find next prime of a int next = nextPrime(a); // If next is not same as 'a' if (next != b) return false; // If next is not same as 'c' if (nextPrime(b) != c) return false; return true; } // Driver code for above functions public static void main (String[] args) { if (areAdjacentPrimes(11, 13, 19)) System.out.print("Yes"); else System.out.print("No"); }}// Mohit Gupta_OMG <(o_0)>
# Python3 program to check given # three numbers are primes are not. # Function checks whether given number is prime or not.def isPrime(n) : # Check if n is a multiple of 2 if (n % 2 == 0) : return False # If not, then just check the odds i = 3 while( i*i <= n) : if (n % i == 0) : return False i = i + 2 return True # Return next prime numberdef nextPrime(start) : # Start with next number nxt = start + 1 # Breaks after finding next prime number while (isPrime(nxt) == False) : nxt = nxt + 1 return nxt # Check given three numbers# are adjacent primes are notdef areAdjacentPrimes(a, b, c) : # Check given three numbers are primes are not if (isPrime(a) == False or isPrime(b) == False or isPrime(c) == False) : return False # Find next prime of a nxt = nextPrime(a) # If next is not same as 'a' if (nxt != b) : return False # If next is not same as 'c' if (nextPrime(b) != c) : return False return True # Driver code for above functionsif (areAdjacentPrimes(11, 13, 19)) : print( "Yes"),else : print( "No") #This code is contributed by NIKITA TIWARI.
// Java program to check given three numbers are// primes are not.using System; class GFG{ public static bool isPrime(int n) { // check if n is a multiple of 2 if (n % 2 == 0) return false; // if not, then just check the odds for (int i = 3; i * i <= n; i += 2) if (n % i == 0) return false; return true; } // return next prime number public static int nextPrime(int start) { // start with next number. int next = start + 1; // breaks after finding next prime number while (!isPrime(next)) next++; return next; } // check given three numbers are adjacent primes are not. public static bool areAdjacentPrimes(int a, int b, int c) { // check given three numbers are primes are not. if (!isPrime(a) || !isPrime(b) || !isPrime(c)) return false; // find next prime of a int next = nextPrime(a); // If next is not same as 'a' if (next != b) return false; // If next is not same as 'c' if (nextPrime(b) != c) return false; return true; } // Driver code public static void Main () { if (areAdjacentPrimes(11, 13, 19)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This article is contributed by vt_m.
<?php// PHP program to check given// three numbers are primes or not. // checks whether given// number is prime or not.function isPrime($n){ // check if n is // a multiple of 2 if ($n % 2 == 0) return false; // if not, then just // check the odds for ($i = 3; $i * $i <= $n; $i += 2) if ($n % $i == 0) return false; return true;} // return next prime numberfunction nextPrime($start){ // start with next number. $next = $start + 1; // breaks after finding // next prime number while (!isPrime($next)) $next++; return $next;} // check given three numbers// are adjacent primes are not.function areAdjacentPrimes($a, $b, $c){ // check given three numbers // are primes are not. if (!isPrime($a) || !isPrime($b) || !isPrime($c)) return false; // find next prime of a $next = nextPrime($a); // If next is not same as 'a' if ($next != $b) return false; // If next is // not same as 'c' if (nextPrime($b) != $c) return false; return true;} // Driver codeif (areAdjacentPrimes(11, 13, 19)) echo "Yes";else echo "No"; // This article is contributed by mits?>
<script> // JavaScript program to check given// three numbers are// primes are not. function isPrime(n) { // check if n is a multiple of 2 if (n % 2 == 0) return false; // if not, then just check the odds for (let i = 3; i * i <= n; i += 2) if (n % i == 0) return false; return true; } // return next prime number function nextPrime(start) { // start with next number. let next = start + 1; // breaks after finding next prime number while (!isPrime(next)) next++; return next; } // check given three numbers are // adjacent primes are not. function areAdjacentPrimes(a, b, c) { // check given three numbers are primes are not. if (!isPrime(a) || !isPrime(b) || !isPrime(c)) return false; // find next prime of a let next = nextPrime(a); // If next is not same as 'a' if (next != b) return false; // If next is not same as 'c' if (nextPrime(b) != c) return false; return true; } // Driver code if (areAdjacentPrimes(11, 13, 19)) document.write("Yes"); else document.write("No"); </script>
Output :
No
Mithun Kumar
ManasChhabra2
souravghosh0416
simmytarika5
ankita_saini
Prime Number
Mathematical
Mathematical
Prime Number
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)
Modular multiplicative inverse
Count all possible paths from top left to bottom right of a mXn matrix
Fizz Buzz Implementation
Check if a number is Palindrome
Program to multiply two matrices
Merge two sorted arrays with O(1) extra space
Generate all permutation of a set in Python
Count ways to reach the n'th stair | [
{
"code": null,
"e": 25937,
"s": 25909,
"text": "\n12 May, 2022"
},
{
"code": null,
"e": 26106,
"s": 25937,
"text": "Given three numbers and check whether they are adjacent primes are not. Three prime numbers are said to be adjacent primes if there is no prime between them.Exampl... |
Weighted Job Scheduling | Set 2 (Using LIS) - GeeksforGeeks | 18 Apr, 2022
Given N jobs where every job is represented by following three elements of it.1. Start Time 2. Finish Time 3. Profit or Value AssociatedFind the maximum profit subset of jobs such that no two jobs in the subset overlap.
Examples:
Input:
Number of Jobs n = 4
Job Details {Start Time, Finish Time, Profit}
Job 1: {1, 2, 50}
Job 2: {3, 5, 20}
Job 3: {6, 19, 100}
Job 4: {2, 100, 200}
Output:
Job 1: {1, 2, 50}
Job 4: {2, 100, 200}
Explanation: We can get the maximum profit by
scheduling jobs 1 and 4 and maximum profit is 250.
In previous post, we have discussed about Weighted Job Scheduling problem. We discussed a DP solution where we basically includes or excludes current job. In this post, another interesting DP solution is discussed where we also print the Jobs. This problem is a variation of standard Longest Increasing Subsequence (LIS) problem. We need a slight change in the Dynamic Programming solution of LIS problem.
We first need to sort jobs according to start time. Let job[0..n-1] be the array of jobs after sorting. We define vector L such that L[i] is itself is a vector that stores Weighted Job Scheduling of job[0..i] that ends with job[i]. Therefore for an index i, L[i] can be recursively written as –
L[0] = {job[0]}
L[i] = {MaxSum(L[j])} + job[i] where j < i and job[j].finish <= job[i].start
= job[i], if there is no such j
For example, consider pairs {3, 10, 20}, {1, 2, 50}, {6, 19, 100}, {2, 100, 200}
After sorting we get,
{1, 2, 50}, {2, 100, 200}, {3, 10, 20}, {6, 19, 100}
Therefore,
L[0]: {1, 2, 50}
L[1]: {1, 2, 50} {2, 100, 200}
L[2]: {1, 2, 50} {3, 10, 20}
L[3]: {1, 2, 50} {6, 19, 100}
We choose the vector with highest profit. In this case, L[1].
Below is the implementation of the above idea –
C++
Java
// C++ program for weighted job scheduling using LIS#include <iostream>#include <vector>#include <algorithm>using namespace std; // A job has start time, finish time and profit.struct Job{ int start, finish, profit;}; // Utility function to calculate sum of all vector// elementsint findSum(vector<Job> arr){ int sum = 0; for (int i = 0; i < arr.size(); i++) sum += arr[i].profit; return sum;} // comparator function for sort functionint compare(Job x, Job y){ return x.start < y.start;} // The main function that finds the maximum possible// profit from given array of jobsvoid findMaxProfit(vector<Job> &arr){ // Sort arr[] by start time. sort(arr.begin(), arr.end(), compare); // L[i] stores Weighted Job Scheduling of // job[0..i] that ends with job[i] vector<vector<Job>> L(arr.size()); // L[0] is equal to arr[0] L[0].push_back(arr[0]); // start from index 1 for (int i = 1; i < arr.size(); i++) { // for every j less than i for (int j = 0; j < i; j++) { // L[i] = {MaxSum(L[j])} + arr[i] where j < i // and arr[j].finish <= arr[i].start if ((arr[j].finish <= arr[i].start) && (findSum(L[j]) > findSum(L[i]))) L[i] = L[j]; } L[i].push_back(arr[i]); } vector<Job> maxChain; // find one with max profit for (int i = 0; i < L.size(); i++) if (findSum(L[i]) > findSum(maxChain)) maxChain = L[i]; for (int i = 0; i < maxChain.size(); i++) cout << "(" << maxChain[i].start << ", " << maxChain[i].finish << ", " << maxChain[i].profit << ") ";} // Driver Functionint main(){ Job a[] = { {3, 10, 20}, {1, 2, 50}, {6, 19, 100}, {2, 100, 200} }; int n = sizeof(a) / sizeof(a[0]); vector<Job> arr(a, a + n); findMaxProfit(arr); return 0;}
// Java program for weighted job// scheduling using LISimport java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.Comparator; class Graph{ // A job has start time, finish time// and profit.static class Job{ int start, finish, profit; public Job(int start, int finish, int profit) { this.start = start; this.finish = finish; this.profit = profit; }}; // Utility function to calculate sum of all// ArrayList elementsstatic int findSum(ArrayList<Job> arr){ int sum = 0; for(int i = 0; i < arr.size(); i++) sum += arr.get(i).profit; return sum;} // The main function that finds the maximum// possible profit from given array of jobsstatic void findMaxProfit(ArrayList<Job> arr){ // Sort arr[] by start time. Collections.sort(arr, new Comparator<Job>() { @Override public int compare(Job x, Job y) { return x.start - y.start; } }); // sort(arr.begin(), arr.end(), compare); // L[i] stores Weighted Job Scheduling of // job[0..i] that ends with job[i] ArrayList<ArrayList<Job>> L = new ArrayList<>(); for(int i = 0; i < arr.size(); i++) { L.add(new ArrayList<>()); } // L[0] is equal to arr[0] L.get(0).add(arr.get(0)); // Start from index 1 for(int i = 1; i < arr.size(); i++) { // For every j less than i for(int j = 0; j < i; j++) { // L[i] = {MaxSum(L[j])} + arr[i] where j < i // and arr[j].finish <= arr[i].start if ((arr.get(j).finish <= arr.get(i).start) && (findSum(L.get(j)) > findSum(L.get(i)))) { ArrayList<Job> copied = new ArrayList<>( L.get(j)); L.set(i, copied); } } L.get(i).add(arr.get(i)); } ArrayList<Job> maxChain = new ArrayList<>(); // Find one with max profit for(int i = 0; i < L.size(); i++) if (findSum(L.get(i)) > findSum(maxChain)) maxChain = L.get(i); for(int i = 0; i < maxChain.size(); i++) { System.out.printf("(%d, %d, %d)\n", maxChain.get(i).start, maxChain.get(i).finish, maxChain.get(i).profit); }} // Driver codepublic static void main(String[] args){ Job[] a = { new Job(3, 10, 20), new Job(1, 2, 50), new Job(6, 19, 100), new Job(2, 100, 200) }; ArrayList<Job> arr = new ArrayList<>( Arrays.asList(a)); findMaxProfit(arr);}} // This code is contributed by sanjeev2552
Output:
(1, 2, 50) (2, 100, 200)
We can further optimize above DP solution by removing findSum() function. Instead, we can maintain another vector/array to store sum of maximum profit possible till job i. The implementation can be seen here.
Time complexity of above Dynamic Programming solution is O(n2) where n is the number of Jobs. Auxiliary space used by the program is O(n2).
This article is contributed by Aditya Goel. 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.
Akanksha_Rai
sanjeev2552
surinderdawra388
LIS
Dynamic Programming
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Matrix Chain Multiplication | DP-8
Longest Palindromic Substring | Set 1
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Edit Distance | DP-5
Sieve of Eratosthenes
Overlapping Subproblems Property in Dynamic Programming | DP-1
Maximum size square sub-matrix with all 1s
Find minimum number of coins that make a given value | [
{
"code": null,
"e": 26493,
"s": 26465,
"text": "\n18 Apr, 2022"
},
{
"code": null,
"e": 26713,
"s": 26493,
"text": "Given N jobs where every job is represented by following three elements of it.1. Start Time 2. Finish Time 3. Profit or Value AssociatedFind the maximum profit sub... |
Python program to find the sum of sine series - GeeksforGeeks | 10 May, 2021
Prerequisite: math
Given n and x, where n is the number of terms in the series and x is the value of the angle in degree. The Task here is, write a program to calculate the sum of sine series of x.
Formula Used:
Example:
Input: n = 10
x = 30
Output: sum of sine series is 0.5
Input: n = 10
x = 60
Output: sum of sine series is 0.87
Below is the program to calculate the sum of sine series:
Python3
# Import Moduleimport math # Create sine functiondef sin( x, n): sine = 0 for i in range(n): sign = (-1)**i pi = 22/7 y = x*(pi/180) sine += ((y**(2.0*i+1))/math.factorial(2*i+1))*sign return sine # driver nodes# Enter value in degree in xx = 10 # Enter number of termsn = 90 # call sine functionprint(round(sin(x,n),2))
Output:
0.17
Code_Mech
Mathematical
Python
Python Programs
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)
Modular multiplicative inverse
Count all possible paths from top left to bottom right of a mXn matrix
Fizz Buzz Implementation
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe | [
{
"code": null,
"e": 25961,
"s": 25933,
"text": "\n10 May, 2021"
},
{
"code": null,
"e": 25980,
"s": 25961,
"text": "Prerequisite: math"
},
{
"code": null,
"e": 26159,
"s": 25980,
"text": "Given n and x, where n is the number of terms in the series and x is th... |
Maximum points of intersection n lines | 23 Apr, 2021
You are given n straight lines. You have to find a maximum number of points of intersection with these n lines.Examples:
Input : n = 4
Output : 6
Input : n = 2
Output :1
Approach : As we have n number of line, and we have to find the maximum point of intersection using this n line. So this can be done using the combination. This problem can be thought of as a number of ways to select any two lines among n line. As every line intersects with others that are selected. So, the total number of points = nC2Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find maximum intersecting// points#include <bits/stdc++.h>using namespace std;#define ll long int // nC2 = (n)*(n-1)/2;ll countMaxIntersect(ll n){ return (n) * (n - 1) / 2;} // Driver codeint main(){ // n is number of line ll n = 8; cout << countMaxIntersect(n) << endl; return 0;}
// Java program to find maximum intersecting// points public class GFG { // nC2 = (n)*(n-1)/2; static long countMaxIntersect(long n) { return (n) * (n - 1) / 2; } // Driver code public static void main(String args[]) { // n is number of line long n = 8; System.out.println(countMaxIntersect(n)); } // This code is contributed by ANKITRAI1}
# Python3 program to find maximum# intersecting points #nC2 = (n)*(n-1)/2def countMaxIntersect(n): return int(n*(n - 1)/2) #Driver codeif __name__=='__main__': # n is number of line n = 8 print(countMaxIntersect(n)) # this code is contributed by# Shashank_Sharma
// C# program to find maximum intersecting// pointsusing System; class GFG{ // nC2 = (n)*(n-1)/2; public static long countMaxIntersect(long n) { return (n) * (n - 1) / 2; } // Driver code public static void Main() { // n is number of line long n = 8; Console.WriteLine(countMaxIntersect(n)); }}// This code is contributed by Soumik
<?PHP// PHP program to find maximum intersecting// points // nC2 = (n)*(n-1)/2;function countMaxIntersect($n){ return ($n) * ($n - 1) / 2;} // Driver code // n is number of line$n = 8;echo countMaxIntersect($n) . "\n"; // This code is contributed by ChitraNayal?>
<script> // Javascript program to find maximum intersecting// points // nC2 = (n)*(n-1)/2;function countMaxIntersect(n){ return (n) * (n - 1) / 2;} // Driver code // n is number of linevar n = 8;document.write( countMaxIntersect(n) ); </script>
28
Shashank_Sharma
ankthon
SoumikMondal
ukasp
noob2000
Combinatorial
Geometric
School Programming
Combinatorial
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count of subsets with sum equal to X
Find the K-th Permutation Sequence of first N natural numbers
Count Derangements (Permutation such that no element appears in its original position)
Print all possible strings of length k that can be formed from a set of n characters
Permutations of a given string using STL
Program for distance between two points on earth
Closest Pair of Points using Divide and Conquer algorithm
Optimum location of point to minimize total distance
Find if two rectangles overlap
Check if two given circles touch or intersect each other | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Apr, 2021"
},
{
"code": null,
"e": 151,
"s": 28,
"text": "You are given n straight lines. You have to find a maximum number of points of intersection with these n lines.Examples: "
},
{
"code": null,
"e": 202,
"s": 1... |
PostgreSQL – ROLLBACK | 30 Jun, 2022
PostgreSQL ROLLBACK command is used to undo the changes done in transactions. As we know transactions in database languages are used for purpose of large computations, for example in banks. For suppose, the employee of the bank incremented the balance record of the wrong person mistakenly then he can simply rollback and can go to the previous state.
ROLLBACK TRANSACTION;
(or)
ROLLBACK;
(or)
ROLLBACK WORK;
To understand the importance of the ROLLBACK command first let’s build a table for examples.
CREATE TABLE BankStatements (
customer_id serial PRIMARY KEY,
full_name VARCHAR NOT NULL,
balance INT
);
Now we will insert data of some customers
INSERT INTO BankStatements (
customer_id ,
full_name,
balance
)
VALUES
(1, 'Sekhar rao', 1000),
(2, 'Abishek Yadav', 500),
(3, 'Srinivas Goud', 1000);
Now as the table is ready we will understand about commit
Example 1:
We will add the data to the table in the transaction using the commit
BEGIN;
INSERT INTO BankStatements (
customer_id,
full_name,
balance
)
VALUES (
4, 'Priya chetri', 500
)
;
SELECT * FROM BankStatements;
ROLLBACK;
SELECT * FROM BankStatements;
Output:
Example 2:
BEGIN;
UPDATE BankStatements
SET balance = balance - 500
WHERE
customer_id = 1;
// displaying data before
// committing the transaction
SELECT customer_id, full_name, balance
FROM BankStatements;
UPDATE BankStatements
SET balance = balance + 500
WHERE
customer_id = 2;
ROLLBACK;
// displaying data after
// committing the transaction
SELECT customer_id, full_name, balance
FROM BankStatements;
Output:
vinayedula
Picked
Technical Scripter 2020
PostgreSQL
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - REPLACE Function
PostgreSQL - INSERT
PostgreSQL - DROP INDEX
PostgreSQL - TIME Data Type
PostgreSQL - ROW_NUMBER Function
PostgreSQL - CREATE SCHEMA
PostgreSQL - EXISTS Operator
PostgreSQL - LEFT JOIN
PostgreSQL - SELECT | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jun, 2022"
},
{
"code": null,
"e": 380,
"s": 28,
"text": "PostgreSQL ROLLBACK command is used to undo the changes done in transactions. As we know transactions in database languages are used for purpose of large computations, for exa... |
Johnson and Trotter algorithm - GeeksforGeeks | CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses
For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more
School Guide
Python Programming
Learn To Make Apps
Explore more
All Courses
TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms
Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data ScienceMachine LearningData Science
Machine Learning
Data Science
CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software DesignsSoftware Design PatternsSystem Design Tutorial
Software Design Patterns
System Design Tutorial
School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
School Programming
MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
JobsApply for JobsPost a JobJOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems
WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri
Geeks Digest
Quizzes
Geeks Campus
Gblog Articles
IDE
Campus Mantri
Sign In
Sign In
Home
Saved Videos
Courses
For Working Professionals
LIVE
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-Paced
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For Students
LIVE
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-Paced
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School Courses
School Guide
Python Programming
Learn To Make Apps
Explore more
Algorithms
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Analysis of Algorithms
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview Corner
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
Languages
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data Science
Machine Learning
Data Science
CS Subjects
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATE
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web Technologies
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software Designs
Software Design Patterns
System Design Tutorial
School Learning
School Programming
Mathematics
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUs
ISRO
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NET
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
Student
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
Curated DSA Lists
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems
Tutorials
Jobs
Apply for Jobs
Post a Job
JOB-A-THON
Practice
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
For Working Professionals
LIVE
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-Paced
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For Students
LIVE
Competitive Programming
Data Structures with C++
Data Science
Explore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-Paced
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School Courses
School Guide
Python Programming
Learn To Make Apps
Explore more
School Guide
Python Programming
Learn To Make Apps
Explore more
Algorithms
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Analysis of Algorithms
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview Corner
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
Languages
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data Science
Machine Learning
Data Science
Machine Learning
Data Science
CS Subjects
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATE
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web Technologies
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software Designs
Software Design Patterns
System Design Tutorial
Software Design Patterns
System Design Tutorial
School Learning
School Programming
School Programming
Mathematics
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUs
ISRO
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NET
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
Student
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
Curated DSA Lists
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems
Tutorials
Jobs
Apply for Jobs
Post a Job
JOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
Practice
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
GBlog
Puzzles
What's New ?
Array
Matrix
Strings
Hashing
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Graph
Searching
Sorting
Divide & Conquer
Mathematical
Geometric
Bitwise
Greedy
Backtracking
Branch and Bound
Dynamic Programming
Pattern Searching
Randomized
Johnson and Trotter algorithm
All permutations of a string using iteration
Program to reverse a string (Iterative and Recursive)
Print reverse of a string using recursion
Write a program to print all permutations of a given string
Print all distinct permutations of a given string with duplicates
Permutations of a given string using STL
All permutations of an array using STL in C++
std::next_permutation and prev_permutation in C++
Lexicographically next permutation in C++
How to print size of array parameter in C++?
How to split a string in C/C++, Python and Java?
boost::split in C++ library
Tokenizing a string in C++
getline() Function and Character Array in C++
getline (string) in C++
How to use getline() in C++ when there are blank lines in input?
scanf() and fscanf() in C
getchar_unlocked() – Faster Input in C/C++ For Competitive Programming
Problem With Using fgets()/gets()/scanf() After scanf() in C
Differentiate printable and control character in C ?
rand() and srand() in C/C++
Permutation and Combination in Python
Factorial of a large number
itertools.combinations() module in Python to print all possible combinations
Program to calculate value of nCr
Count ways to reach the nth stair using step 1, 2 or 3
Combinational Sum
Print all possible strings of length k that can be formed from a set of n characters
Johnson and Trotter algorithm
All permutations of a string using iteration
Program to reverse a string (Iterative and Recursive)
Print reverse of a string using recursion
Write a program to print all permutations of a given string
Print all distinct permutations of a given string with duplicates
Permutations of a given string using STL
All permutations of an array using STL in C++
std::next_permutation and prev_permutation in C++
Lexicographically next permutation in C++
How to print size of array parameter in C++?
How to split a string in C/C++, Python and Java?
boost::split in C++ library
Tokenizing a string in C++
getline() Function and Character Array in C++
getline (string) in C++
How to use getline() in C++ when there are blank lines in input?
scanf() and fscanf() in C
getchar_unlocked() – Faster Input in C/C++ For Competitive Programming
Problem With Using fgets()/gets()/scanf() After scanf() in C
Differentiate printable and control character in C ?
rand() and srand() in C/C++
Permutation and Combination in Python
Factorial of a large number
itertools.combinations() module in Python to print all possible combinations
Program to calculate value of nCr
Count ways to reach the nth stair using step 1, 2 or 3
Combinational Sum
Print all possible strings of length k that can be formed from a set of n characters
Difficulty Level :
Hard
We are given a sequence of numbers from 1 to n. Each permutation in the sequence that we need to generate should differ from the previous permutation by swapping just two adjacent elements of the sequence.
Examples:
Input : n = 3
Output : 123 132 312 321 231 213
Input : n = 4
Output : 1234 1243 1423 4123 4132
1432 1342 1324 3124 3142 3412 4312
4321 3421 3241 3214 2314 2341 2431
4231 4213 2413 2143 2134
A simple solution to use permutations of n-1 elements to generate permutations of n elements.
For example let us see how to generate permutations of size 3 using permutations of size 2.
Permutations of two elements are 1 2 and 2 1.Permutations of three elements can be obtained by inserting 3 at different positions in all permutations of size 2.Inserting 3 in different positions of 1 2 leads to 1 2 3, 1 3 2 and 3 1 2.Inserting 3 in different positions of 2 1 leads to 2 1 3, 2 3 1 and 3 2 1.
To generate permutations of size four, we consider all above six permutations of size three and insert 4 at different positions in every permutation.
Johnson and Trotter algorithmThe Johnson and Trotter algorithm doesn’t require to store all permutations of size n-1 and doesn’t require going through all shorter permutations. Instead, it keeps track of the direction of each element of the permutation.
Find out the largest mobile integer in a particular sequence. A directed integer is said to be mobile if it is greater than its immediate neighbor in the direction it is looking at.Switch this mobile integer and the adjacent integer to which its direction points.Switch the direction of all the elements whose value is greater than the mobile integer value.Repeat the step 1 until unless there is no mobile integer left in the sequence.
Find out the largest mobile integer in a particular sequence. A directed integer is said to be mobile if it is greater than its immediate neighbor in the direction it is looking at.
Switch this mobile integer and the adjacent integer to which its direction points.
Switch the direction of all the elements whose value is greater than the mobile integer value.
Repeat the step 1 until unless there is no mobile integer left in the sequence.
Let us see how to generate permutations of
size four. We first print 1 2 3 4. Initially
all directions are right to left.
<1 <2 <3 <4
All mobile numbers are 2, 3 and 4. The largest
mobile number is 4. We swap 3 and 4. Since 4
is largest, we don't change any direction.
<1 <2 <4 <3
4 is the largest mobile. We swap it with 2.
<1 <4 <2 <3
4 is the largest mobile. We swap it with 1.
<4 <1 <2 <3
3 is largest mobile. We swap it with 2 and
change directions of greater elements.
4> <1 <3 <2
4 is largest mobile. We swap it with 3.
<4 1> <2 <3
We proceed this way and print all permutations.
Below is the implementation of the approach.
C++
Java
C#
// CPP program to print all permutations using// Johnson and Trotter algorithm.#include <bits/stdc++.h>using namespace std; bool LEFT_TO_RIGHT = true;bool RIGHT_TO_LEFT = false; // Utility functions for finding the// position of largest mobile integer in a[].int searchArr(int a[], int n, int mobile){ for (int i = 0; i < n; i++) if (a[i] == mobile) return i + 1;} // To carry out step 1 of the algorithm i.e.// to find the largest mobile integer.int getMobile(int a[], bool dir[], int n){ int mobile_prev = 0, mobile = 0; for (int i = 0; i < n; i++) { // direction 0 represents RIGHT TO LEFT. if (dir[a[i]-1] == RIGHT_TO_LEFT && i!=0) { if (a[i] > a[i-1] && a[i] > mobile_prev) { mobile = a[i]; mobile_prev = mobile; } } // direction 1 represents LEFT TO RIGHT. if (dir[a[i]-1] == LEFT_TO_RIGHT && i!=n-1) { if (a[i] > a[i+1] && a[i] > mobile_prev) { mobile = a[i]; mobile_prev = mobile; } } } if (mobile == 0 && mobile_prev == 0) return 0; else return mobile;} // Prints a single permutationint printOnePerm(int a[], bool dir[], int n){ int mobile = getMobile(a, dir, n); int pos = searchArr(a, n, mobile); // swapping the elements according to the // direction i.e. dir[]. if (dir[a[pos - 1] - 1] == RIGHT_TO_LEFT) swap(a[pos-1], a[pos-2]); else if (dir[a[pos - 1] - 1] == LEFT_TO_RIGHT) swap(a[pos], a[pos-1]); // changing the directions for elements // greater than largest mobile integer. for (int i = 0; i < n; i++) { if (a[i] > mobile) { if (dir[a[i] - 1] == LEFT_TO_RIGHT) dir[a[i] - 1] = RIGHT_TO_LEFT; else if (dir[a[i] - 1] == RIGHT_TO_LEFT) dir[a[i] - 1] = LEFT_TO_RIGHT; } } for (int i = 0; i < n; i++) cout << a[i]; cout << " ";} // To end the algorithm for efficiency it ends// at the factorial of n because number of// permutations possible is just n!.int fact(int n){ int res = 1; for (int i = 1; i <= n; i++) res = res * i; return res;} // This function mainly calls printOnePerm()// one by one to print all permutations.void printPermutation(int n){ // To store current permutation int a[n]; // To store current directions bool dir[n]; // storing the elements from 1 to n and // printing first permutation. for (int i = 0; i < n; i++) { a[i] = i + 1; cout << a[i]; } cout << endl; // initially all directions are set // to RIGHT TO LEFT i.e. 0. for (int i = 0; i < n; i++) dir[i] = RIGHT_TO_LEFT; // for generating permutations in the order. for (int i = 1; i < fact(n); i++) printOnePerm(a, dir, n);} // Driver codeint main(){ int n = 4; printPermutation(n); return 0;}
// Java program to print all // permutations using Johnson// and Trotter algorithm.import java.util.*;import java.lang.*; public class GfG{ private final static boolean LEFT_TO_RIGHT = true; private final static boolean RIGHT_TO_LEFT = false; // Utility functions for // finding the position // of largest mobile // integer in a[]. public static int searchArr(int a[], int n, int mobile) { for (int i = 0; i < n; i++) if (a[i] == mobile) return i + 1; return 0; } // To carry out step 1 // of the algorithm i.e. // to find the largest // mobile integer. public static int getMobile(int a[], boolean dir[], int n) { int mobile_prev = 0, mobile = 0; for (int i = 0; i < n; i++) { // direction 0 represents // RIGHT TO LEFT. if (dir[a[i] - 1] == RIGHT_TO_LEFT && i != 0) { if (a[i] > a[i - 1] && a[i] > mobile_prev) { mobile = a[i]; mobile_prev = mobile; } } // direction 1 represents // LEFT TO RIGHT. if (dir[a[i] - 1] == LEFT_TO_RIGHT && i ! =n - 1) { if (a[i] > a[i + 1] && a[i] > mobile_prev) { mobile = a[i]; mobile_prev = mobile; } } } if (mobile == 0 && mobile_prev == 0) return 0; else return mobile; } // Prints a single // permutation public static int printOnePerm(int a[], boolean dir[], int n) { int mobile = getMobile(a, dir, n); int pos = searchArr(a, n, mobile); // swapping the elements // according to the // direction i.e. dir[]. if (dir[a[pos - 1] - 1] == RIGHT_TO_LEFT) { int temp = a[pos - 1]; a[pos - 1] = a[pos - 2]; a[pos - 2] = temp; } else if (dir[a[pos - 1] - 1] == LEFT_TO_RIGHT) { int temp = a[pos]; a[pos] = a[pos - 1]; a[pos - 1] = temp; } // changing the directions // for elements greater // than largest mobile integer. for (int i = 0; i < n; i++) { if (a[i] > mobile) { if (dir[a[i] - 1] == LEFT_TO_RIGHT) dir[a[i] - 1] = RIGHT_TO_LEFT; else if (dir[a[i] - 1] == RIGHT_TO_LEFT) dir[a[i] - 1] = LEFT_TO_RIGHT; } } for (int i = 0; i < n; i++) System.out.print(a[i]); System.out.print(" "); return 0; } // To end the algorithm // for efficiency it ends // at the factorial of n // because number of // permutations possible // is just n!. public static int fact(int n) { int res = 1; for (int i = 1; i <= n; i++) res = res * i; return res; } // This function mainly // calls printOnePerm() // one by one to print // all permutations. public static void printPermutation(int n) { // To store current // permutation int[] a = new int[n]; // To store current // directions boolean[] dir = new boolean[n]; // storing the elements // from 1 to n and // printing first permutation. for (int i = 0; i < n; i++) { a[i] = i + 1; System.out.print(a[i]); } System.out.print("\n"); // initially all directions // are set to RIGHT TO // LEFT i.e. 0. for (int i = 0; i < n; i++) dir[i] = RIGHT_TO_LEFT; // for generating permutations // in the order. for (int i = 1; i < fact(n); i++) printOnePerm(a, dir, n); } // Driver function public static void main(String argc[]) { int n = 4; printPermutation(n); } } // This code is contributed by Sagar Shukla
// Java program to print all // permutations using Johnson// and Trotter algorithm.using System; public class GfG{ private static bool LEFT_TO_RIGHT = true; private static bool RIGHT_TO_LEFT = false; // Utility functions for // finding the position // of largest mobile // integer in a[]. public static int searchArr(int []a, int n, int mobile) { for (int i = 0; i < n; i++) if (a[i] == mobile) return i + 1; return 0; } // To carry out step 1 // of the algorithm i.e. // to find the largest // mobile integer. public static int getMobile(int []a, bool []dir, int n) { int mobile_prev = 0, mobile = 0; for (int i = 0; i < n; i++) { // direction 0 represents // RIGHT TO LEFT. if (dir[a[i] - 1] == RIGHT_TO_LEFT && i != 0) { if (a[i] > a[i - 1] && a[i] > mobile_prev) { mobile = a[i]; mobile_prev = mobile; } } // direction 1 represents // LEFT TO RIGHT. if (dir[a[i] - 1] == LEFT_TO_RIGHT && i!=n - 1) { if (a[i] > a[i + 1] && a[i] > mobile_prev) { mobile = a[i]; mobile_prev = mobile; } } } if (mobile == 0 && mobile_prev == 0) return 0; else return mobile; } // Prints a single // permutation public static int printOnePerm(int []a, bool []dir, int n) { int mobile = getMobile(a, dir, n); int pos = searchArr(a, n, mobile); // swapping the elements // according to the // direction i.e. dir[]. if (dir[a[pos - 1] - 1] == RIGHT_TO_LEFT) { int temp = a[pos - 1]; a[pos - 1] = a[pos - 2]; a[pos - 2] = temp; } else if (dir[a[pos - 1] - 1] == LEFT_TO_RIGHT) { int temp = a[pos]; a[pos] = a[pos - 1]; a[pos - 1] = temp; } // changing the directions // for elements greater // than largest mobile integer. for (int i = 0; i < n; i++) { if (a[i] > mobile) { if (dir[a[i] - 1] == LEFT_TO_RIGHT) dir[a[i] - 1] = RIGHT_TO_LEFT; else if (dir[a[i] - 1] == RIGHT_TO_LEFT) dir[a[i] - 1] = LEFT_TO_RIGHT; } } for (int i = 0; i < n; i++) Console.Write(a[i]); Console.Write(" "); return 0; } // To end the algorithm // for efficiency it ends // at the factorial of n // because number of // permutations possible // is just n!. public static int fact(int n) { int res = 1; for (int i = 1; i <= n; i++) res = res * i; return res; } // This function mainly // calls printOnePerm() // one by one to print // all permutations. public static void printPermutation(int n) { // To store current // permutation int []a = new int[n]; // To store current // directions bool []dir = new bool[n]; // storing the elements // from 1 to n and // printing first permutation. for (int i = 0; i < n; i++) { a[i] = i + 1; Console.Write(a[i]); } Console.Write("\n"); // initially all directions // are set to RIGHT TO // LEFT i.e. 0. for (int i = 0; i < n; i++) dir[i] = RIGHT_TO_LEFT; // for generating permutations // in the order. for (int i = 1; i < fact(n); i++) printOnePerm(a, dir, n); } // Driver function public static void Main() { int n = 4; printPermutation(n); } } // This code is contributed by nitin mittal.
1234 1243 1423 4123 4132 1432 1342 1324
3124 3142 3412 4312 4321 3421 3241 3214
2314 2341 2431 4231 4213 2413 2143 2134
nitin mittal
Jean-PhilippeDrecourt
Combinatorial
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count of subsets with sum equal to X
Python program to get all subsets of given size of a set
Heap's Algorithm for generating permutations
Distinct permutations of the string | Set 2
Make all combinations of size k
Count Derangements (Permutation such that no element appears in its original position)
Print all subsets of given size of a set
Find all distinct subsets of a given set using BitMasking Approach
Ways to sum to N using Natural Numbers up to K with repetitions allowed
Print all permutations in sorted (lexicographic) order | [
{
"code": null,
"e": 419,
"s": 0,
"text": "CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data Sc... |
Minimum possible final health of the last monster in a game - GeeksforGeeks | 05 Aug, 2021
Given N monsters, each monster has initial health h[i] which is an integer. A monster is alive if its health is greater than 0. In each turn a random monster kills another random monster, the monster which is attacked, its health reduces by the amount of health of the attacking monster. This process is continued until a single monster is left. What will be the minimum possible health of the last remained monster. In others words, the task is to play the game in such a way that monster which is left in the end has the least possible health.Examples:
Input: h[] = {2, 14, 28, 56} Output: 2 When only the first monster keeps on attacking the remaining 3 monsters, the final health of the last monster will be 2, which is minimum.Input: h[] = {7, 17, 9, 100, 25} Output: 1Input: h[] = {5, 5, 5} Output: 5
Approach: It can be observed from the problem that one has to find a certain value of health of the monster, let’s say k which can kill other monsters including self. Once this crucial observation is made problem becomes easy. Suppose we have two monsters with health h1 and h2, and let’s say h2 > h1. We can see that in a random choice, the optimal way would be to pick a monster with lower health and reduce the health of the other monster till its health becomes less than the health of the attacking monster. After that we will pick the second monster whose health has became less than h1 and the process will continue till only one monster is left. So at last we will be left with the minimum value which would be gcd(h1, h2). This gcd method can be extended for all the monsters. So our resultant minimum possible health of the monster will be the gcd of all the health of given monsters i.e. H(min) = gcd(h1, h2, ..., hn).Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the gcd of two numbersint gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Function to return the minimum// possible health for the monsterint solve(int* health, int n){ // gcd of first and second element int currentgcd = gcd(health[0], health[1]); // gcd for all subsequent elements for (int i = 2; i < n; ++i) { currentgcd = gcd(currentgcd, health[i]); } return currentgcd;} // Driver codeint main(){ int health[] = { 4, 6, 8, 12 }; int n = sizeof(health) / sizeof(health[0]); cout << solve(health, n); return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the gcd of two numbersstatic int gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Function to return the minimum// possible health for the monsterstatic int solve(int health[], int n){ // gcd of first and second element int currentgcd = gcd(health[0], health[1]); // gcd for all subsequent elements for (int i = 2; i < n; ++i) { currentgcd = gcd(currentgcd, health[i]); } return currentgcd;} // Driver codepublic static void main(String args[]){ int health[] = { 4, 6, 8, 12 }; int n = health.length; System.out.println(solve(health, n));}} // This code is contributed by// Surendra_Gangwar
# Python3 implementation of the approach # Function to return the gcd of two numbersdef gcd(a, b): if (a == 0): return b return gcd(b % a, a) # Function to return the minimum# possible health for the monsterdef solve(health, n): # gcd of first and second element currentgcd = gcd(health[0], health[1]) # gcd for all subsequent elements for i in range(2, n): currentgcd = gcd(currentgcd, health[i]) return currentgcd # Driver codehealth = [4, 6, 8, 12]n = len(health)print(solve(health, n)) # This code is contributed by mohit kumar
// C# implementation of the approachusing System; class GFG{ // Function to return the gcd of two numbersstatic int gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Function to return the minimum// possible health for the monsterstatic int solve(int []health, int n){ // gcd of first and second element int currentgcd = gcd(health[0], health[1]); // gcd for all subsequent elements for (int i = 2; i < n; ++i) { currentgcd = gcd(currentgcd, health[i]); } return currentgcd;} // Driver codepublic static void Main(String []args){ int []health = { 4, 6, 8, 12 }; int n = health.Length; Console.WriteLine(solve(health, n));}} // This code is contributed by Arnab Kundu
<?php// PHP implementation of the approach // Function to return the gcd of two numbersfunction gcd($a, $b){ if ($a == 0) return $b; return gcd($b % $a, $a);} // Function to return the minimum// possible health for the monsterfunction solve($health, $n){ // gcd of first and second element $currentgcd = gcd($health[0], $health[1]); // gcd for all subsequent elements for ($i = 2; $i < $n; ++$i) { $currentgcd = gcd($currentgcd, $health[$i]); } return $currentgcd;} // Driver code$health = array(4, 6, 8, 12);$n = sizeof($health);echo solve($health, $n); // This code is contributed by Akanksha Rai?>
<script> // Javascript implementation of the approach // Function to return the gcd of two numbersfunction gcd(a, b){ if (a == 0) return b; return gcd(b % a, a);} // Function to return the minimum// possible health for the monsterfunction solve(health, n){ // gcd of first and second element let currentgcd = gcd(health[0], health[1]); // gcd for all subsequent elements for (let i = 2; i < n; ++i) { currentgcd = gcd(currentgcd, health[i]); } return currentgcd;} // Driver Code let health = [ 4, 6, 8, 12 ]; let n = health.length; document.write(solve(health, n)); // This code is contributed by target_2.</script>
2
Time Complexity: O(N * log(MAX)) where N is the size of the array and MAX is the maximum number in the array. We are running a loop that takes O(N) time. Also, the GCD function takes O(log(min(A, B)), and in the worst case when A and B are the same and A = B = MAX then the GCD function takes O(log(MAX)) time. So, overall time complexity = O(N * log(MAX))Auxiliary Space: O(log(MAX))
mohit kumar 29
SURENDRA_GANGWAR
Akanksha_Rai
andrew1234
target_2
pankajsharmagfg
GCD-LCM
HCF
Algorithms
Greedy
Mathematical
Greedy
Mathematical
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
How to write a Pseudo Code?
Understanding Time Complexity with Simple Examples
Introduction to Algorithms
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Program for array rotation
Write a program to print all permutations of a given string | [
{
"code": null,
"e": 26201,
"s": 26173,
"text": "\n05 Aug, 2021"
},
{
"code": null,
"e": 26758,
"s": 26201,
"text": "Given N monsters, each monster has initial health h[i] which is an integer. A monster is alive if its health is greater than 0. In each turn a random monster kills... |
Golang | How to find the index of rune in the string? - GeeksforGeeks | 28 Aug, 2019
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding.In the Go strings, you can also find the first index of the specified rune in the given string using IndexRune() function. This function returns the index of the first instance of the Unicode code point, i.e, specified rune, or -1 if the specified rune is not present in the given string. If the rune is utf8.RuneError, then it returns the first instance of any invalid UTF-8 byte sequence. It is defined under the string package so, you have to import string package in your program for accessing IndexRune function.
Syntax:
func IndexRune(str string, r rune) int
Example 1:
// Go program to illustrate how to find// the index value of the given runepackage main import ( "fmt" "strings") func main() { // Creating and Finding the first index // of the rune in the given string // Using IndexRunefunction res1 := strings.IndexRune("****Welcome to GeeksforGeeks****", 60) res2 := strings.IndexRune("Learning how to trim"+ " a slice of bytes", 'r') res3 := strings.IndexRune("GeeksforGeeks", 'G') // Display the results fmt.Println("Index Value 1: ", res1) fmt.Println("Index Value 2: ", res2) fmt.Println("Index Value 3: ", res3) }
Output:
Index Value 1: -1
Index Value 2: 3
Index Value 3: 0
Example 2:
// Go program to illustrate how to find// the index value of the given runepackage main import ( "fmt" "strings") func main() { // Creating and initializing a string // Using shorthand declaration string_1 := "Welcome to GeeksforGeeks" string_2 := "AppleAppleAppleAppleAppleApple" string_3 := "%G%E%E%K%S" // Creating and initializing rune var r1, r2, r3 rune r1 = 'R' r2 = 'l' r3 = 42 // Finding the first index // of the given rune // Using IndexRune function res1 := strings.IndexRune(string_1, r1) res2 := strings.IndexRune(string_2, r2) res3 := strings.IndexRune(string_3, r3) // Display the results fmt.Printf("String 1: %s , Rune 1:%q , Index Value: %d", string_1, r1, res1) fmt.Printf("\nString 2: %s , Rune 2:%q , Index Value: %d", string_2, r2, res2) fmt.Printf("\nString 3: %s , Rune 3:%q , Index Value: %d", string_3, r3, res3) }
Output:
String 1: Welcome to GeeksforGeeks , Rune 1:'R' , Index Value: -1
String 2: AppleAppleAppleAppleAppleApple , Rune 2:'l' , Index Value: 3
String 3: %G%E%E%K%S , Rune 3:'*' , Index Value: -1
Golang
Golang-String
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
Arrays in Go
Slices in Golang
Golang Maps
Inheritance in GoLang
Different Ways to Find the Type of Variable in Golang
Interfaces in Golang
How to Trim a String in Golang?
How to compare times in Golang?
How to Parse JSON in Golang? | [
{
"code": null,
"e": 25653,
"s": 25625,
"text": "\n28 Aug, 2019"
},
{
"code": null,
"e": 26393,
"s": 25653,
"text": "In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every characte... |
Inserting JSON data into a table in Cassandra - GeeksforGeeks | 17 Mar, 2021
In this article, you will be able to understand how you can insert JSON data into a table in Cassandra and will discuss with the help of an example and then finally conclude the importance of JSON insertion. Let’s discuss it one by one.
Overview :It is a practical way than cqlsh to insert column and column values. In JSON values inserted in the form of string if they are not a number for example id with datatype uuid inserted as a string but will be stored as uuid. For better understanding now, first, we will see insertion data using cqlsh commands and then will discuss how you can insert data by using JSON format.
Example :Let’s consider you have existing keyspace namely cluster1 and then first we will create a user_data table by using the CQL command as follows.
use cluster1;
create table user_record
(
user_id uuid,
first_name varchar,
last_name varchar,
company varchar,
primary key(user_id)
);
Method-1 : Insertion by using cqlsh commands –
insert into user_record(user_id, first_name, last_name, company)
values(101aa90a-4bba-211f-a4fb-00001a101cda,'Ashish','Rana','abc');
insert into user_record(user_id, first_name, last_name, company)
values(102aa90a-4bba-211f-a4fb-00002a102cda,'Ayush','NA','abc');
After insertion, you can use the following cql command to verify the inserted data.
select * from user_record;
Output –
Method-2 :Insertion by using JSON format –To insert data in JSON format, JSON keyword will be added to the INSERT command as follows.
INSERT INTO cluster1.user_record JSON '{
"user_id" : "103aa90a-4bba-211f-a4fb-00001a101cda",
"first_name" : "Ashish",
"last_name" : "Rana",
"company" : "abc" }';
Using JSON format if you do not insert any value for any column then a null value will be entered automatically as you can see in the below given example.
INSERT INTO cluster1.user_record JSON '{
"user_id" : "104aa90a-4bba-211f-a4fb-00001a101cda",
"first_name" : "Ashish",
"last_name" : "Rana"
}';
After insertion, you can use the following cql command to verify the inserted data.
select * from user_record;
Output –
Apache
NoSQL
Articles
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Complexity and Space Complexity
Docker - COPY Instruction
Time complexities of different data structures
Difference between Class and Object
SQL | Date functions
SQL | WITH clause
ACID Properties in DBMS
SQL query to find second highest salary?
Normal Forms in DBMS
Introduction of B-Tree | [
{
"code": null,
"e": 25666,
"s": 25638,
"text": "\n17 Mar, 2021"
},
{
"code": null,
"e": 25903,
"s": 25666,
"text": "In this article, you will be able to understand how you can insert JSON data into a table in Cassandra and will discuss with the help of an example and then finall... |
Transform One String to Another using Minimum Number of Given Operation - GeeksforGeeks | 02 May, 2022
Given two strings A and B, the task is to convert A to B if possible. The only operation allowed is to put any character from A and insert it at front. Find if it’s possible to convert the string. If yes, then output minimum no. of operations required for transformation.
Examples:
Input: A = "ABD", B = "BAD"
Output: 1
Explanation: Pick B and insert it at front.
Input: A = "EACBD", B = "EABCD"
Output: 3
Explanation: Pick B and insert at front, EACBD => BEACD
Pick A and insert at front, BEACD => ABECD
Pick E and insert at front, ABECD => EABCD
Checking whether a string can be transformed to another is simple. We need to check whether both strings have same number of characters and same set of characters. This can be easily done by creating a count array for first string and checking if second string has same count of every character. How to find minimum number of operations when we are sure that we can transform A to B? The idea is to start matching from last characters of both strings. If last characters match, then our task reduces to n-1 characters. If last characters don’t match, then find the position of B’s mismatching character in A. The difference between two positions indicates that these many characters of A must be moved before current character of A.
Below is complete algorithm. 1) Find if A can be transformed to B or not by first creating a count array for all characters of A, then checking with B if B has same count for every character. 2) Initialize result as 0. 3) Start traversing from end of both strings. ......a) If current characters of A and B match, i.e., A[i] == B[j] .........then do i = i-1 and j = j-1 b) If current characters don’t match, then search B[j] in remaining .........A. While searching, keep incrementing result as these characters .........must be moved ahead for A to B transformation.
Below are the implementations based on this idea.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find minimum number of operations required// to transform one string to other#include <bits/stdc++.h>using namespace std; // Function to find minimum number of operations required to// transform A to B.int minOps(string& A, string& B){ int m = A.length(), n = B.length(); // This parts checks whether conversion is possible or not if (n != m) return -1; int count[256]; memset(count, 0, sizeof(count)); // count characters in A for (int i = 0; i < n; i++) count[A[i]]++; // subtract count for every character in B for (int i = 0; i < n; i++) count[B[i]]--; // Check if all counts become 0 for (int i = 0; i < 256; i++) if (count[i]) return -1; // This part calculates the number of operations // required int res = 0; for (int i = n - 1, j = n - 1; i >= 0;) { // If there is a mismatch, then keep incrementing // result 'res' until B[j] is not found in A[0..i] while (i >= 0 && A[i] != B[j]) { i--; res++; } // If A[i] and B[j] match if (i >= 0) { i--; j--; } } return res;} // Driver programint main(){ string A = "EACBD"; string B = "EABCD"; cout << "Minimum number of operations required is " << minOps(A, B); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// C program to find minimum number of operations required// to transform one string to other#include <stdio.h>#include <string.h> // Function to find minimum number of operations required to// transform A to B.int minOps(char A[], char B[]){ int m = strlen(A), n = strlen(B); // This parts checks whether conversion is // possible or not if (n != m) return -1; int count[256]; for (int i = 0; i < 256; i++) count[i] = 0; // count characters in A for (int i = 0; i < n; i++) count[A[i]]++; // subtract count for every character in B for (int i = 0; i < n; i++) count[B[i]]--; // Check if all counts become 0 for (int i = 0; i < 256; i++) if (count[i]) return -1; // This part calculates the number of operations // required int res = 0; for (int i = n - 1, j = n - 1; i >= 0;) { // If there is a mismatch, then keep incrementing // result 'res' until B[j] is not found in A[0..i] while (i >= 0 && A[i] != B[j]) { i--; res++; } // If A[i] and B[j] match if (i >= 0) { i--; j--; } } return res;} // Driver programint main(){ char A[] = "EACBD"; char B[] = "EABCD"; printf("Minimum number of operations required is %d", minOps(A, B)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java program to find minimum number of operations// required to transform one string to otherimport java.io.*;import java.util.*; public class GFG { // Function to find minimum number of operations // required to transform A to B. public static int minOps(String A, String B) { // This parts checks whether conversion is possible // or not if (A.length() != B.length()) return -1; int i, j, res = 0; int count[] = new int[256]; // count characters in A // subtract count for every character in B for (i = 0; i < A.length(); i++) { count[A.charAt(i)]++; count[B.charAt(i)]--; } // Check if all counts become 0 for (i = 0; i < 256; i++) if (count[i] != 0) return -1; i = A.length() - 1; j = B.length() - 1; while (i >= 0) { // If there is a mismatch, then keep // incrementing result 'res' until B[j] is not // found in A[0..i] if (A.charAt(i) != B.charAt(j)) res++; else j--; i--; } return res; } // Driver code public static void main(String[] args) { String A = "EACBD"; String B = "EABCD"; System.out.println( "Minimum number of operations required is " + minOps(A, B)); }} // This code is contributed by Aditya Kumar (adityakumar129)
# Python program to find the minimum number of# operations required to transform one string to other # Function to find minimum number of operations required# to transform A to Bdef minOps(A, B): m = len(A) n = len(B) # This part checks whether conversion is possible or not if n != m: return -1 count = [0] * 256 for i in range(n): # count characters in A count[ord(B[i])] += 1 for i in range(n): # subtract count for every char in B count[ord(A[i])] -= 1 for i in range(256): # Check if all counts become 0 if count[i]: return -1 # This part calculates the number of operations required res = 0 i = n-1 j = n-1 while i >= 0: # if there is a mismatch, then keep incrementing # result 'res' until B[j] is not found in A[0..i] while i>= 0 and A[i] != B[j]: i -= 1 res += 1 # if A[i] and B[j] match if i >= 0: i -= 1 j -= 1 return res # Driver programA = "EACBD"B = "EABCD"print ("Minimum number of operations required is " + str(minOps(A,B)))# This code is contributed by Bhavya Jain
// C# program to find minimum number of// operations required to transform one// string to otherusing System; class GFG{ // Function to find minimum number of// operations required to transform// A to B.public static int minOps(string A, string B){ // This parts checks whether // conversion is possible or not if (A.Length != B.Length) { return -1; } int i, j, res = 0; int[] count = new int [256]; // count characters in A // subtract count for every // character in B for (i = 0; i < A.Length; i++) { count[A[i]]++; count[B[i]]--; } // Check if all counts become 0 for (i = 0; i < 256; i++) { if (count[i] != 0) { return -1; } } i = A.Length - 1; j = B.Length - 1; while (i >= 0) { // If there is a mismatch, then // keep incrementing result 'res' // until B[j] is not found in A[0..i] if (A[i] != B[j]) { res++; } else { j--; } i--; } return res;} // Driver codepublic static void Main(string[] args){ string A = "EACBD"; string B = "EABCD"; Console.WriteLine("Minimum number of " + "operations required is " + minOps(A, B));}} // This code is contributed by Shrikant13
<?php// PHP program to find minimum number of// operations required to transform one string to other // Function to find minimum number of operations required to transform// A to B.function minOps($A, $B){ $m = strlen($A); $n = strlen($B); // This parts checks whether conversion is // possible or not if ($n != $m) return -1; $count = array_fill(0,256,NULL); for ($i=0; $i<$n; $i++) // count characters in A $count[ord($B[$i])]++; for ($i=0; $i<$n; $i++) // subtract count for $count[ord($A[$i])]--; // every character in B for ($i=0; $i<256; $i++) // Check if all counts become 0 if ($count[$i]) return -1; // This part calculates the number of operations required $res = 0; for ($i=$n-1, $j=$n-1; $i>=0; ) { // If there is a mismatch, then keep incrementing // result 'res' until B[j] is not found in A[0..i] while ($i>=0 && $A[$i] != $B[$j]) { $i--; $res++; } // If A[i] and B[j] match if ($i >= 0) { $i--; $j--; } } return $res;} // Driver program $A = "EACBD";$B = "EABCD";echo "Minimum number of operations ". "required is ". minOps($A, $B);return 0;?>
<script> // Javascript program to find minimum number// of operations required to transform one// string to other // Function to find minimum number of// operations required to transform// A to B.function minOps(A, B){ // This parts checks whether conversion // is possible or not if (A.length != B.length) return -1; let i, j, res = 0; let count = new Array(256); for(let i = 0; i < 256; i++) { count[i] = 0; } // count characters in A // Subtract count for every character in B for(i = 0; i < A.length; i++) { count[A[i].charCodeAt(0)]++; count[B[i].charCodeAt(0)]--; } // Check if all counts become 0 for(i = 0; i < 256; i++) if (count[i] != 0) return -1; i = A.length - 1; j = B.length - 1; while(i >= 0) { // If there is a mismatch, then // keep incrementing result 'res' // until B[j] is not found in A[0..i] if (A[i] != B[j]) res++; else j--; i--; } return res; } // Driver codelet A = "EACBD";let B = "EABCD"; document.write("Minimum number of " + "operations required is " + minOps(A, B)); // This code is contributed by avanitrachhadiya2155 </script>
Output:
Minimum number of operations required is 3
Time Complexity: O(n), please note that i is always decremented (in while loop and in if), and the for loop starts from n-1 and runs while i >= 0.
Thanks to Gaurav Ahirwar for above solution.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
dipesh_jain
shrikanth13
ukasp
avanitrachhadiya2155
vaishnavichouhan25
amartyaghoshgfg
adityakumar129
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Different methods to reverse a string in C/C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Check whether two strings are anagram of each other
Top 50 String Coding Problems for Interviews | [
{
"code": null,
"e": 26015,
"s": 25987,
"text": "\n02 May, 2022"
},
{
"code": null,
"e": 26287,
"s": 26015,
"text": "Given two strings A and B, the task is to convert A to B if possible. The only operation allowed is to put any character from A and insert it at front. Find if it’... |
PyQtGraph - Setting Pen of Line in Line Graph - GeeksforGeeks | 15 Jan, 2022
In this article we will see how we can set pen of the line in line graph of the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) A line chart or line plot or line graph or curve chart is a type of chart which displays information as a series of data points called ‘markers’ connected by straight line segments. It is a basic type of chart common in many fields. Line graph is created with the help of plot class in PyQtGraph. Pen is basically painter object used to draw the line on the window, with the help of pen we can set the color of the line.
We can create a plot window and create lines on it with the help of commands given below
# creating a pyqtgraph plot window
plt = pg.plot()
# plotting line in green color
# with dot symbol as x, not a mandatory field
line = plt.plot(x, y, pen='g', symbol='x', symbolPen='g', symbolBrush=0.2, name='green')
In order to do this we use setPen method with the line objectSyntax : line.setPen(QColor(168, 34, 3))Argument : It takes QColor/QBrush/QPen object as argumentReturn : It returns None
Below is the implementation
Python3
# importing Qt widgetsfrom PyQt5.QtWidgets import * import sys # importing pyqtgraph as pgimport pyqtgraph as pgfrom PyQt5.QtGui import * # Bar Graph classclass BarGraphItem(pg.BarGraphItem): # constructor which inherit original # BarGraphItem def __init__(self, *args, **kwargs): pg.BarGraphItem.__init__(self, *args, **kwargs) # creating a mouse double click event def mouseDoubleClickEvent(self, e): # setting scale self.setScale(0.2) class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("PyQtGraph") # setting geometry self.setGeometry(100, 100, 600, 500) # icon icon = QIcon("skin.png") # setting icon to the window self.setWindowIcon(icon) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a widget object widget = QWidget() # creating a new label label = QLabel("GeeksforGeeks Line Plot") # making it multiline label.setWordWrap(True) # y values to plot by line 1 y = [2, 8, 6, 8, 6, 11, 14, 13, 18, 19] # y values to plot by line 2 y2 = [3, 1, 5, 8, 9, 11, 16, 17, 14, 16] x = range(0, 10) # create plot window object plt = pg.plot() # showing x and y grids plt.showGrid(x = True, y = True) # adding legend plt.addLegend() # set properties of the label for y axis plt.setLabel('left', 'Vertical Values', units ='y') # set properties of the label for x axis plt.setLabel('bottom', 'Horizontal Values', units ='s') # setting horizontal range plt.setXRange(0, 10) # setting vertical range plt.setYRange(0, 20) # plotting line in green color # with dot symbol as x, not a mandatory field line1 = plt.plot(x, y, pen ='g', symbol ='x', symbolPen ='g', symbolBrush = 0.2, name ='green') # plotting line2 with blue color # with dot symbol as o line2 = plt.plot(x, y2, pen ='b', symbol ='o', symbolPen ='b', symbolBrush = 0.2, name ='blue') # setting pen of the line 1 line1.setPen(QColor(168, 34, 3)) # label minimum width label.setMinimumWidth(150) # Creating a grid layout layout = QGridLayout() # setting this layout to the widget widget.setLayout(layout) # adding label to the layout layout.addWidget(label, 1, 0) # plot window goes on right side, spanning 3 rows layout.addWidget(plt, 0, 1, 3, 1) # setting this widget as central widget of the main window self.setCentralWidget(widget) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
surindertarika1234
sagartomar9927
ruhelaa48
Python-gui
Python-PyQt
Python-PyQtGraph
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
Convert integer to string in Python | [
{
"code": null,
"e": 26119,
"s": 26091,
"text": "\n15 Jan, 2022"
},
{
"code": null,
"e": 26886,
"s": 26119,
"text": "In this article we will see how we can set pen of the line in line graph of the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python tha... |
Hacking Tools for Penetration Testing - Fsociety in Kali Linux - GeeksforGeeks | 18 Jul, 2021
Fsociety is a free and open-source tool available on GitHub which is used as an information-gathering tool. Fsociety is used to scanning websites for information gathering and finding vulnerabilities in websites and web apps. Fsociety is one of the easiest and useful tools for performing reconnaissance on websites and web apps. The Fsociety tool is also available for Linux, Windows, and Android phones ( termux ), which is coded in both bash and Python. Fsociety provides a command-line interface that you can run on Kali Linux. This tool can be used to get information about our target(domain). We can target any domain using Fsociety. The interactive console provides a number of helpful features, such as command completion and contextual help. Fsociety is based upon Mr. Robotincludes series.
1. Information gathering
The first step to security assessment or ethical hacking is collecting all the possible information about the target, and that is why this Fsociety provides some famous information-gathering tools such as:
Nmap
Setoolkit
Host To IP
WPScan
CMS Scanner
XSStrike
Dork – Google Dorks Passive Vulnerability Auditor
Scan A server’s Users
Crips
2. Password Attacks
For performing any kind of password attack, Fsociety has mainly 2 tools. Those are Cupp – for generating password lists, Nc rack – network Authentication protocol.
3. Wireless Testing
It also has tools such as Reaver Pixiewps and Bluetooth Honeypot for performing any kind of wireless attack.
4. Exploitation Tools
After you are done with information gathering and finding any kind of vulnerabilities, the next thing you have to do is to exploit those vulnerabilities, so for exploiting the vulnerabilities Fsociety provides the following tools:
sqlmap
ATSCAN
Shellnoob
Commix
FTP Auto Bypass
JBoss Autopwn
5. Sniffing & Spoofing
Fsociety lets you perform Sniffing and Spoofing by providing several numbers of tools such as:
Setoolkit
SSLtrip
pyPISHER
SMTP Mailer
6. Web Hacking
Web hacking and Web pentestings tools are also available in Fsociety These are the following tools:
Drupal Hacking
Inurlbr
WordPress & Joomla Scanner
Gravity Form Scanner
File Upload Checker
WordPress Exploit Scanner
WordPress Plugins Scanner
Shell and Directory Finder
Joomla! 1.5 – 3.4.5 remote code execution
Vbulletin 5.X remote code execution
BruteX – Automatically brute force all services running on a target
Arachni – Web Application Security Scanner Framework
7. Private Web Hacking
It also includes some private Web hacking tools such as:
Get all websites
Get joomla websites
Get wordpress websites
Control Panel Finder
Zip Files Finder
Upload File Finder
Get server users
SQli Scanner
Ports Scan (range of ports)
Ports Scan (common ports)
Get server Info
Bypass Cloudflare
8. Post-Exploitation
After you are done with exploitation you have to perform some post-exploitation attacks to maintain persistent access to the system according to your need so for that also Fsociety provides some tools such as Shell Checker, POET, Weema.
9. Contributors – Contain a contributors list.
10. Install & Update is used to update the framework.
Step 1: Open your kali linux operating system and use the following command to install the tool from GitHub.
git clone https://github.com/Manisso/fsociety.git
Step 2: The tool has been downloaded and now move it to the directory using the following command.
cd fsociety
ls
Step 3: Now install the tool using the following command.
./install.sh
Step 4: All the dependencies have been downloaded and now run the tool using the following command.
./fsociety.py
Example 1: Use the Fsociety framework to perform reconnaissance in a domain.
1
After that, select nmap.
1
enter the IP address of the target.
Type 2 for port scan.
2
The framework has started nmap and this is how you can also perform on your target ip address.
Example 2: Use the Fsociety framework tool to find the IP address of a domain.
Select the host for IP tool in the framework, then enter the hostname. The tool will give you the IP address of the host.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux | [
{
"code": null,
"e": 25677,
"s": 25649,
"text": "\n18 Jul, 2021"
},
{
"code": null,
"e": 26478,
"s": 25677,
"text": "Fsociety is a free and open-source tool available on GitHub which is used as an information-gathering tool. Fsociety is used to scanning websites for information g... |
Linux - Renaming File While Downloading with Wget - GeeksforGeeks | 11 Feb, 2021
Wget utility is the most popular and powerful tool to download files on operating systems like Linux and Windows OS.Wget supports the HTTP, HTTPS, and FTP protocols, as well as retrieval through HTTP proxies.
Wget is non-interactive, which means it can work in the background while the user is not logged on. In case while downloading any file if the downloading disturbs then the wget save the half downloaded file and allow us to download the remaining part of the file to download. Wget also provides the feature of downloading websites to use offline.
By default, the wget downloads the file and saves it with the original name in the URL. Let’s see what options provide the wget. To see all options of wget use the following command
wget --help
Then wget shows the all options to how to use it.
Now let’s see how to download the file using wget.
To download the file using wget use the following command:
wget -c FILE_URL
Here we have used -c option because it allows users to complete the partially downloaded files. Here is example
In the above image, we can see that the file is downloaded with the name of the file in the URL. Now let’s see how to rename file while downloading
Wget provide the -O option to save the file with a different name instate of the name in the URL. Use the following command to save the downloaded file with a different name.
wget -cO - FILE_URL > NEW_FILE_NAME.extension
In the above command instead of FILE_URL use the URL of the file to be downloaded and in the place of NEW_FILE_NAME.extension use the new name to file with the extension. Here is example
The file is written to standard output and then redirected by the shell to the specified file as shown in the screenshot above.
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
Docker - COPY Instruction
mv command in Linux with examples
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux | [
{
"code": null,
"e": 25651,
"s": 25623,
"text": "\n11 Feb, 2021"
},
{
"code": null,
"e": 25860,
"s": 25651,
"text": "Wget utility is the most popular and powerful tool to download files on operating systems like Linux and Windows OS.Wget supports the HTTP, HTTPS, and FTP protocol... |
TRANSLATE() Function in SQL Server - GeeksforGeeks | 05 Jan, 2021
TRANSLATE() function :This function in SQL Server is used to return the translated string of the string stated in the first argument of this function, when the characters stated in the characters argument of the above function are converted into the characters stated in the last argument i.e, translations.
Features :
This function is used to find a modified string of the string stated in the first argument, when the characters given in the characters argument are converted into the characters given in the last argument i.e, translations.
This function accepts string, characters, and translations as parameter.
This function can translate the string fully as well as partially.
This function can return an error if specified characters and translations are not of same length.
Syntax :
TRANSLATE(string, characters, translations)
Parameter :This method accepts three parameters as given below :
string : Specified input string which is to be translated.
characters : Specified characters which must be substituted.
translations : Specified new characters.
Returns :It returns the modified string of the string stated in the first argument of this function, when the characters given in the characters argument are interpreted into the characters stated in the last argument i.e, translations.
Example-1 :Getting a string from the specified string, characters and translations.
SELECT TRANSLATE('Geek', 'Geek', 'geek');
Output :
geek
Example-2 :Using TRANSLATE() function with a variable and getting the translated string as output.
DECLARE @str VARCHAR(2);
SET @str = 'gf';
SELECT TRANSLATE(@str, 'gf', 'cs');
Output :
cs
Example-3 :Using TRANSLATE() function with three variables and getting the translated string as output.
DECLARE @str VARCHAR(3);
DECLARE @chars VARCHAR(3);
DECLARE @newchar VARCHAR(3);
SET @str = 'abc';
SET @chars = 'ab';
SET @newchar = 'ed';
SELECT TRANSLATE(@str, @chars, @newchar);
Output :
edc
Example-4 :Getting a translated string of the string stated in the first argument, when the characters given in the characters argument of this function are interpreted into the characters given in the last argument i.e, translations.
SELECT TRANSLATE('x*[y+z]/[x-y]', '[][]', '()()');
Output :
x*(y+z)/(x-y)
Application :This function is used to return the translated string of the string stated in the first argument, when the characters given in the characters argument are interpreted into the characters given in the last argument i.e, translations.
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Subquery
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL Query to Convert VARCHAR to INT
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates | [
{
"code": null,
"e": 25513,
"s": 25485,
"text": "\n05 Jan, 2021"
},
{
"code": null,
"e": 25821,
"s": 25513,
"text": "TRANSLATE() function :This function in SQL Server is used to return the translated string of the string stated in the first argument of this function, when the cha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.