title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Web Scraping CryptoCurrency price and storing it in MongoDB using Python
|
29 Dec, 2020
Let us see how to fetch history price in USD or BTC, traded volume and market cap for a given date range using Santiment API and storing the data into MongoDB collection.
Python is a mature language and getting much used in the Cryptocurrency domain. MongoDB is a NoSQL database getting paired with Python in many projects which helps to hold details that got retrieved from Python Programs. PyMongo is a Python distribution containing tools for working with MongoDB and it is a very convenient way to work with MongoDB from Python to do Create/Update/Delete/Read operations easily.
Let us see the code in using Santiment’s API in getting cryptocurrency prices for a given date range
Few Examples of cryptocurrency are :
bitcoin
ethereum
ripple
bitcoin-cash
litecoin
eos
cardano
stellar
neo
iota
In the place of id, we can pass bitcoin/ethereum or any cryptocurrency name which the below code can parse and get the dataFor valid cryptocurrency name, data will be retrieved properlyIn the place of from_date and to_date valid dates in valid date formats in yyyy-mm-dd pattern need to be given. For understanding purpose, it is given to take 7 days of data. We can able to get 1 month old data too. API call can able to get data for the given cryptocurrencies in the given date range or else if not available (due to invalid cryptocurrency name/invalid date range specification), we can catch the errorsIn the below program, for easier understanding, taking bitcoin and ethereum in “IndexCoins.idx” file and hence in the place of id, they are passed
In the place of id, we can pass bitcoin/ethereum or any cryptocurrency name which the below code can parse and get the data
For valid cryptocurrency name, data will be retrieved properly
In the place of from_date and to_date valid dates in valid date formats in yyyy-mm-dd pattern need to be given. For understanding purpose, it is given to take 7 days of data. We can able to get 1 month old data too. API call can able to get data for the given cryptocurrencies in the given date range or else if not available (due to invalid cryptocurrency name/invalid date range specification), we can catch the errors
In the below program, for easier understanding, taking bitcoin and ethereum in “IndexCoins.idx” file and hence in the place of id, they are passed
Example :
For the following input
For bitcoin above API call, returns data as below
Similarly for ethereum also, we will get value
Retrieved value has to be stored in MongoDB
Database : geeksforgeeks
Collection : Coll_santiment_Price
As we are going to take for 7 days of data, it has to be given in a loop
In MongoDB, _id is the default column which can be got by ObjectId(). Our process has multiple rows where each and every row is identified by means of “cryptocurrencyname” and “time”. In our code, we are having it as “id” and “time” respectively.
Let “Coll_santiment_Price” be created with 3 columns namely _id, id and time first. Then upon successful execution of API call, for the id and time, let API call output namely (verify column name from bitcoinprice.png) ‘priceBtc’, ‘priceUsd’,’volume’ and ‘marketcap’ are updated in a loop.
Code Implementation in Python
Python3
# importing the modulesfrom datetime import date, timedelta, datetimefrom pymongo import MongoClientimport sanfrom bson.objectid import ObjectId client = MongoClient('mongodb://localhost:27017/')db1 = client.geeksforgeeksdata = {} with open("IndexCoins.idx") as openfileobject: for line in openfileobject: # One by one File's cryptocurrency names are read id = line.strip() try: print(id) # Collecting the data for 7 days and hence range(7) is taken for idx in range(7): daystr = str(date.today() - timedelta(days = idx)) # Coll_santiment_Price collection documents need to be created # It will have columns namely "_id", "time", "id", # "priceBtc", "priceUsd", "volume", "marketcap" data['id'] = id data['time'] = daystr # _id column for unique key and can be generated by using ObjectId() data['_id'] = ObjectId() # Initially create 3 columns in collection as rest of the # columns are updated after running santiment api call db1.Coll_santiment_Price.insert(data) try: # Santiment API call to get Cryptocurrency prices daa = san.get("prices/" + id, from_date = "2020-08-20", to_date = "2020-08-27", interval = "1d") # API call output and for bitcoin it is given in # https://media.geeksforgeeks.org/wp-content/uploads/20200827191739/bitcoinprice.png print(daa) except: print("URL error") continue; # 7 days output for idx in range(7): daystr = str(date.today() - timedelta(days=idx)) # API call output for the above chosen date row = daa.loc[daystr] # priceBtc, priceUsd, volume and marketcap are # collected and stored in seperate variables priceBtc = row['priceBtc'] priceUsd = row['priceUsd'] volume = row['volume'] marketcap = row['marketcap'] print(id, daystr, priceBtc, priceUsd, volume, marketcap) try: # Update the collection with above details against # cryptocurrency id and time i.e. bitcoin and 2020-08-27 db1.Coll_santiment_Price.update( {'time': daystr, 'id': id}, {"$set": {"priceBtc": priceBtc, "priceUsd": priceUsd, "volume": volume, "marketcap": marketcap, } }, upsert = True ) except Exception as e: print(e) except: print("Error")
Sample Output : (For bitcoin)
Sample Output : (For Ethereum)
Santiment API calls for getting prices are very much used across cryptocurrency projects. As we are getting historical data, for data analytics, this is very much useful. Moreover, it is freely accessible and hence any beginner-level projects can use it without any issues. Price variations are not much varying and hence well set for demo and small scale projects.
Python web-scraping-exercises
Python-mongoDB
python-utility
Web-scraping
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 199,
"s": 28,
"text": "Let us see how to fetch history price in USD or BTC, traded volume and market cap for a given date range using Santiment API and storing the data into MongoDB collection."
},
{
"code": null,
"e": 612,
"s": 199,
"text": "Python is a mature language and getting much used in the Cryptocurrency domain. MongoDB is a NoSQL database getting paired with Python in many projects which helps to hold details that got retrieved from Python Programs. PyMongo is a Python distribution containing tools for working with MongoDB and it is a very convenient way to work with MongoDB from Python to do Create/Update/Delete/Read operations easily."
},
{
"code": null,
"e": 713,
"s": 612,
"text": "Let us see the code in using Santiment’s API in getting cryptocurrency prices for a given date range"
},
{
"code": null,
"e": 750,
"s": 713,
"text": "Few Examples of cryptocurrency are :"
},
{
"code": null,
"e": 825,
"s": 750,
"text": "bitcoin\nethereum\nripple\nbitcoin-cash\nlitecoin\neos\ncardano\nstellar\nneo\niota"
},
{
"code": null,
"e": 1577,
"s": 825,
"text": "In the place of id, we can pass bitcoin/ethereum or any cryptocurrency name which the below code can parse and get the dataFor valid cryptocurrency name, data will be retrieved properlyIn the place of from_date and to_date valid dates in valid date formats in yyyy-mm-dd pattern need to be given. For understanding purpose, it is given to take 7 days of data. We can able to get 1 month old data too. API call can able to get data for the given cryptocurrencies in the given date range or else if not available (due to invalid cryptocurrency name/invalid date range specification), we can catch the errorsIn the below program, for easier understanding, taking bitcoin and ethereum in “IndexCoins.idx” file and hence in the place of id, they are passed"
},
{
"code": null,
"e": 1701,
"s": 1577,
"text": "In the place of id, we can pass bitcoin/ethereum or any cryptocurrency name which the below code can parse and get the data"
},
{
"code": null,
"e": 1764,
"s": 1701,
"text": "For valid cryptocurrency name, data will be retrieved properly"
},
{
"code": null,
"e": 2185,
"s": 1764,
"text": "In the place of from_date and to_date valid dates in valid date formats in yyyy-mm-dd pattern need to be given. For understanding purpose, it is given to take 7 days of data. We can able to get 1 month old data too. API call can able to get data for the given cryptocurrencies in the given date range or else if not available (due to invalid cryptocurrency name/invalid date range specification), we can catch the errors"
},
{
"code": null,
"e": 2332,
"s": 2185,
"text": "In the below program, for easier understanding, taking bitcoin and ethereum in “IndexCoins.idx” file and hence in the place of id, they are passed"
},
{
"code": null,
"e": 2342,
"s": 2332,
"text": "Example :"
},
{
"code": null,
"e": 2366,
"s": 2342,
"text": "For the following input"
},
{
"code": null,
"e": 2416,
"s": 2366,
"text": "For bitcoin above API call, returns data as below"
},
{
"code": null,
"e": 2463,
"s": 2416,
"text": "Similarly for ethereum also, we will get value"
},
{
"code": null,
"e": 2507,
"s": 2463,
"text": "Retrieved value has to be stored in MongoDB"
},
{
"code": null,
"e": 2532,
"s": 2507,
"text": "Database : geeksforgeeks"
},
{
"code": null,
"e": 2566,
"s": 2532,
"text": "Collection : Coll_santiment_Price"
},
{
"code": null,
"e": 2639,
"s": 2566,
"text": "As we are going to take for 7 days of data, it has to be given in a loop"
},
{
"code": null,
"e": 2886,
"s": 2639,
"text": "In MongoDB, _id is the default column which can be got by ObjectId(). Our process has multiple rows where each and every row is identified by means of “cryptocurrencyname” and “time”. In our code, we are having it as “id” and “time” respectively."
},
{
"code": null,
"e": 3176,
"s": 2886,
"text": "Let “Coll_santiment_Price” be created with 3 columns namely _id, id and time first. Then upon successful execution of API call, for the id and time, let API call output namely (verify column name from bitcoinprice.png) ‘priceBtc’, ‘priceUsd’,’volume’ and ‘marketcap’ are updated in a loop."
},
{
"code": null,
"e": 3206,
"s": 3176,
"text": "Code Implementation in Python"
},
{
"code": null,
"e": 3214,
"s": 3206,
"text": "Python3"
},
{
"code": "# importing the modulesfrom datetime import date, timedelta, datetimefrom pymongo import MongoClientimport sanfrom bson.objectid import ObjectId client = MongoClient('mongodb://localhost:27017/')db1 = client.geeksforgeeksdata = {} with open(\"IndexCoins.idx\") as openfileobject: for line in openfileobject: # One by one File's cryptocurrency names are read id = line.strip() try: print(id) # Collecting the data for 7 days and hence range(7) is taken for idx in range(7): daystr = str(date.today() - timedelta(days = idx)) # Coll_santiment_Price collection documents need to be created # It will have columns namely \"_id\", \"time\", \"id\", # \"priceBtc\", \"priceUsd\", \"volume\", \"marketcap\" data['id'] = id data['time'] = daystr # _id column for unique key and can be generated by using ObjectId() data['_id'] = ObjectId() # Initially create 3 columns in collection as rest of the # columns are updated after running santiment api call db1.Coll_santiment_Price.insert(data) try: # Santiment API call to get Cryptocurrency prices daa = san.get(\"prices/\" + id, from_date = \"2020-08-20\", to_date = \"2020-08-27\", interval = \"1d\") # API call output and for bitcoin it is given in # https://media.geeksforgeeks.org/wp-content/uploads/20200827191739/bitcoinprice.png print(daa) except: print(\"URL error\") continue; # 7 days output for idx in range(7): daystr = str(date.today() - timedelta(days=idx)) # API call output for the above chosen date row = daa.loc[daystr] # priceBtc, priceUsd, volume and marketcap are # collected and stored in seperate variables priceBtc = row['priceBtc'] priceUsd = row['priceUsd'] volume = row['volume'] marketcap = row['marketcap'] print(id, daystr, priceBtc, priceUsd, volume, marketcap) try: # Update the collection with above details against # cryptocurrency id and time i.e. bitcoin and 2020-08-27 db1.Coll_santiment_Price.update( {'time': daystr, 'id': id}, {\"$set\": {\"priceBtc\": priceBtc, \"priceUsd\": priceUsd, \"volume\": volume, \"marketcap\": marketcap, } }, upsert = True ) except Exception as e: print(e) except: print(\"Error\")",
"e": 6405,
"s": 3214,
"text": null
},
{
"code": null,
"e": 6435,
"s": 6405,
"text": "Sample Output : (For bitcoin)"
},
{
"code": null,
"e": 6466,
"s": 6435,
"text": "Sample Output : (For Ethereum)"
},
{
"code": null,
"e": 6832,
"s": 6466,
"text": "Santiment API calls for getting prices are very much used across cryptocurrency projects. As we are getting historical data, for data analytics, this is very much useful. Moreover, it is freely accessible and hence any beginner-level projects can use it without any issues. Price variations are not much varying and hence well set for demo and small scale projects."
},
{
"code": null,
"e": 6862,
"s": 6832,
"text": "Python web-scraping-exercises"
},
{
"code": null,
"e": 6877,
"s": 6862,
"text": "Python-mongoDB"
},
{
"code": null,
"e": 6892,
"s": 6877,
"text": "python-utility"
},
{
"code": null,
"e": 6905,
"s": 6892,
"text": "Web-scraping"
},
{
"code": null,
"e": 6912,
"s": 6905,
"text": "Python"
}
] |
GATE | GATE CS 2013 | Question 65
|
13 Sep, 2021
Determine the maximum length of the cable (in km) for transmitting data at a rate of 500 Mbps in an Ethernet LAN with frames of size 10,000 bits. Assume the signal speed in the cable to be 2,00,000 km/s.(A) 1(B) 2(C) 2.5(D) 5Answer: (B)Explanation:
Data should be transmitted at the rate of 500 Mbps.
Transmission Time >= 2*Propagation Time
=> 10000/(500*1000000) <= 2*length/200000
=> length = 2km (max)
so, answer will be: (B) 2km
Quiz of this Question
anikakapoor
GATE-CS-2013
GATE-GATE CS 2013
Computer Networks Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Sep, 2021"
},
{
"code": null,
"e": 303,
"s": 54,
"text": "Determine the maximum length of the cable (in km) for transmitting data at a rate of 500 Mbps in an Ethernet LAN with frames of size 10,000 bits. Assume the signal speed in the cable to be 2,00,000 km/s.(A) 1(B) 2(C) 2.5(D) 5Answer: (B)Explanation:"
},
{
"code": null,
"e": 488,
"s": 303,
"text": "Data should be transmitted at the rate of 500 Mbps.\nTransmission Time >= 2*Propagation Time\n=> 10000/(500*1000000) <= 2*length/200000\n=> length = 2km (max)\nso, answer will be: (B) 2km "
},
{
"code": null,
"e": 510,
"s": 488,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 522,
"s": 510,
"text": "anikakapoor"
},
{
"code": null,
"e": 535,
"s": 522,
"text": "GATE-CS-2013"
},
{
"code": null,
"e": 553,
"s": 535,
"text": "GATE-GATE CS 2013"
},
{
"code": null,
"e": 576,
"s": 553,
"text": "Computer Networks Quiz"
}
] |
Huffman Coding | Greedy Algo-3
|
19 Apr, 2022
Huffman coding is a lossless data compression algorithm. The idea is to assign variable-length codes to input characters, lengths of the assigned codes are based on the frequencies of corresponding characters. The most frequent character gets the smallest code and the least frequent character gets the largest code.The variable-length codes assigned to input characters are Prefix Codes, means the codes (bit sequences) are assigned in such a way that the code assigned to one character is not the prefix of code assigned to any other character. This is how Huffman Coding makes sure that there is no ambiguity when decoding the generated bitstream. Let us understand prefix codes with a counter example. Let there be four characters a, b, c and d, and their corresponding variable length codes be 00, 01, 0 and 1. This coding leads to ambiguity because code assigned to c is the prefix of codes assigned to a and b. If the compressed bit stream is 0001, the de-compressed output may be “cccd” or “ccb” or “acd” or “ab”.See this for applications of Huffman Coding. There are mainly two major parts in Huffman Coding
Build a Huffman Tree from input characters.Traverse the Huffman Tree and assign codes to characters.
Build a Huffman Tree from input characters.
Traverse the Huffman Tree and assign codes to characters.
Steps to build Huffman TreeInput is an array of unique characters along with their frequency of occurrences and output is Huffman Tree.
Create a leaf node for each unique character and build a min heap of all leaf nodes (Min Heap is used as a priority queue. The value of frequency field is used to compare two nodes in min heap. Initially, the least frequent character is at root)Extract two nodes with the minimum frequency from the min heap. Create a new internal node with a frequency equal to the sum of the two nodes frequencies. Make the first extracted node as its left child and the other extracted node as its right child. Add this node to the min heap.Repeat steps#2 and #3 until the heap contains only one node. The remaining node is the root node and the tree is complete.Let us understand the algorithm with an example:
Create a leaf node for each unique character and build a min heap of all leaf nodes (Min Heap is used as a priority queue. The value of frequency field is used to compare two nodes in min heap. Initially, the least frequent character is at root)
Extract two nodes with the minimum frequency from the min heap.
Create a new internal node with a frequency equal to the sum of the two nodes frequencies. Make the first extracted node as its left child and the other extracted node as its right child. Add this node to the min heap.
Repeat steps#2 and #3 until the heap contains only one node. The remaining node is the root node and the tree is complete.Let us understand the algorithm with an example:
character Frequency
a 5
b 9
c 12
d 13
e 16
f 45
Step 1. Build a min heap that contains 6 nodes where each node represents root of a tree with single node.Step 2 Extract two minimum frequency nodes from min heap. Add a new internal node with frequency 5 + 9 = 14.
Now min heap contains 5 nodes where 4 nodes are roots of trees with single element each, and one heap node is root of tree with 3 elements
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.
character Frequency
c 12
d 13
Internal Node 14
e 16
f 45
Step 3: Extract two minimum frequency nodes from heap. Add a new internal node with frequency 12 + 13 = 25
Now min heap contains 4 nodes where 2 nodes are roots of trees with single element each, and two heap nodes are root of tree with more than one nodes
character Frequency
Internal Node 14
e 16
Internal Node 25
f 45
Step 4: Extract two minimum frequency nodes. Add a new internal node with frequency 14 + 16 = 30
Now min heap contains 3 nodes.
character Frequency
Internal Node 25
Internal Node 30
f 45
Step 5: Extract two minimum frequency nodes. Add a new internal node with frequency 25 + 30 = 55
Now min heap contains 2 nodes.
character Frequency
f 45
Internal Node 55
Step 6: Extract two minimum frequency nodes. Add a new internal node with frequency 45 + 55 = 100
Now min heap contains only one node.
character Frequency
Internal Node 100
Since the heap contains only one node, the algorithm stops here.
Steps to print codes from Huffman Tree:Traverse the tree formed starting from the root. Maintain an auxiliary array. While moving to the left child, write 0 to the array. While moving to the right child, write 1 to the array. Print the array when a leaf node is encountered.
The codes are as follows:
character code-word
f 0
c 100
d 101
a 1100
b 1101
e 111
Below is the implementation of above approach:
C
C++
C++
Java
Python3
Javascript
// C program for Huffman Coding#include <stdio.h>#include <stdlib.h> // This constant can be avoided by explicitly// calculating height of Huffman Tree#define MAX_TREE_HT 100 // A Huffman tree nodestruct MinHeapNode { // One of the input characters char data; // Frequency of the character unsigned freq; // Left and right child of this node struct MinHeapNode *left, *right;}; // A Min Heap: Collection of// min-heap (or Huffman tree) nodesstruct MinHeap { // Current size of min heap unsigned size; // capacity of min heap unsigned capacity; // Array of minheap node pointers struct MinHeapNode** array;}; // A utility function allocate a new// min heap node with given character// and frequency of the characterstruct MinHeapNode* newNode(char data, unsigned freq){ struct MinHeapNode* temp = (struct MinHeapNode*)malloc( sizeof(struct MinHeapNode)); temp->left = temp->right = NULL; temp->data = data; temp->freq = freq; return temp;} // A utility function to create// a min heap of given capacitystruct MinHeap* createMinHeap(unsigned capacity) { struct MinHeap* minHeap = (struct MinHeap*)malloc(sizeof(struct MinHeap)); // current size is 0 minHeap->size = 0; minHeap->capacity = capacity; minHeap->array = (struct MinHeapNode**)malloc( minHeap->capacity * sizeof(struct MinHeapNode*)); return minHeap;} // A utility function to// swap two min heap nodesvoid swapMinHeapNode(struct MinHeapNode** a, struct MinHeapNode** b) { struct MinHeapNode* t = *a; *a = *b; *b = t;} // The standard minHeapify function.void minHeapify(struct MinHeap* minHeap, int idx) { int smallest = idx; int left = 2 * idx + 1; int right = 2 * idx + 2; if (left < minHeap->size && minHeap->array[left]->freq < minHeap->array[smallest]->freq) smallest = left; if (right < minHeap->size && minHeap->array[right]->freq < minHeap->array[smallest]->freq) smallest = right; if (smallest != idx) { swapMinHeapNode(&minHeap->array[smallest], &minHeap->array[idx]); minHeapify(minHeap, smallest); }} // A utility function to check// if size of heap is 1 or notint isSizeOne(struct MinHeap* minHeap){ return (minHeap->size == 1);} // A standard function to extract// minimum value node from heapstruct MinHeapNode* extractMin(struct MinHeap* minHeap) { struct MinHeapNode* temp = minHeap->array[0]; minHeap->array[0] = minHeap->array[minHeap->size - 1]; --minHeap->size; minHeapify(minHeap, 0); return temp;} // A utility function to insert// a new node to Min Heapvoid insertMinHeap(struct MinHeap* minHeap, struct MinHeapNode* minHeapNode) { ++minHeap->size; int i = minHeap->size - 1; while (i && minHeapNode->freq < minHeap->array[(i - 1) / 2]->freq) { minHeap->array[i] = minHeap->array[(i - 1) / 2]; i = (i - 1) / 2; } minHeap->array[i] = minHeapNode;} // A standard function to build min heapvoid buildMinHeap(struct MinHeap* minHeap) { int n = minHeap->size - 1; int i; for (i = (n - 1) / 2; i >= 0; --i) minHeapify(minHeap, i);} // A utility function to print an array of size nvoid printArr(int arr[], int n){ int i; for (i = 0; i < n; ++i) printf("%d", arr[i]); printf("\n");} // Utility function to check if this node is leafint isLeaf(struct MinHeapNode* root) { return !(root->left) && !(root->right);} // Creates a min heap of capacity// equal to size and inserts all character of// data[] in min heap. Initially size of// min heap is equal to capacitystruct MinHeap* createAndBuildMinHeap(char data[], int freq[], int size) { struct MinHeap* minHeap = createMinHeap(size); for (int i = 0; i < size; ++i) minHeap->array[i] = newNode(data[i], freq[i]); minHeap->size = size; buildMinHeap(minHeap); return minHeap;} // The main function that builds Huffman treestruct MinHeapNode* buildHuffmanTree(char data[], int freq[], int size) { struct MinHeapNode *left, *right, *top; // Step 1: Create a min heap of capacity // equal to size. Initially, there are // modes equal to size. struct MinHeap* minHeap = createAndBuildMinHeap(data, freq, size); // Iterate while size of heap doesn't become 1 while (!isSizeOne(minHeap)) { // Step 2: Extract the two minimum // freq items from min heap left = extractMin(minHeap); right = extractMin(minHeap); // Step 3: Create a new internal // node with frequency equal to the // sum of the two nodes frequencies. // Make the two extracted node as // left and right children of this new node. // Add this node to the min heap // '$' is a special value for internal nodes, not // used top = newNode('$', left->freq + right->freq); top->left = left; top->right = right; insertMinHeap(minHeap, top); } // Step 4: The remaining node is the // root node and the tree is complete. return extractMin(minHeap);} // Prints huffman codes from the root of Huffman Tree.// It uses arr[] to store codesvoid printCodes(struct MinHeapNode* root, int arr[], int top) { // Assign 0 to left edge and recur if (root->left) { arr[top] = 0; printCodes(root->left, arr, top + 1); } // Assign 1 to right edge and recur if (root->right) { arr[top] = 1; printCodes(root->right, arr, top + 1); } // If this is a leaf node, then // it contains one of the input // characters, print the character // and its code from arr[] if (isLeaf(root)) { printf("%c: ", root->data); printArr(arr, top); }} // The main function that builds a// Huffman Tree and print codes by traversing// the built Huffman Treevoid HuffmanCodes(char data[], int freq[], int size) { // Construct Huffman Tree struct MinHeapNode* root = buildHuffmanTree(data, freq, size); // Print Huffman codes using // the Huffman tree built above int arr[MAX_TREE_HT], top = 0; printCodes(root, arr, top);} // Driver codeint main(){ char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; int freq[] = { 5, 9, 12, 13, 16, 45 }; int size = sizeof(arr) / sizeof(arr[0]); HuffmanCodes(arr, freq, size); return 0;}
// C++ program for Huffman Coding#include <iostream>#include <cstdlib>using namespace std; // This constant can be avoided by explicitly// calculating height of Huffman Tree#define MAX_TREE_HT 100 // A Huffman tree nodestruct MinHeapNode { // One of the input characters char data; // Frequency of the character unsigned freq; // Left and right child of this node struct MinHeapNode *left, *right;}; // A Min Heap: Collection of// min-heap (or Huffman tree) nodesstruct MinHeap { // Current size of min heap unsigned size; // capacity of min heap unsigned capacity; // Array of minheap node pointers struct MinHeapNode** array;}; // A utility function allocate a new// min heap node with given character// and frequency of the characterstruct MinHeapNode* newNode(char data, unsigned freq){ struct MinHeapNode* temp = (struct MinHeapNode*)malloc(sizeof(struct MinHeapNode)); temp->left = temp->right = NULL; temp->data = data; temp->freq = freq; return temp;} // A utility function to create// a min heap of given capacitystruct MinHeap* createMinHeap(unsigned capacity) { struct MinHeap* minHeap = (struct MinHeap*)malloc(sizeof(struct MinHeap)); // current size is 0 minHeap->size = 0; minHeap->capacity = capacity; minHeap->array = (struct MinHeapNode**)malloc(minHeap->capacity * sizeof(struct MinHeapNode*)); return minHeap;} // A utility function to// swap two min heap nodesvoid swapMinHeapNode(struct MinHeapNode** a, struct MinHeapNode** b) { struct MinHeapNode* t = *a; *a = *b; *b = t;} // The standard minHeapify function.void minHeapify(struct MinHeap* minHeap, int idx) { int smallest = idx; int left = 2 * idx + 1; int right = 2 * idx + 2; if (left < minHeap->size && minHeap->array[left]->freq < minHeap->array[smallest]->freq) smallest = left; if (right < minHeap->size && minHeap->array[right]->freq < minHeap->array[smallest]->freq) smallest = right; if (smallest != idx) { swapMinHeapNode(&minHeap->array[smallest], &minHeap->array[idx]); minHeapify(minHeap, smallest); }} // A utility function to check// if size of heap is 1 or notint isSizeOne(struct MinHeap* minHeap){ return (minHeap->size == 1);} // A standard function to extract// minimum value node from heapstruct MinHeapNode* extractMin(struct MinHeap* minHeap) { struct MinHeapNode* temp = minHeap->array[0]; minHeap->array[0] = minHeap->array[minHeap->size - 1]; --minHeap->size; minHeapify(minHeap, 0); return temp;} // A utility function to insert// a new node to Min Heapvoid insertMinHeap(struct MinHeap* minHeap, struct MinHeapNode* minHeapNode) { ++minHeap->size; int i = minHeap->size - 1; while (i && minHeapNode->freq < minHeap->array[(i - 1) / 2]->freq) { minHeap->array[i] = minHeap->array[(i - 1) / 2]; i = (i - 1) / 2; } minHeap->array[i] = minHeapNode;} // A standard function to build min heapvoid buildMinHeap(struct MinHeap* minHeap) { int n = minHeap->size - 1; int i; for (i = (n - 1) / 2; i >= 0; --i) minHeapify(minHeap, i);} // A utility function to print an array of size nvoid printArr(int arr[], int n){ int i; for (i = 0; i < n; ++i) cout<< arr[i]; cout<<"\n";} // Utility function to check if this node is leafint isLeaf(struct MinHeapNode* root) { return !(root->left) && !(root->right);} // Creates a min heap of capacity// equal to size and inserts all character of// data[] in min heap. Initially size of// min heap is equal to capacitystruct MinHeap* createAndBuildMinHeap(char data[], int freq[], int size) { struct MinHeap* minHeap = createMinHeap(size); for (int i = 0; i < size; ++i) minHeap->array[i] = newNode(data[i], freq[i]); minHeap->size = size; buildMinHeap(minHeap); return minHeap;} // The main function that builds Huffman treestruct MinHeapNode* buildHuffmanTree(char data[], int freq[], int size) { struct MinHeapNode *left, *right, *top; // Step 1: Create a min heap of capacity // equal to size. Initially, there are // modes equal to size. struct MinHeap* minHeap = createAndBuildMinHeap(data, freq, size); // Iterate while size of heap doesn't become 1 while (!isSizeOne(minHeap)) { // Step 2: Extract the two minimum // freq items from min heap left = extractMin(minHeap); right = extractMin(minHeap); // Step 3: Create a new internal // node with frequency equal to the // sum of the two nodes frequencies. // Make the two extracted node as // left and right children of this new node. // Add this node to the min heap // '$' is a special value for internal nodes, not used top = newNode('$', left->freq + right->freq); top->left = left; top->right = right; insertMinHeap(minHeap, top); } // Step 4: The remaining node is the // root node and the tree is complete. return extractMin(minHeap);} // Prints huffman codes from the root of Huffman Tree.// It uses arr[] to store codesvoid printCodes(struct MinHeapNode* root, int arr[], int top) { // Assign 0 to left edge and recur if (root->left) { arr[top] = 0; printCodes(root->left, arr, top + 1); } // Assign 1 to right edge and recur if (root->right) { arr[top] = 1; printCodes(root->right, arr, top + 1); } // If this is a leaf node, then // it contains one of the input // characters, print the character // and its code from arr[] if (isLeaf(root)) { cout<< root->data <<": "; printArr(arr, top); }} // The main function that builds a// Huffman Tree and print codes by traversing// the built Huffman Treevoid HuffmanCodes(char data[], int freq[], int size) { // Construct Huffman Tree struct MinHeapNode* root = buildHuffmanTree(data, freq, size); // Print Huffman codes using // the Huffman tree built above int arr[MAX_TREE_HT], top = 0; printCodes(root, arr, top);} // Driver codeint main(){ char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; int freq[] = { 5, 9, 12, 13, 16, 45 }; int size = sizeof(arr) / sizeof(arr[0]); HuffmanCodes(arr, freq, size); return 0;}
// C++(STL) program for Huffman Coding with STL#include <bits/stdc++.h>using namespace std; // A Huffman tree nodestruct MinHeapNode { // One of the input characters char data; // Frequency of the character unsigned freq; // Left and right child MinHeapNode *left, *right; MinHeapNode(char data, unsigned freq) { left = right = NULL; this->data = data; this->freq = freq; }}; // For comparison of// two heap nodes (needed in min heap)struct compare { bool operator()(MinHeapNode* l, MinHeapNode* r) { return (l->freq > r->freq); }}; // Prints huffman codes from// the root of Huffman Tree.void printCodes(struct MinHeapNode* root, string str){ if (!root) return; if (root->data != '$') cout << root->data << ": " << str << "\n"; printCodes(root->left, str + "0"); printCodes(root->right, str + "1");} // The main function that builds a Huffman Tree and// print codes by traversing the built Huffman Treevoid HuffmanCodes(char data[], int freq[], int size){ struct MinHeapNode *left, *right, *top; // Create a min heap & inserts all characters of data[] priority_queue<MinHeapNode*, vector<MinHeapNode*>, compare> minHeap; for (int i = 0; i < size; ++i) minHeap.push(new MinHeapNode(data[i], freq[i])); // Iterate while size of heap doesn't become 1 while (minHeap.size() != 1) { // Extract the two minimum // freq items from min heap left = minHeap.top(); minHeap.pop(); right = minHeap.top(); minHeap.pop(); // Create a new internal node with // frequency equal to the sum of the // two nodes frequencies. Make the // two extracted node as left and right children // of this new node. Add this node // to the min heap '$' is a special value // for internal nodes, not used top = new MinHeapNode('$', left->freq + right->freq); top->left = left; top->right = right; minHeap.push(top); } // Print Huffman codes using // the Huffman tree built above printCodes(minHeap.top(), "");} // Driver Codeint main(){ char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; int freq[] = { 5, 9, 12, 13, 16, 45 }; int size = sizeof(arr) / sizeof(arr[0]); HuffmanCodes(arr, freq, size); return 0;} // This code is contributed by Aditya Goel
import java.util.PriorityQueue;import java.util.Scanner;import java.util.Comparator; // node class is the basic structure// of each node present in the Huffman - tree.class HuffmanNode { int data; char c; HuffmanNode left; HuffmanNode right;} // comparator class helps to compare the node// on the basis of one of its attribute.// Here we will be compared// on the basis of data values of the nodes.class MyComparator implements Comparator<HuffmanNode> { public int compare(HuffmanNode x, HuffmanNode y) { return x.data - y.data; }} public class Huffman { // recursive function to print the // huffman-code through the tree traversal. // Here s is the huffman - code generated. public static void printCode(HuffmanNode root, String s) { // base case; if the left and right are null // then its a leaf node and we print // the code s generated by traversing the tree. if (root.left == null && root.right == null && Character.isLetter(root.c)) { // c is the character in the node System.out.println(root.c + ":" + s); return; } // if we go to left then add "0" to the code. // if we go to the right add"1" to the code. // recursive calls for left and // right sub-tree of the generated tree. printCode(root.left, s + "0"); printCode(root.right, s + "1"); } // main function public static void main(String[] args) { Scanner s = new Scanner(System.in); // number of characters. int n = 6; char[] charArray = { 'a', 'b', 'c', 'd', 'e', 'f' }; int[] charfreq = { 5, 9, 12, 13, 16, 45 }; // creating a priority queue q. // makes a min-priority queue(min-heap). PriorityQueue<HuffmanNode> q = new PriorityQueue<HuffmanNode>(n, new MyComparator()); for (int i = 0; i < n; i++) { // creating a Huffman node object // and add it to the priority queue. HuffmanNode hn = new HuffmanNode(); hn.c = charArray[i]; hn.data = charfreq[i]; hn.left = null; hn.right = null; // add functions adds // the huffman node to the queue. q.add(hn); } // create a root node HuffmanNode root = null; // Here we will extract the two minimum value // from the heap each time until // its size reduces to 1, extract until // all the nodes are extracted. while (q.size() > 1) { // first min extract. HuffmanNode x = q.peek(); q.poll(); // second min extract. HuffmanNode y = q.peek(); q.poll(); // new node f which is equal HuffmanNode f = new HuffmanNode(); // to the sum of the frequency of the two nodes // assigning values to the f node. f.data = x.data + y.data; f.c = '-'; // first extracted node as left child. f.left = x; // second extracted node as the right child. f.right = y; // marking the f node as the root node. root = f; // add this node to the priority-queue. q.add(f); } // print the codes by traversing the tree printCode(root, ""); }} // This code is contributed by Kunwar Desh Deepak Singh
# A Huffman Tree Nodeclass node: def __init__(self, freq, symbol, left=None, right=None): # frequency of symbol self.freq = freq # symbol name (character) self.symbol = symbol # node left of current node self.left = left # node right of current node self.right = right # tree direction (0/1) self.huff = '' # utility function to print huffman# codes for all symbols in the newly# created Huffman tree def printNodes(node, val=''): # huffman code for current node newVal = val + str(node.huff) # if node is not an edge node # then traverse inside it if(node.left): printNodes(node.left, newVal) if(node.right): printNodes(node.right, newVal) # if node is edge node then # display its huffman code if(not node.left and not node.right): print(f"{node.symbol} -> {newVal}") # characters for huffman treechars = ['a', 'b', 'c', 'd', 'e', 'f'] # frequency of charactersfreq = [ 5, 9, 12, 13, 16, 45] # list containing unused nodesnodes = [] # converting characters and frequencies# into huffman tree nodesfor x in range(len(chars)): nodes.append(node(freq[x], chars[x])) while len(nodes) > 1: # sort all the nodes in ascending order # based on theri frequency nodes = sorted(nodes, key=lambda x: x.freq) # pick 2 smallest nodes left = nodes[0] right = nodes[1] # assign directional value to these nodes left.huff = 0 right.huff = 1 # combine the 2 smallest nodes to create # new node as their parent newNode = node(left.freq+right.freq, left.symbol+right.symbol, left, right) # remove the 2 nodes and add their # parent as new node among others nodes.remove(left) nodes.remove(right) nodes.append(newNode) # Huffman Tree is ready!printNodes(nodes[0])
<script> // node class is the basic structure// of each node present in the Huffman - tree.class HuffmanNode{ constructor() { this.data = 0; this.c = ''; this.left = this.right = null; }} // recursive function to print the // huffman-code through the tree traversal. // Here s is the huffman - code generated. function printCode(root,s) { // base case; if the left and right are null // then its a leaf node and we print // the code s generated by traversing the tree. if (root.left == null && root.right == null && (root.c).toLowerCase() != (root.c).toUpperCase()) { // c is the character in the node document.write(root.c + ":" + s+"<br>"); return; } // if we go to left then add "0" to the code. // if we go to the right add"1" to the code. // recursive calls for left and // right sub-tree of the generated tree. printCode(root.left, s + "0"); printCode(root.right, s + "1"); } // main function // number of characters. let n = 6; let charArray = [ 'a', 'b', 'c', 'd', 'e', 'f' ]; let charfreq = [ 5, 9, 12, 13, 16, 45 ]; // creating a priority queue q. // makes a min-priority queue(min-heap). let q = []; for (let i = 0; i < n; i++) { // creating a Huffman node object // and add it to the priority queue. let hn = new HuffmanNode(); hn.c = charArray[i]; hn.data = charfreq[i]; hn.left = null; hn.right = null; // add functions adds // the huffman node to the queue. q.push(hn); } // create a root node let root = null; q.sort(function(a,b){return a.data-b.data;}); // Here we will extract the two minimum value // from the heap each time until // its size reduces to 1, extract until // all the nodes are extracted. while (q.length > 1) { // first min extract. let x = q[0]; q.shift(); // second min extract. let y = q[0]; q.shift(); // new node f which is equal let f = new HuffmanNode(); // to the sum of the frequency of the two nodes // assigning values to the f node. f.data = x.data + y.data; f.c = '-'; // first extracted node as left child. f.left = x; // second extracted node as the right child. f.right = y; // marking the f node as the root node. root = f; // add this node to the priority-queue. q.push(f); q.sort(function(a,b){return a.data-b.data;}); } // print the codes by traversing the tree printCode(root, ""); // This code is contributed by avanitrachhadiya2155</script>
Output:
f: 0
c: 100
d: 101
a: 1100
b: 1101
e: 111
Time complexity: O(nlogn) where n is the number of unique characters. If there are n nodes, extractMin() is called 2*(n – 1) times. extractMin() takes O(logn) time as it calles minHeapify(). So, overall complexity is O(nlogn).If the input array is sorted, there exists a linear time algorithm. We will soon be discussing in our next post.
They are used for transmitting fax and text.They are used by conventional compression formats like PKZIP, GZIP, etc.Multimedia codecs like JPEG, PNG, and MP3 use Huffman encoding(to be more precise the prefix codes).
They are used for transmitting fax and text.
They are used by conventional compression formats like PKZIP, GZIP, etc.
Multimedia codecs like JPEG, PNG, and MP3 use Huffman encoding(to be more precise the prefix codes).
It is useful in cases where there is a series of frequently occurring characters.
Reference:http://en.wikipedia.org/wiki/Huffman_codingThis article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
kddeepak
SoumikMondal
AyushShaZz
deekshant149
tripathipriyanshu1998
tacklestar
avanitrachhadiya2155
arorakashish0911
simmytarika5
krisania804
Amazon
encoding-decoding
Huffman Coding
Morgan Stanley
priority-queue
Samsung
United Health Group
Greedy
Heap
Morgan Stanley
Amazon
Samsung
United Health Group
Greedy
Heap
priority-queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Apr, 2022"
},
{
"code": null,
"e": 1169,
"s": 52,
"text": "Huffman coding is a lossless data compression algorithm. The idea is to assign variable-length codes to input characters, lengths of the assigned codes are based on the frequencies of corresponding characters. The most frequent character gets the smallest code and the least frequent character gets the largest code.The variable-length codes assigned to input characters are Prefix Codes, means the codes (bit sequences) are assigned in such a way that the code assigned to one character is not the prefix of code assigned to any other character. This is how Huffman Coding makes sure that there is no ambiguity when decoding the generated bitstream. Let us understand prefix codes with a counter example. Let there be four characters a, b, c and d, and their corresponding variable length codes be 00, 01, 0 and 1. This coding leads to ambiguity because code assigned to c is the prefix of codes assigned to a and b. If the compressed bit stream is 0001, the de-compressed output may be “cccd” or “ccb” or “acd” or “ab”.See this for applications of Huffman Coding. There are mainly two major parts in Huffman Coding"
},
{
"code": null,
"e": 1270,
"s": 1169,
"text": "Build a Huffman Tree from input characters.Traverse the Huffman Tree and assign codes to characters."
},
{
"code": null,
"e": 1314,
"s": 1270,
"text": "Build a Huffman Tree from input characters."
},
{
"code": null,
"e": 1372,
"s": 1314,
"text": "Traverse the Huffman Tree and assign codes to characters."
},
{
"code": null,
"e": 1509,
"s": 1372,
"text": "Steps to build Huffman TreeInput is an array of unique characters along with their frequency of occurrences and output is Huffman Tree. "
},
{
"code": null,
"e": 2207,
"s": 1509,
"text": "Create a leaf node for each unique character and build a min heap of all leaf nodes (Min Heap is used as a priority queue. The value of frequency field is used to compare two nodes in min heap. Initially, the least frequent character is at root)Extract two nodes with the minimum frequency from the min heap. Create a new internal node with a frequency equal to the sum of the two nodes frequencies. Make the first extracted node as its left child and the other extracted node as its right child. Add this node to the min heap.Repeat steps#2 and #3 until the heap contains only one node. The remaining node is the root node and the tree is complete.Let us understand the algorithm with an example:"
},
{
"code": null,
"e": 2453,
"s": 2207,
"text": "Create a leaf node for each unique character and build a min heap of all leaf nodes (Min Heap is used as a priority queue. The value of frequency field is used to compare two nodes in min heap. Initially, the least frequent character is at root)"
},
{
"code": null,
"e": 2518,
"s": 2453,
"text": "Extract two nodes with the minimum frequency from the min heap. "
},
{
"code": null,
"e": 2737,
"s": 2518,
"text": "Create a new internal node with a frequency equal to the sum of the two nodes frequencies. Make the first extracted node as its left child and the other extracted node as its right child. Add this node to the min heap."
},
{
"code": null,
"e": 2908,
"s": 2737,
"text": "Repeat steps#2 and #3 until the heap contains only one node. The remaining node is the root node and the tree is complete.Let us understand the algorithm with an example:"
},
{
"code": null,
"e": 3043,
"s": 2908,
"text": "character Frequency\n a 5\n b 9\n c 12\n d 13\n e 16\n f 45"
},
{
"code": null,
"e": 3260,
"s": 3043,
"text": "Step 1. Build a min heap that contains 6 nodes where each node represents root of a tree with single node.Step 2 Extract two minimum frequency nodes from min heap. Add a new internal node with frequency 5 + 9 = 14. "
},
{
"code": null,
"e": 3399,
"s": 3260,
"text": "Now min heap contains 5 nodes where 4 nodes are roots of trees with single element each, and one heap node is root of tree with 3 elements"
},
{
"code": null,
"e": 3408,
"s": 3399,
"text": "Chapters"
},
{
"code": null,
"e": 3435,
"s": 3408,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 3485,
"s": 3435,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 3508,
"s": 3485,
"text": "captions off, selected"
},
{
"code": null,
"e": 3516,
"s": 3508,
"text": "English"
},
{
"code": null,
"e": 3540,
"s": 3516,
"text": "This is a modal window."
},
{
"code": null,
"e": 3609,
"s": 3540,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 3631,
"s": 3609,
"text": "End of dialog window."
},
{
"code": null,
"e": 3792,
"s": 3631,
"text": "character Frequency\n c 12\n d 13\n Internal Node 14\n e 16\n f 45"
},
{
"code": null,
"e": 3900,
"s": 3792,
"text": "Step 3: Extract two minimum frequency nodes from heap. Add a new internal node with frequency 12 + 13 = 25 "
},
{
"code": null,
"e": 4050,
"s": 3900,
"text": "Now min heap contains 4 nodes where 2 nodes are roots of trees with single element each, and two heap nodes are root of tree with more than one nodes"
},
{
"code": null,
"e": 4184,
"s": 4050,
"text": "character Frequency\nInternal Node 14\n e 16\nInternal Node 25\n f 45"
},
{
"code": null,
"e": 4282,
"s": 4184,
"text": "Step 4: Extract two minimum frequency nodes. Add a new internal node with frequency 14 + 16 = 30 "
},
{
"code": null,
"e": 4313,
"s": 4282,
"text": "Now min heap contains 3 nodes."
},
{
"code": null,
"e": 4418,
"s": 4313,
"text": "character Frequency\nInternal Node 25\nInternal Node 30\n f 45 "
},
{
"code": null,
"e": 4516,
"s": 4418,
"text": "Step 5: Extract two minimum frequency nodes. Add a new internal node with frequency 25 + 30 = 55 "
},
{
"code": null,
"e": 4547,
"s": 4516,
"text": "Now min heap contains 2 nodes."
},
{
"code": null,
"e": 4611,
"s": 4547,
"text": "character Frequency\n f 45\nInternal Node 55"
},
{
"code": null,
"e": 4710,
"s": 4611,
"text": "Step 6: Extract two minimum frequency nodes. Add a new internal node with frequency 45 + 55 = 100 "
},
{
"code": null,
"e": 4747,
"s": 4710,
"text": "Now min heap contains only one node."
},
{
"code": null,
"e": 4793,
"s": 4747,
"text": "character Frequency\nInternal Node 100"
},
{
"code": null,
"e": 4858,
"s": 4793,
"text": "Since the heap contains only one node, the algorithm stops here."
},
{
"code": null,
"e": 5134,
"s": 4858,
"text": "Steps to print codes from Huffman Tree:Traverse the tree formed starting from the root. Maintain an auxiliary array. While moving to the left child, write 0 to the array. While moving to the right child, write 1 to the array. Print the array when a leaf node is encountered. "
},
{
"code": null,
"e": 5160,
"s": 5134,
"text": "The codes are as follows:"
},
{
"code": null,
"e": 5296,
"s": 5160,
"text": "character code-word\n f 0\n c 100\n d 101\n a 1100\n b 1101\n e 111"
},
{
"code": null,
"e": 5344,
"s": 5296,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 5346,
"s": 5344,
"text": "C"
},
{
"code": null,
"e": 5350,
"s": 5346,
"text": "C++"
},
{
"code": null,
"e": 5354,
"s": 5350,
"text": "C++"
},
{
"code": null,
"e": 5359,
"s": 5354,
"text": "Java"
},
{
"code": null,
"e": 5367,
"s": 5359,
"text": "Python3"
},
{
"code": null,
"e": 5378,
"s": 5367,
"text": "Javascript"
},
{
"code": "// C program for Huffman Coding#include <stdio.h>#include <stdlib.h> // This constant can be avoided by explicitly// calculating height of Huffman Tree#define MAX_TREE_HT 100 // A Huffman tree nodestruct MinHeapNode { // One of the input characters char data; // Frequency of the character unsigned freq; // Left and right child of this node struct MinHeapNode *left, *right;}; // A Min Heap: Collection of// min-heap (or Huffman tree) nodesstruct MinHeap { // Current size of min heap unsigned size; // capacity of min heap unsigned capacity; // Array of minheap node pointers struct MinHeapNode** array;}; // A utility function allocate a new// min heap node with given character// and frequency of the characterstruct MinHeapNode* newNode(char data, unsigned freq){ struct MinHeapNode* temp = (struct MinHeapNode*)malloc( sizeof(struct MinHeapNode)); temp->left = temp->right = NULL; temp->data = data; temp->freq = freq; return temp;} // A utility function to create// a min heap of given capacitystruct MinHeap* createMinHeap(unsigned capacity) { struct MinHeap* minHeap = (struct MinHeap*)malloc(sizeof(struct MinHeap)); // current size is 0 minHeap->size = 0; minHeap->capacity = capacity; minHeap->array = (struct MinHeapNode**)malloc( minHeap->capacity * sizeof(struct MinHeapNode*)); return minHeap;} // A utility function to// swap two min heap nodesvoid swapMinHeapNode(struct MinHeapNode** a, struct MinHeapNode** b) { struct MinHeapNode* t = *a; *a = *b; *b = t;} // The standard minHeapify function.void minHeapify(struct MinHeap* minHeap, int idx) { int smallest = idx; int left = 2 * idx + 1; int right = 2 * idx + 2; if (left < minHeap->size && minHeap->array[left]->freq < minHeap->array[smallest]->freq) smallest = left; if (right < minHeap->size && minHeap->array[right]->freq < minHeap->array[smallest]->freq) smallest = right; if (smallest != idx) { swapMinHeapNode(&minHeap->array[smallest], &minHeap->array[idx]); minHeapify(minHeap, smallest); }} // A utility function to check// if size of heap is 1 or notint isSizeOne(struct MinHeap* minHeap){ return (minHeap->size == 1);} // A standard function to extract// minimum value node from heapstruct MinHeapNode* extractMin(struct MinHeap* minHeap) { struct MinHeapNode* temp = minHeap->array[0]; minHeap->array[0] = minHeap->array[minHeap->size - 1]; --minHeap->size; minHeapify(minHeap, 0); return temp;} // A utility function to insert// a new node to Min Heapvoid insertMinHeap(struct MinHeap* minHeap, struct MinHeapNode* minHeapNode) { ++minHeap->size; int i = minHeap->size - 1; while (i && minHeapNode->freq < minHeap->array[(i - 1) / 2]->freq) { minHeap->array[i] = minHeap->array[(i - 1) / 2]; i = (i - 1) / 2; } minHeap->array[i] = minHeapNode;} // A standard function to build min heapvoid buildMinHeap(struct MinHeap* minHeap) { int n = minHeap->size - 1; int i; for (i = (n - 1) / 2; i >= 0; --i) minHeapify(minHeap, i);} // A utility function to print an array of size nvoid printArr(int arr[], int n){ int i; for (i = 0; i < n; ++i) printf(\"%d\", arr[i]); printf(\"\\n\");} // Utility function to check if this node is leafint isLeaf(struct MinHeapNode* root) { return !(root->left) && !(root->right);} // Creates a min heap of capacity// equal to size and inserts all character of// data[] in min heap. Initially size of// min heap is equal to capacitystruct MinHeap* createAndBuildMinHeap(char data[], int freq[], int size) { struct MinHeap* minHeap = createMinHeap(size); for (int i = 0; i < size; ++i) minHeap->array[i] = newNode(data[i], freq[i]); minHeap->size = size; buildMinHeap(minHeap); return minHeap;} // The main function that builds Huffman treestruct MinHeapNode* buildHuffmanTree(char data[], int freq[], int size) { struct MinHeapNode *left, *right, *top; // Step 1: Create a min heap of capacity // equal to size. Initially, there are // modes equal to size. struct MinHeap* minHeap = createAndBuildMinHeap(data, freq, size); // Iterate while size of heap doesn't become 1 while (!isSizeOne(minHeap)) { // Step 2: Extract the two minimum // freq items from min heap left = extractMin(minHeap); right = extractMin(minHeap); // Step 3: Create a new internal // node with frequency equal to the // sum of the two nodes frequencies. // Make the two extracted node as // left and right children of this new node. // Add this node to the min heap // '$' is a special value for internal nodes, not // used top = newNode('$', left->freq + right->freq); top->left = left; top->right = right; insertMinHeap(minHeap, top); } // Step 4: The remaining node is the // root node and the tree is complete. return extractMin(minHeap);} // Prints huffman codes from the root of Huffman Tree.// It uses arr[] to store codesvoid printCodes(struct MinHeapNode* root, int arr[], int top) { // Assign 0 to left edge and recur if (root->left) { arr[top] = 0; printCodes(root->left, arr, top + 1); } // Assign 1 to right edge and recur if (root->right) { arr[top] = 1; printCodes(root->right, arr, top + 1); } // If this is a leaf node, then // it contains one of the input // characters, print the character // and its code from arr[] if (isLeaf(root)) { printf(\"%c: \", root->data); printArr(arr, top); }} // The main function that builds a// Huffman Tree and print codes by traversing// the built Huffman Treevoid HuffmanCodes(char data[], int freq[], int size) { // Construct Huffman Tree struct MinHeapNode* root = buildHuffmanTree(data, freq, size); // Print Huffman codes using // the Huffman tree built above int arr[MAX_TREE_HT], top = 0; printCodes(root, arr, top);} // Driver codeint main(){ char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; int freq[] = { 5, 9, 12, 13, 16, 45 }; int size = sizeof(arr) / sizeof(arr[0]); HuffmanCodes(arr, freq, size); return 0;}",
"e": 11924,
"s": 5378,
"text": null
},
{
"code": "// C++ program for Huffman Coding#include <iostream>#include <cstdlib>using namespace std; // This constant can be avoided by explicitly// calculating height of Huffman Tree#define MAX_TREE_HT 100 // A Huffman tree nodestruct MinHeapNode { // One of the input characters char data; // Frequency of the character unsigned freq; // Left and right child of this node struct MinHeapNode *left, *right;}; // A Min Heap: Collection of// min-heap (or Huffman tree) nodesstruct MinHeap { // Current size of min heap unsigned size; // capacity of min heap unsigned capacity; // Array of minheap node pointers struct MinHeapNode** array;}; // A utility function allocate a new// min heap node with given character// and frequency of the characterstruct MinHeapNode* newNode(char data, unsigned freq){ struct MinHeapNode* temp = (struct MinHeapNode*)malloc(sizeof(struct MinHeapNode)); temp->left = temp->right = NULL; temp->data = data; temp->freq = freq; return temp;} // A utility function to create// a min heap of given capacitystruct MinHeap* createMinHeap(unsigned capacity) { struct MinHeap* minHeap = (struct MinHeap*)malloc(sizeof(struct MinHeap)); // current size is 0 minHeap->size = 0; minHeap->capacity = capacity; minHeap->array = (struct MinHeapNode**)malloc(minHeap->capacity * sizeof(struct MinHeapNode*)); return minHeap;} // A utility function to// swap two min heap nodesvoid swapMinHeapNode(struct MinHeapNode** a, struct MinHeapNode** b) { struct MinHeapNode* t = *a; *a = *b; *b = t;} // The standard minHeapify function.void minHeapify(struct MinHeap* minHeap, int idx) { int smallest = idx; int left = 2 * idx + 1; int right = 2 * idx + 2; if (left < minHeap->size && minHeap->array[left]->freq < minHeap->array[smallest]->freq) smallest = left; if (right < minHeap->size && minHeap->array[right]->freq < minHeap->array[smallest]->freq) smallest = right; if (smallest != idx) { swapMinHeapNode(&minHeap->array[smallest], &minHeap->array[idx]); minHeapify(minHeap, smallest); }} // A utility function to check// if size of heap is 1 or notint isSizeOne(struct MinHeap* minHeap){ return (minHeap->size == 1);} // A standard function to extract// minimum value node from heapstruct MinHeapNode* extractMin(struct MinHeap* minHeap) { struct MinHeapNode* temp = minHeap->array[0]; minHeap->array[0] = minHeap->array[minHeap->size - 1]; --minHeap->size; minHeapify(minHeap, 0); return temp;} // A utility function to insert// a new node to Min Heapvoid insertMinHeap(struct MinHeap* minHeap, struct MinHeapNode* minHeapNode) { ++minHeap->size; int i = minHeap->size - 1; while (i && minHeapNode->freq < minHeap->array[(i - 1) / 2]->freq) { minHeap->array[i] = minHeap->array[(i - 1) / 2]; i = (i - 1) / 2; } minHeap->array[i] = minHeapNode;} // A standard function to build min heapvoid buildMinHeap(struct MinHeap* minHeap) { int n = minHeap->size - 1; int i; for (i = (n - 1) / 2; i >= 0; --i) minHeapify(minHeap, i);} // A utility function to print an array of size nvoid printArr(int arr[], int n){ int i; for (i = 0; i < n; ++i) cout<< arr[i]; cout<<\"\\n\";} // Utility function to check if this node is leafint isLeaf(struct MinHeapNode* root) { return !(root->left) && !(root->right);} // Creates a min heap of capacity// equal to size and inserts all character of// data[] in min heap. Initially size of// min heap is equal to capacitystruct MinHeap* createAndBuildMinHeap(char data[], int freq[], int size) { struct MinHeap* minHeap = createMinHeap(size); for (int i = 0; i < size; ++i) minHeap->array[i] = newNode(data[i], freq[i]); minHeap->size = size; buildMinHeap(minHeap); return minHeap;} // The main function that builds Huffman treestruct MinHeapNode* buildHuffmanTree(char data[], int freq[], int size) { struct MinHeapNode *left, *right, *top; // Step 1: Create a min heap of capacity // equal to size. Initially, there are // modes equal to size. struct MinHeap* minHeap = createAndBuildMinHeap(data, freq, size); // Iterate while size of heap doesn't become 1 while (!isSizeOne(minHeap)) { // Step 2: Extract the two minimum // freq items from min heap left = extractMin(minHeap); right = extractMin(minHeap); // Step 3: Create a new internal // node with frequency equal to the // sum of the two nodes frequencies. // Make the two extracted node as // left and right children of this new node. // Add this node to the min heap // '$' is a special value for internal nodes, not used top = newNode('$', left->freq + right->freq); top->left = left; top->right = right; insertMinHeap(minHeap, top); } // Step 4: The remaining node is the // root node and the tree is complete. return extractMin(minHeap);} // Prints huffman codes from the root of Huffman Tree.// It uses arr[] to store codesvoid printCodes(struct MinHeapNode* root, int arr[], int top) { // Assign 0 to left edge and recur if (root->left) { arr[top] = 0; printCodes(root->left, arr, top + 1); } // Assign 1 to right edge and recur if (root->right) { arr[top] = 1; printCodes(root->right, arr, top + 1); } // If this is a leaf node, then // it contains one of the input // characters, print the character // and its code from arr[] if (isLeaf(root)) { cout<< root->data <<\": \"; printArr(arr, top); }} // The main function that builds a// Huffman Tree and print codes by traversing// the built Huffman Treevoid HuffmanCodes(char data[], int freq[], int size) { // Construct Huffman Tree struct MinHeapNode* root = buildHuffmanTree(data, freq, size); // Print Huffman codes using // the Huffman tree built above int arr[MAX_TREE_HT], top = 0; printCodes(root, arr, top);} // Driver codeint main(){ char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; int freq[] = { 5, 9, 12, 13, 16, 45 }; int size = sizeof(arr) / sizeof(arr[0]); HuffmanCodes(arr, freq, size); return 0;}",
"e": 18305,
"s": 11924,
"text": null
},
{
"code": "// C++(STL) program for Huffman Coding with STL#include <bits/stdc++.h>using namespace std; // A Huffman tree nodestruct MinHeapNode { // One of the input characters char data; // Frequency of the character unsigned freq; // Left and right child MinHeapNode *left, *right; MinHeapNode(char data, unsigned freq) { left = right = NULL; this->data = data; this->freq = freq; }}; // For comparison of// two heap nodes (needed in min heap)struct compare { bool operator()(MinHeapNode* l, MinHeapNode* r) { return (l->freq > r->freq); }}; // Prints huffman codes from// the root of Huffman Tree.void printCodes(struct MinHeapNode* root, string str){ if (!root) return; if (root->data != '$') cout << root->data << \": \" << str << \"\\n\"; printCodes(root->left, str + \"0\"); printCodes(root->right, str + \"1\");} // The main function that builds a Huffman Tree and// print codes by traversing the built Huffman Treevoid HuffmanCodes(char data[], int freq[], int size){ struct MinHeapNode *left, *right, *top; // Create a min heap & inserts all characters of data[] priority_queue<MinHeapNode*, vector<MinHeapNode*>, compare> minHeap; for (int i = 0; i < size; ++i) minHeap.push(new MinHeapNode(data[i], freq[i])); // Iterate while size of heap doesn't become 1 while (minHeap.size() != 1) { // Extract the two minimum // freq items from min heap left = minHeap.top(); minHeap.pop(); right = minHeap.top(); minHeap.pop(); // Create a new internal node with // frequency equal to the sum of the // two nodes frequencies. Make the // two extracted node as left and right children // of this new node. Add this node // to the min heap '$' is a special value // for internal nodes, not used top = new MinHeapNode('$', left->freq + right->freq); top->left = left; top->right = right; minHeap.push(top); } // Print Huffman codes using // the Huffman tree built above printCodes(minHeap.top(), \"\");} // Driver Codeint main(){ char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; int freq[] = { 5, 9, 12, 13, 16, 45 }; int size = sizeof(arr) / sizeof(arr[0]); HuffmanCodes(arr, freq, size); return 0;} // This code is contributed by Aditya Goel",
"e": 20708,
"s": 18305,
"text": null
},
{
"code": "import java.util.PriorityQueue;import java.util.Scanner;import java.util.Comparator; // node class is the basic structure// of each node present in the Huffman - tree.class HuffmanNode { int data; char c; HuffmanNode left; HuffmanNode right;} // comparator class helps to compare the node// on the basis of one of its attribute.// Here we will be compared// on the basis of data values of the nodes.class MyComparator implements Comparator<HuffmanNode> { public int compare(HuffmanNode x, HuffmanNode y) { return x.data - y.data; }} public class Huffman { // recursive function to print the // huffman-code through the tree traversal. // Here s is the huffman - code generated. public static void printCode(HuffmanNode root, String s) { // base case; if the left and right are null // then its a leaf node and we print // the code s generated by traversing the tree. if (root.left == null && root.right == null && Character.isLetter(root.c)) { // c is the character in the node System.out.println(root.c + \":\" + s); return; } // if we go to left then add \"0\" to the code. // if we go to the right add\"1\" to the code. // recursive calls for left and // right sub-tree of the generated tree. printCode(root.left, s + \"0\"); printCode(root.right, s + \"1\"); } // main function public static void main(String[] args) { Scanner s = new Scanner(System.in); // number of characters. int n = 6; char[] charArray = { 'a', 'b', 'c', 'd', 'e', 'f' }; int[] charfreq = { 5, 9, 12, 13, 16, 45 }; // creating a priority queue q. // makes a min-priority queue(min-heap). PriorityQueue<HuffmanNode> q = new PriorityQueue<HuffmanNode>(n, new MyComparator()); for (int i = 0; i < n; i++) { // creating a Huffman node object // and add it to the priority queue. HuffmanNode hn = new HuffmanNode(); hn.c = charArray[i]; hn.data = charfreq[i]; hn.left = null; hn.right = null; // add functions adds // the huffman node to the queue. q.add(hn); } // create a root node HuffmanNode root = null; // Here we will extract the two minimum value // from the heap each time until // its size reduces to 1, extract until // all the nodes are extracted. while (q.size() > 1) { // first min extract. HuffmanNode x = q.peek(); q.poll(); // second min extract. HuffmanNode y = q.peek(); q.poll(); // new node f which is equal HuffmanNode f = new HuffmanNode(); // to the sum of the frequency of the two nodes // assigning values to the f node. f.data = x.data + y.data; f.c = '-'; // first extracted node as left child. f.left = x; // second extracted node as the right child. f.right = y; // marking the f node as the root node. root = f; // add this node to the priority-queue. q.add(f); } // print the codes by traversing the tree printCode(root, \"\"); }} // This code is contributed by Kunwar Desh Deepak Singh",
"e": 24219,
"s": 20708,
"text": null
},
{
"code": "# A Huffman Tree Nodeclass node: def __init__(self, freq, symbol, left=None, right=None): # frequency of symbol self.freq = freq # symbol name (character) self.symbol = symbol # node left of current node self.left = left # node right of current node self.right = right # tree direction (0/1) self.huff = '' # utility function to print huffman# codes for all symbols in the newly# created Huffman tree def printNodes(node, val=''): # huffman code for current node newVal = val + str(node.huff) # if node is not an edge node # then traverse inside it if(node.left): printNodes(node.left, newVal) if(node.right): printNodes(node.right, newVal) # if node is edge node then # display its huffman code if(not node.left and not node.right): print(f\"{node.symbol} -> {newVal}\") # characters for huffman treechars = ['a', 'b', 'c', 'd', 'e', 'f'] # frequency of charactersfreq = [ 5, 9, 12, 13, 16, 45] # list containing unused nodesnodes = [] # converting characters and frequencies# into huffman tree nodesfor x in range(len(chars)): nodes.append(node(freq[x], chars[x])) while len(nodes) > 1: # sort all the nodes in ascending order # based on theri frequency nodes = sorted(nodes, key=lambda x: x.freq) # pick 2 smallest nodes left = nodes[0] right = nodes[1] # assign directional value to these nodes left.huff = 0 right.huff = 1 # combine the 2 smallest nodes to create # new node as their parent newNode = node(left.freq+right.freq, left.symbol+right.symbol, left, right) # remove the 2 nodes and add their # parent as new node among others nodes.remove(left) nodes.remove(right) nodes.append(newNode) # Huffman Tree is ready!printNodes(nodes[0])",
"e": 26059,
"s": 24219,
"text": null
},
{
"code": "<script> // node class is the basic structure// of each node present in the Huffman - tree.class HuffmanNode{ constructor() { this.data = 0; this.c = ''; this.left = this.right = null; }} // recursive function to print the // huffman-code through the tree traversal. // Here s is the huffman - code generated. function printCode(root,s) { // base case; if the left and right are null // then its a leaf node and we print // the code s generated by traversing the tree. if (root.left == null && root.right == null && (root.c).toLowerCase() != (root.c).toUpperCase()) { // c is the character in the node document.write(root.c + \":\" + s+\"<br>\"); return; } // if we go to left then add \"0\" to the code. // if we go to the right add\"1\" to the code. // recursive calls for left and // right sub-tree of the generated tree. printCode(root.left, s + \"0\"); printCode(root.right, s + \"1\"); } // main function // number of characters. let n = 6; let charArray = [ 'a', 'b', 'c', 'd', 'e', 'f' ]; let charfreq = [ 5, 9, 12, 13, 16, 45 ]; // creating a priority queue q. // makes a min-priority queue(min-heap). let q = []; for (let i = 0; i < n; i++) { // creating a Huffman node object // and add it to the priority queue. let hn = new HuffmanNode(); hn.c = charArray[i]; hn.data = charfreq[i]; hn.left = null; hn.right = null; // add functions adds // the huffman node to the queue. q.push(hn); } // create a root node let root = null; q.sort(function(a,b){return a.data-b.data;}); // Here we will extract the two minimum value // from the heap each time until // its size reduces to 1, extract until // all the nodes are extracted. while (q.length > 1) { // first min extract. let x = q[0]; q.shift(); // second min extract. let y = q[0]; q.shift(); // new node f which is equal let f = new HuffmanNode(); // to the sum of the frequency of the two nodes // assigning values to the f node. f.data = x.data + y.data; f.c = '-'; // first extracted node as left child. f.left = x; // second extracted node as the right child. f.right = y; // marking the f node as the root node. root = f; // add this node to the priority-queue. q.push(f); q.sort(function(a,b){return a.data-b.data;}); } // print the codes by traversing the tree printCode(root, \"\"); // This code is contributed by avanitrachhadiya2155</script>",
"e": 29086,
"s": 26059,
"text": null
},
{
"code": null,
"e": 29094,
"s": 29086,
"text": "Output:"
},
{
"code": null,
"e": 29136,
"s": 29094,
"text": "f: 0\nc: 100\nd: 101\na: 1100\nb: 1101\ne: 111"
},
{
"code": null,
"e": 29475,
"s": 29136,
"text": "Time complexity: O(nlogn) where n is the number of unique characters. If there are n nodes, extractMin() is called 2*(n – 1) times. extractMin() takes O(logn) time as it calles minHeapify(). So, overall complexity is O(nlogn).If the input array is sorted, there exists a linear time algorithm. We will soon be discussing in our next post."
},
{
"code": null,
"e": 29692,
"s": 29475,
"text": "They are used for transmitting fax and text.They are used by conventional compression formats like PKZIP, GZIP, etc.Multimedia codecs like JPEG, PNG, and MP3 use Huffman encoding(to be more precise the prefix codes)."
},
{
"code": null,
"e": 29737,
"s": 29692,
"text": "They are used for transmitting fax and text."
},
{
"code": null,
"e": 29810,
"s": 29737,
"text": "They are used by conventional compression formats like PKZIP, GZIP, etc."
},
{
"code": null,
"e": 29911,
"s": 29810,
"text": "Multimedia codecs like JPEG, PNG, and MP3 use Huffman encoding(to be more precise the prefix codes)."
},
{
"code": null,
"e": 29994,
"s": 29911,
"text": " It is useful in cases where there is a series of frequently occurring characters."
},
{
"code": null,
"e": 30253,
"s": 29994,
"text": "Reference:http://en.wikipedia.org/wiki/Huffman_codingThis article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 30262,
"s": 30253,
"text": "kddeepak"
},
{
"code": null,
"e": 30275,
"s": 30262,
"text": "SoumikMondal"
},
{
"code": null,
"e": 30286,
"s": 30275,
"text": "AyushShaZz"
},
{
"code": null,
"e": 30299,
"s": 30286,
"text": "deekshant149"
},
{
"code": null,
"e": 30321,
"s": 30299,
"text": "tripathipriyanshu1998"
},
{
"code": null,
"e": 30332,
"s": 30321,
"text": "tacklestar"
},
{
"code": null,
"e": 30353,
"s": 30332,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 30370,
"s": 30353,
"text": "arorakashish0911"
},
{
"code": null,
"e": 30383,
"s": 30370,
"text": "simmytarika5"
},
{
"code": null,
"e": 30395,
"s": 30383,
"text": "krisania804"
},
{
"code": null,
"e": 30402,
"s": 30395,
"text": "Amazon"
},
{
"code": null,
"e": 30420,
"s": 30402,
"text": "encoding-decoding"
},
{
"code": null,
"e": 30435,
"s": 30420,
"text": "Huffman Coding"
},
{
"code": null,
"e": 30450,
"s": 30435,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 30465,
"s": 30450,
"text": "priority-queue"
},
{
"code": null,
"e": 30473,
"s": 30465,
"text": "Samsung"
},
{
"code": null,
"e": 30493,
"s": 30473,
"text": "United Health Group"
},
{
"code": null,
"e": 30500,
"s": 30493,
"text": "Greedy"
},
{
"code": null,
"e": 30505,
"s": 30500,
"text": "Heap"
},
{
"code": null,
"e": 30520,
"s": 30505,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 30527,
"s": 30520,
"text": "Amazon"
},
{
"code": null,
"e": 30535,
"s": 30527,
"text": "Samsung"
},
{
"code": null,
"e": 30555,
"s": 30535,
"text": "United Health Group"
},
{
"code": null,
"e": 30562,
"s": 30555,
"text": "Greedy"
},
{
"code": null,
"e": 30567,
"s": 30562,
"text": "Heap"
},
{
"code": null,
"e": 30582,
"s": 30567,
"text": "priority-queue"
}
] |
How to Create custom Turtle shapes in Python?
|
19 Apr, 2021
In Turtle, by default, we have an arrowhead-shaped cursor for drawing on the canvas. This can be changed to some other predefined shape or we can also create a custom shape and register it under a name. Not just that, we can even use gif format images to replace our cursor.
The shape() function is used to set the shape of the cursor. The pre-defined shapes include turtle, arrow, circle, square and triangle.
Python3
import turtle # turtle objectc_turtle = turtle.Turtle() # changing the cursor# shape to circlec_turtle.shape('circle')
The turtle module has register_shape() function for registering custom shapes.
Syntax : turtle.register_shape(name, shape) Parameters :
name : a string- the name of the shape to be registered.
shape : a tuple of tuples containing the coordinates for the custom shape.
The n-tuple argument for the shape parameter, denotes the relative position of each corner of an n-sided polygon. Let us try to create a simple diamond shape to understand this.Consider this diamond, having length of diagonal = 20, in a Cartesian plane :
To create this shape, we need to pass these coordinates in clockwise order.
Python3
import turtle # turtle objectdimond_turtle = turtle.Turtle() # the coordinates# of each cornershape =((0, 0), (10, 10), (20, 0), (10, -10)) # registering the new shapeturtle.register_shape('diamond', shape) # changing the shape to 'diamond'dimond_turtle.shape('diamond')
Using images for Turtle cursorTo use an image as the cursor, we need to pass the image file path as parameter to register_shape(). Note that this image has to be in gif format.
Python3
import turtle # turtle objectimg_turtle = turtle.Turtle() # registering the image# as a new shapeturtle.register_shape('example.gif') # setting the image as cursorimg_turtle.shape('example.gif')
arorakashish0911
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Apr, 2021"
},
{
"code": null,
"e": 327,
"s": 52,
"text": "In Turtle, by default, we have an arrowhead-shaped cursor for drawing on the canvas. This can be changed to some other predefined shape or we can also create a custom shape and register it under a name. Not just that, we can even use gif format images to replace our cursor."
},
{
"code": null,
"e": 465,
"s": 327,
"text": "The shape() function is used to set the shape of the cursor. The pre-defined shapes include turtle, arrow, circle, square and triangle. "
},
{
"code": null,
"e": 473,
"s": 465,
"text": "Python3"
},
{
"code": "import turtle # turtle objectc_turtle = turtle.Turtle() # changing the cursor# shape to circlec_turtle.shape('circle')",
"e": 594,
"s": 473,
"text": null
},
{
"code": null,
"e": 677,
"s": 596,
"text": "The turtle module has register_shape() function for registering custom shapes. "
},
{
"code": null,
"e": 736,
"s": 677,
"text": "Syntax : turtle.register_shape(name, shape) Parameters : "
},
{
"code": null,
"e": 793,
"s": 736,
"text": "name : a string- the name of the shape to be registered."
},
{
"code": null,
"e": 870,
"s": 795,
"text": "shape : a tuple of tuples containing the coordinates for the custom shape."
},
{
"code": null,
"e": 1129,
"s": 874,
"text": "The n-tuple argument for the shape parameter, denotes the relative position of each corner of an n-sided polygon. Let us try to create a simple diamond shape to understand this.Consider this diamond, having length of diagonal = 20, in a Cartesian plane :"
},
{
"code": null,
"e": 1211,
"s": 1135,
"text": "To create this shape, we need to pass these coordinates in clockwise order."
},
{
"code": null,
"e": 1221,
"s": 1213,
"text": "Python3"
},
{
"code": "import turtle # turtle objectdimond_turtle = turtle.Turtle() # the coordinates# of each cornershape =((0, 0), (10, 10), (20, 0), (10, -10)) # registering the new shapeturtle.register_shape('diamond', shape) # changing the shape to 'diamond'dimond_turtle.shape('diamond')",
"e": 1492,
"s": 1221,
"text": null
},
{
"code": null,
"e": 1670,
"s": 1492,
"text": "Using images for Turtle cursorTo use an image as the cursor, we need to pass the image file path as parameter to register_shape(). Note that this image has to be in gif format. "
},
{
"code": null,
"e": 1678,
"s": 1670,
"text": "Python3"
},
{
"code": "import turtle # turtle objectimg_turtle = turtle.Turtle() # registering the image# as a new shapeturtle.register_shape('example.gif') # setting the image as cursorimg_turtle.shape('example.gif')",
"e": 1874,
"s": 1678,
"text": null
},
{
"code": null,
"e": 1893,
"s": 1876,
"text": "arorakashish0911"
},
{
"code": null,
"e": 1907,
"s": 1893,
"text": "Python-turtle"
},
{
"code": null,
"e": 1914,
"s": 1907,
"text": "Python"
}
] |
PostgreSQL – Array Data Type
|
30 Jun, 2022
PostgreSQL Supports the concept of Arrays. All data type has a companion array associated with it irrespective of the properties of the data type.It is available even for user-defined data types.
Syntax: variable_name DATA TYPE [];
Now that we know the use and need of Arrays in PostgreSQL, let’s look into some examples. Example 1: First we create a table(say, contacts) where the phones column is defined as an array of text as follows:
CREATE TABLE contacts (
id serial PRIMARY KEY,
name VARCHAR (100),
phones TEXT []
);
Now we insert some contacts to our table as follows:
INSERT INTO contacts (name, phones)
VALUES
(
'Raju Kumar',
'{"(408)-589-5841"}'
),
(
'Nikhil Aggarwal',
'{"(408)-589-5841"}'
),
(
'Anshul Aggarwal',
'{"(408)-589-5841"}'
),
(
'Puja Singh',
'{"(408)-589-5842", "(408)-589-58423"}'
);
Now we query for the contact data as follows:
SELECT
name,
phones
FROM
contacts;
Output: Example 2: In the same table we created in the above example we will query to know who has the phone number (408)-589-5842 irrespective of the position of the phone number in the phone’s array, using ANY() function as follows:
SELECT
name,
phones
FROM
contacts
WHERE
'(408)-589-5842' = ANY (phones);
Output:
surinderdawra388
postgreSQL
postgreSQL-dataTypes
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jun, 2022"
},
{
"code": null,
"e": 225,
"s": 28,
"text": "PostgreSQL Supports the concept of Arrays. All data type has a companion array associated with it irrespective of the properties of the data type.It is available even for user-defined data types."
},
{
"code": null,
"e": 261,
"s": 225,
"text": "Syntax: variable_name DATA TYPE [];"
},
{
"code": null,
"e": 468,
"s": 261,
"text": "Now that we know the use and need of Arrays in PostgreSQL, let’s look into some examples. Example 1: First we create a table(say, contacts) where the phones column is defined as an array of text as follows:"
},
{
"code": null,
"e": 565,
"s": 468,
"text": "CREATE TABLE contacts (\n id serial PRIMARY KEY,\n name VARCHAR (100),\n phones TEXT []\n);"
},
{
"code": null,
"e": 618,
"s": 565,
"text": "Now we insert some contacts to our table as follows:"
},
{
"code": null,
"e": 946,
"s": 618,
"text": "INSERT INTO contacts (name, phones)\nVALUES\n (\n 'Raju Kumar',\n '{\"(408)-589-5841\"}'\n ),\n (\n 'Nikhil Aggarwal',\n '{\"(408)-589-5841\"}'\n ),\n (\n 'Anshul Aggarwal',\n '{\"(408)-589-5841\"}'\n ),\n (\n 'Puja Singh',\n '{\"(408)-589-5842\", \"(408)-589-58423\"}'\n );"
},
{
"code": null,
"e": 992,
"s": 946,
"text": "Now we query for the contact data as follows:"
},
{
"code": null,
"e": 1039,
"s": 992,
"text": "SELECT\n name,\n phones\nFROM\n contacts;"
},
{
"code": null,
"e": 1275,
"s": 1039,
"text": "Output: Example 2: In the same table we created in the above example we will query to know who has the phone number (408)-589-5842 irrespective of the position of the phone number in the phone’s array, using ANY() function as follows:"
},
{
"code": null,
"e": 1364,
"s": 1275,
"text": "SELECT\n name,\n phones\nFROM\n contacts\nWHERE\n '(408)-589-5842' = ANY (phones);"
},
{
"code": null,
"e": 1373,
"s": 1364,
"text": "Output: "
},
{
"code": null,
"e": 1390,
"s": 1373,
"text": "surinderdawra388"
},
{
"code": null,
"e": 1401,
"s": 1390,
"text": "postgreSQL"
},
{
"code": null,
"e": 1422,
"s": 1401,
"text": "postgreSQL-dataTypes"
},
{
"code": null,
"e": 1433,
"s": 1422,
"text": "PostgreSQL"
}
] |
UGC-NET | UGC NET CS 2017 Jan – III | Question 50
|
27 Nov, 2018
Consider a disk queue with I/O requests on the following cylinders in their arriving order:
6, 10, 12, 54, 97, 73, 128, 15, 44, 110, 34, 45
The disk head is assumed to be at cylinder 23 and moving in the direction of decreasing number of cylinders. Total number of cylinders in the disk is 150. The disk head movement using SCAN-scheduling algorithm is:(A) 172(B) 173(C) 227(D) 228Answer:Explanation: According to SCAN disk scheduling algorithm:
When it completed its last given sequence from input, it stops.So, total disk head movement = 23+128 = 151.
So, none option matches.Quiz of this Question
UGC-NET
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Nov, 2018"
},
{
"code": null,
"e": 120,
"s": 28,
"text": "Consider a disk queue with I/O requests on the following cylinders in their arriving order:"
},
{
"code": null,
"e": 169,
"s": 120,
"text": "6, 10, 12, 54, 97, 73, 128, 15, 44, 110, 34, 45 "
},
{
"code": null,
"e": 475,
"s": 169,
"text": "The disk head is assumed to be at cylinder 23 and moving in the direction of decreasing number of cylinders. Total number of cylinders in the disk is 150. The disk head movement using SCAN-scheduling algorithm is:(A) 172(B) 173(C) 227(D) 228Answer:Explanation: According to SCAN disk scheduling algorithm:"
},
{
"code": null,
"e": 583,
"s": 475,
"text": "When it completed its last given sequence from input, it stops.So, total disk head movement = 23+128 = 151."
},
{
"code": null,
"e": 629,
"s": 583,
"text": "So, none option matches.Quiz of this Question"
},
{
"code": null,
"e": 637,
"s": 629,
"text": "UGC-NET"
}
] |
How to create an alert in JavaFX?
|
An alert is a dialog which shows pre-built dialog types. You can create an alert by instantiating the javafx.scene.control.Alert class. This class is a subclass of the Dialog class. You can create required type of dialog bypassing the respective parameter at the time of instantiation as −
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
The following Example demonstrates the creation of an Alert.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
public class AlertExample extends Application {
public void start(Stage stage) {
//Creating a dialog
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
//Setting the title
alert.setTitle("Alert");
ButtonType type = new ButtonType("Ok", ButtonData.OK_DONE);
//Setting the content of the dialog
alert.setContentText("This is a confirmmation alert");
//Adding buttons to the dialog pane
alert.getDialogPane().getButtonTypes().add(type);
//Setting the label
Text txt = new Text("Click the button to show the dialog");
Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12);
txt.setFont(font);
//Creating a button
Button button = new Button("Show Dialog");
//Showing the dialog on clicking the button
button.setOnAction(e -> {
alert.showAndWait();
});
//Creating a vbox to hold the button and the label
HBox pane = new HBox(15);
//Setting the space between the nodes of a HBox pane
pane.setPadding(new Insets(50, 150, 50, 60));
pane.getChildren().addAll(txt, button);
//Creating a scene object
Scene scene = new Scene(new Group(pane), 595, 300, Color.BEIGE);
stage.setTitle("Alert");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
|
[
{
"code": null,
"e": 1352,
"s": 1062,
"text": "An alert is a dialog which shows pre-built dialog types. You can create an alert by instantiating the javafx.scene.control.Alert class. This class is a subclass of the Dialog class. You can create required type of dialog bypassing the respective parameter at the time of instantiation as −"
},
{
"code": null,
"e": 1407,
"s": 1352,
"text": "Alert alert = new Alert(Alert.AlertType.CONFIRMATION);"
},
{
"code": null,
"e": 1468,
"s": 1407,
"text": "The following Example demonstrates the creation of an Alert."
},
{
"code": null,
"e": 3459,
"s": 1468,
"text": "import javafx.application.Application;\nimport javafx.geometry.Insets;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Alert;\nimport javafx.scene.control.Alert.AlertType;\nimport javafx.scene.control.Button;\nimport javafx.scene.control.ButtonBar.ButtonData;\nimport javafx.scene.control.ButtonType;\nimport javafx.scene.control.Dialog;\nimport javafx.scene.layout.HBox;\nimport javafx.stage.Stage;\nimport javafx.scene.paint.Color;\nimport javafx.scene.text.Font;\nimport javafx.scene.text.FontPosture;\nimport javafx.scene.text.FontWeight;\nimport javafx.scene.text.Text;\npublic class AlertExample extends Application {\n public void start(Stage stage) {\n //Creating a dialog\n Alert alert = new Alert(Alert.AlertType.CONFIRMATION);\n //Setting the title\n alert.setTitle(\"Alert\");\n ButtonType type = new ButtonType(\"Ok\", ButtonData.OK_DONE);\n //Setting the content of the dialog\n alert.setContentText(\"This is a confirmmation alert\");\n //Adding buttons to the dialog pane\n alert.getDialogPane().getButtonTypes().add(type);\n //Setting the label\n Text txt = new Text(\"Click the button to show the dialog\");\n Font font = Font.font(\"verdana\", FontWeight.BOLD, FontPosture.REGULAR, 12);\n txt.setFont(font);\n //Creating a button\n Button button = new Button(\"Show Dialog\");\n //Showing the dialog on clicking the button\n button.setOnAction(e -> {\n alert.showAndWait();\n });\n //Creating a vbox to hold the button and the label\n HBox pane = new HBox(15);\n //Setting the space between the nodes of a HBox pane\n pane.setPadding(new Insets(50, 150, 50, 60));\n pane.getChildren().addAll(txt, button);\n //Creating a scene object\n Scene scene = new Scene(new Group(pane), 595, 300, Color.BEIGE);\n stage.setTitle(\"Alert\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}"
}
] |
MySQL INSERT INTO SELECT into a table with AUTO_INCREMENT
|
Let us create a table −
mysql> create table DemoTable1923
(
UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
UserName varchar(20)
);
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1923(UserId,UserName)
select 101 as UserId,'Chris' as UserName;
Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> insert into DemoTable1923(UserId,UserName)
select 102 as UserId,'Robert' as UserName;
Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> insert into DemoTable1923(UserId,UserName)
select 103 as UserId,'Sam' as UserName;
Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0
Display all records from the table using select statement −
mysql> select * from DemoTable1923;
This will produce the following output −
+--------+----------+
| UserId | UserName |
+--------+----------+
| 101 | Chris |
| 102 | Robert |
| 103 | Sam |
+--------+----------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1086,
"s": 1062,
"text": "Let us create a table −"
},
{
"code": null,
"e": 1243,
"s": 1086,
"text": "mysql> create table DemoTable1923\n (\n UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n UserName varchar(20)\n );\nQuery OK, 0 rows affected (0.00 sec)"
},
{
"code": null,
"e": 1299,
"s": 1243,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1814,
"s": 1299,
"text": "mysql> insert into DemoTable1923(UserId,UserName)\n select 101 as UserId,'Chris' as UserName;\nQuery OK, 1 row affected (0.00 sec)\nRecords: 1 Duplicates: 0 Warnings: 0\n\nmysql> insert into DemoTable1923(UserId,UserName)\n select 102 as UserId,'Robert' as UserName;\nQuery OK, 1 row affected (0.00 sec)\nRecords: 1 Duplicates: 0 Warnings: 0\n\nmysql> insert into DemoTable1923(UserId,UserName)\n select 103 as UserId,'Sam' as UserName;\nQuery OK, 1 row affected (0.00 sec)\nRecords: 1 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 1874,
"s": 1814,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1910,
"s": 1874,
"text": "mysql> select * from DemoTable1923;"
},
{
"code": null,
"e": 1951,
"s": 1910,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2130,
"s": 1951,
"text": "+--------+----------+\n| UserId | UserName |\n+--------+----------+\n| 101 | Chris |\n| 102 | Robert |\n| 103 | Sam |\n+--------+----------+\n3 rows in set (0.00 sec)"
}
] |
How to represent the mean with vertical line in a histogram created by hist function in R?
|
The value of mean is an important characteristic of the data to be represented by a histogram, therefore, one might want to plot it with the histogram. If the histogram is created by using hist function then we can create a vertical line on the histogram with the help of abline function by defining mean of the data for vertical argument v.
set.seed(101)
x<-rnorm(10000,2,0.75)
hist(x)
Adding a blue color line at the mean value of x in the histogram −
abline(v=mean(x),col="blue",lwd=2)
abline(v=mean(x),col="blue",lwd=8)
|
[
{
"code": null,
"e": 1404,
"s": 1062,
"text": "The value of mean is an important characteristic of the data to be represented by a histogram, therefore, one might want to plot it with the histogram. If the histogram is created by using hist function then we can create a vertical line on the histogram with the help of abline function by defining mean of the data for vertical argument v."
},
{
"code": null,
"e": 1449,
"s": 1404,
"text": "set.seed(101)\nx<-rnorm(10000,2,0.75)\nhist(x)"
},
{
"code": null,
"e": 1516,
"s": 1449,
"text": "Adding a blue color line at the mean value of x in the histogram −"
},
{
"code": null,
"e": 1551,
"s": 1516,
"text": "abline(v=mean(x),col=\"blue\",lwd=2)"
},
{
"code": null,
"e": 1586,
"s": 1551,
"text": "abline(v=mean(x),col=\"blue\",lwd=8)"
}
] |
exit - Unix, Linux Command
|
exit-The exit command terminates a script, just as in a C program. It can also return a value, which is available to the script's parent process.
exit
exit-Issuing the exit command at the shell prompt will cause the shell to exit.
In some cases, if you have jobs running in the background, the shell will remind you that they are running and simply return you to the command prompt. In this case, issuing exit again will terminate those jobs and exit the shell.
Common aliases for exit include "bye", "logout", and "lo".Every command returns an exit status (sometimes referred to as a return status or exit code). A successful command returns a 0, while an unsuccessful one returns a non-zero value that usually can be interpreted as an error code. Well-behaved UNIX commands, programs, and utilities return a 0 exit code upon successful completion, though there are some exceptions.
Likewise, functions within a script and the script itself return an exit status. The last command executed in the function or script determines the exit status. Within a script, an exit nnn command may be used to deliver an nnn exit status to the shell (nnn must be an integer in the 0 - 255 range).
EXAMPLE-1:
To exit from shell:
$ exitoutput:# su ubuntuubuntu@ubuntu:~$ exitexitroot@ubuntu:/home/ubuntu#
EXAMPLE-2:
exit command is used to return the succsess/failure of functionality in script.
# cat test.sh
#!/bin/bashecho "This is a test."# Terminate our shell script with success messageexit 0
root@ubuntu:/home/ubuntu# ./test.shThis is a test.root@ubuntu:/home/ubuntu# echo $?0
root@ubuntu:/home/ubuntu# cat test.sh#!/bin/bashecho "This is a test."# Terminate our shell script with failure messageexit 1
root@ubuntu:/home/ubuntu# ./test.shThis is a test.root@ubuntu:/home/ubuntu# echo $?1
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 10723,
"s": 10577,
"text": "exit-The exit command terminates a script, just as in a C program. It can also return a value, which is available to the script's parent process."
},
{
"code": null,
"e": 10728,
"s": 10723,
"text": "exit"
},
{
"code": null,
"e": 10809,
"s": 10728,
"text": "exit-Issuing the exit command at the shell prompt will cause the shell to exit.\n"
},
{
"code": null,
"e": 11463,
"s": 10809,
"text": "In some cases, if you have jobs running in the background, the shell will remind you that they are running and simply return you to the command prompt. In this case, issuing exit again will terminate those jobs and exit the shell.\nCommon aliases for exit include \"bye\", \"logout\", and \"lo\".Every command returns an exit status (sometimes referred to as a return status or exit code). A successful command returns a 0, while an unsuccessful one returns a non-zero value that usually can be interpreted as an error code. Well-behaved UNIX commands, programs, and utilities return a 0 exit code upon successful completion, though there are some exceptions.\n"
},
{
"code": null,
"e": 11764,
"s": 11463,
"text": "Likewise, functions within a script and the script itself return an exit status. The last command executed in the function or script determines the exit status. Within a script, an exit nnn command may be used to deliver an nnn exit status to the shell (nnn must be an integer in the 0 - 255 range).\n"
},
{
"code": null,
"e": 11775,
"s": 11764,
"text": "EXAMPLE-1:"
},
{
"code": null,
"e": 11795,
"s": 11775,
"text": "To exit from shell:"
},
{
"code": null,
"e": 11871,
"s": 11795,
"text": "$ exitoutput:# su ubuntuubuntu@ubuntu:~$ exitexitroot@ubuntu:/home/ubuntu#\n"
},
{
"code": null,
"e": 11882,
"s": 11871,
"text": "EXAMPLE-2:"
},
{
"code": null,
"e": 11962,
"s": 11882,
"text": "exit command is used to return the succsess/failure of functionality in script."
},
{
"code": null,
"e": 11976,
"s": 11962,
"text": "# cat test.sh"
},
{
"code": null,
"e": 12065,
"s": 11976,
"text": "#!/bin/bashecho \"This is a test.\"# Terminate our shell script with success messageexit 0"
},
{
"code": null,
"e": 12150,
"s": 12065,
"text": "root@ubuntu:/home/ubuntu# ./test.shThis is a test.root@ubuntu:/home/ubuntu# echo $?0"
},
{
"code": null,
"e": 12276,
"s": 12150,
"text": "root@ubuntu:/home/ubuntu# cat test.sh#!/bin/bashecho \"This is a test.\"# Terminate our shell script with failure messageexit 1"
},
{
"code": null,
"e": 12361,
"s": 12276,
"text": "root@ubuntu:/home/ubuntu# ./test.shThis is a test.root@ubuntu:/home/ubuntu# echo $?1"
},
{
"code": null,
"e": 12396,
"s": 12361,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 12424,
"s": 12396,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 12458,
"s": 12424,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 12475,
"s": 12458,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 12508,
"s": 12475,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 12519,
"s": 12508,
"text": " Pradeep D"
},
{
"code": null,
"e": 12554,
"s": 12519,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 12570,
"s": 12554,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 12603,
"s": 12570,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 12615,
"s": 12603,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 12647,
"s": 12615,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 12655,
"s": 12647,
"text": " Uplatz"
},
{
"code": null,
"e": 12662,
"s": 12655,
"text": " Print"
},
{
"code": null,
"e": 12673,
"s": 12662,
"text": " Add Notes"
}
] |
Explaining a BigQuery ML model. How to obtain and interpret... | by Lak Lakshmanan | Towards Data Science
|
BigQuery ML is an easy-to-use way to invoke machine learning models on structured data using just SQL. Although it started with only linear regression, more sophisticated models like Deep Neural Networks and AutoML Tables have been added by connecting BigQuery ML with TensorFlow and Vertex AI as its backend. In other words, although we write SQL, what gets executed is TensorFlow.
BigQuery ML is picking up more features from the Vertex AI backend*. In an earlier post, I showed you hyperparameter tuning. In this post, I’ll show you explainability.
Explainability is a way to understand what a machine learning model is doing. There are two types of explainability. In local explainability, we ask the ML model how it came up with a result for an individual prediction. Why does it say this rental will last 2000 seconds? Why does it suggest that this transaction is fraudulent?
In global explainability, we ask about feature importance. How important is the time-of-day in predicting the duration of a rental? How important is the transaction amount in predicting whether a transaction is fraudulent?
BigQuery ML supports both types of explanations, but in my experience, the local explainability is what end-users want, so I’ll focus on that.
I’ll take the simple model to predict the duration of a bicycle rental that I use throughout my book (BigQuery: The Definitive Guide):
CREATE OR REPLACE MODEL ch09eu.bicycle_linearTRANSFORM( * EXCEPT(start_date), CAST(EXTRACT(dayofweek from start_date) AS STRING) as dayofweek, CAST(EXTRACT(hour from start_date) AS STRING) as hourofday)OPTIONS(model_type='linear_reg', input_label_cols=['duration'])ASSELECT duration , start_station_name , start_date FROM `bigquery-public-data`.london_bicycles.cycle_hire
Explaining a prediction
Instead of calling ML.PREDICT, we call ML.EXPLAIN_PREDICT to get explanations alongside the predictions:
SELECT * FROM ML.EXPLAIN_PREDICT( MODEL `ai-analytics-solutions.ch09eu.bicycle_linear`, ( SELECT 'Park Street, Bankside' AS start_station_name, CURRENT_TIMESTAMP() AS start_date ) )
The result:
The predicted duration is 1929 seconds.
The model starts with a baseline prediction value of 4598 seconds — this is the average prediction value over the entire training dataset. From the second input (the timestamp), the model has pulled out the hour-of-day and day-of-week.
The day-of-week being Wednesday, the model adds 247 seconds to the baseline value. In other words, people rent bicycles for slightly longer than average on Wednesdays.
But then, we are looking at 4am. And that causes the rental duration to be adjusted dramatically downwards, by 2800 seconds!
Finally, Parkside is a station where rentals are typically on the lower side. So, the model applies another correction, this time of 116 seconds.
4598 + 247–2800–116 = 1929
As our second example, let’s take a fraud prediction model:
CREATE OR REPLACE MODEL advdata.ulb_fraud_detection TRANSFORM( * EXCEPT(Amount), SAFE.LOG(Amount) AS log_amount)OPTIONS( INPUT_LABEL_COLS=['class'], AUTO_CLASS_WEIGHTS = TRUE, DATA_SPLIT_METHOD='seq', DATA_SPLIT_COL='Time', MODEL_TYPE='logistic_reg') ASSELECT *FROM `bigquery-public-data.ml_datasets.ulb_fraud_detection`
Again, we use ML.EXPLAIN_PREDICT:
SELECT * FROM ML.EXPLAIN_PREDICT( MODEL `ai-analytics-solutions.advdata.ulb_fraud_detection`, ( SELECT * FROM `bigquery-public-data.ml_datasets.ulb_fraud_detection` WHERE Amount BETWEEN 300 AND 305 LIMIT 1 ) )
The result has a fraud predicted_class of 0 (no fraud) with a probability of 0.946. This corresponds to a logits value of -2.87 (the probability is the sigmoid of the logits).
Unfortunately, this dataset doesn’t tell us what the columns are, but the baseline is -2.70 indicating that there is not much unusual about the data values.
Let’s try a different prediction, this time picking a very high-valued transaction:
SELECT * FROM ML.EXPLAIN_PREDICT( MODEL `ai-analytics-solutions.advdata.ulb_fraud_detection`, ( SELECT * FROM `bigquery-public-data.ml_datasets.ulb_fraud_detection` WHERE Amount > 10000 LIMIT 1 ) )
Now, the model predicts that the transaction is likely to be fraudulent. The logits value is 12.665 whereas the baseline value is -2.7. The key factors behind the dramatically increased probability for this transaction are V4 (which adds 10.67) and V14 (which reduces it by 4). Of course, this would mean more if we knew V4 and V14 were ... but the publicly released financial dataset doesn’t have this information.
As you can see, you can use instance explanations to explain how different inputs caused the resulting value to change. This can help build confidence that the model is working properly.
Enjoy!
* Explainability is implemented in the most efficient way for each model type. In some cases, Vertex AI is called and in other cases, it is done within BigQuery itself. But that’s an implementation detail — regardless of how it’s implemented, you’d call it the same way.
|
[
{
"code": null,
"e": 555,
"s": 172,
"text": "BigQuery ML is an easy-to-use way to invoke machine learning models on structured data using just SQL. Although it started with only linear regression, more sophisticated models like Deep Neural Networks and AutoML Tables have been added by connecting BigQuery ML with TensorFlow and Vertex AI as its backend. In other words, although we write SQL, what gets executed is TensorFlow."
},
{
"code": null,
"e": 724,
"s": 555,
"text": "BigQuery ML is picking up more features from the Vertex AI backend*. In an earlier post, I showed you hyperparameter tuning. In this post, I’ll show you explainability."
},
{
"code": null,
"e": 1054,
"s": 724,
"text": "Explainability is a way to understand what a machine learning model is doing. There are two types of explainability. In local explainability, we ask the ML model how it came up with a result for an individual prediction. Why does it say this rental will last 2000 seconds? Why does it suggest that this transaction is fraudulent?"
},
{
"code": null,
"e": 1277,
"s": 1054,
"text": "In global explainability, we ask about feature importance. How important is the time-of-day in predicting the duration of a rental? How important is the transaction amount in predicting whether a transaction is fraudulent?"
},
{
"code": null,
"e": 1420,
"s": 1277,
"text": "BigQuery ML supports both types of explanations, but in my experience, the local explainability is what end-users want, so I’ll focus on that."
},
{
"code": null,
"e": 1555,
"s": 1420,
"text": "I’ll take the simple model to predict the duration of a bicycle rental that I use throughout my book (BigQuery: The Definitive Guide):"
},
{
"code": null,
"e": 1954,
"s": 1555,
"text": "CREATE OR REPLACE MODEL ch09eu.bicycle_linearTRANSFORM( * EXCEPT(start_date), CAST(EXTRACT(dayofweek from start_date) AS STRING) as dayofweek, CAST(EXTRACT(hour from start_date) AS STRING) as hourofday)OPTIONS(model_type='linear_reg', input_label_cols=['duration'])ASSELECT duration , start_station_name , start_date FROM `bigquery-public-data`.london_bicycles.cycle_hire"
},
{
"code": null,
"e": 1978,
"s": 1954,
"text": "Explaining a prediction"
},
{
"code": null,
"e": 2083,
"s": 1978,
"text": "Instead of calling ML.PREDICT, we call ML.EXPLAIN_PREDICT to get explanations alongside the predictions:"
},
{
"code": null,
"e": 2292,
"s": 2083,
"text": "SELECT * FROM ML.EXPLAIN_PREDICT( MODEL `ai-analytics-solutions.ch09eu.bicycle_linear`, ( SELECT 'Park Street, Bankside' AS start_station_name, CURRENT_TIMESTAMP() AS start_date ) )"
},
{
"code": null,
"e": 2304,
"s": 2292,
"text": "The result:"
},
{
"code": null,
"e": 2344,
"s": 2304,
"text": "The predicted duration is 1929 seconds."
},
{
"code": null,
"e": 2580,
"s": 2344,
"text": "The model starts with a baseline prediction value of 4598 seconds — this is the average prediction value over the entire training dataset. From the second input (the timestamp), the model has pulled out the hour-of-day and day-of-week."
},
{
"code": null,
"e": 2748,
"s": 2580,
"text": "The day-of-week being Wednesday, the model adds 247 seconds to the baseline value. In other words, people rent bicycles for slightly longer than average on Wednesdays."
},
{
"code": null,
"e": 2873,
"s": 2748,
"text": "But then, we are looking at 4am. And that causes the rental duration to be adjusted dramatically downwards, by 2800 seconds!"
},
{
"code": null,
"e": 3019,
"s": 2873,
"text": "Finally, Parkside is a station where rentals are typically on the lower side. So, the model applies another correction, this time of 116 seconds."
},
{
"code": null,
"e": 3046,
"s": 3019,
"text": "4598 + 247–2800–116 = 1929"
},
{
"code": null,
"e": 3106,
"s": 3046,
"text": "As our second example, let’s take a fraud prediction model:"
},
{
"code": null,
"e": 3449,
"s": 3106,
"text": "CREATE OR REPLACE MODEL advdata.ulb_fraud_detection TRANSFORM( * EXCEPT(Amount), SAFE.LOG(Amount) AS log_amount)OPTIONS( INPUT_LABEL_COLS=['class'], AUTO_CLASS_WEIGHTS = TRUE, DATA_SPLIT_METHOD='seq', DATA_SPLIT_COL='Time', MODEL_TYPE='logistic_reg') ASSELECT *FROM `bigquery-public-data.ml_datasets.ulb_fraud_detection`"
},
{
"code": null,
"e": 3483,
"s": 3449,
"text": "Again, we use ML.EXPLAIN_PREDICT:"
},
{
"code": null,
"e": 3734,
"s": 3483,
"text": "SELECT * FROM ML.EXPLAIN_PREDICT( MODEL `ai-analytics-solutions.advdata.ulb_fraud_detection`, ( SELECT * FROM `bigquery-public-data.ml_datasets.ulb_fraud_detection` WHERE Amount BETWEEN 300 AND 305 LIMIT 1 ) )"
},
{
"code": null,
"e": 3910,
"s": 3734,
"text": "The result has a fraud predicted_class of 0 (no fraud) with a probability of 0.946. This corresponds to a logits value of -2.87 (the probability is the sigmoid of the logits)."
},
{
"code": null,
"e": 4067,
"s": 3910,
"text": "Unfortunately, this dataset doesn’t tell us what the columns are, but the baseline is -2.70 indicating that there is not much unusual about the data values."
},
{
"code": null,
"e": 4151,
"s": 4067,
"text": "Let’s try a different prediction, this time picking a very high-valued transaction:"
},
{
"code": null,
"e": 4390,
"s": 4151,
"text": "SELECT * FROM ML.EXPLAIN_PREDICT( MODEL `ai-analytics-solutions.advdata.ulb_fraud_detection`, ( SELECT * FROM `bigquery-public-data.ml_datasets.ulb_fraud_detection` WHERE Amount > 10000 LIMIT 1 ) )"
},
{
"code": null,
"e": 4806,
"s": 4390,
"text": "Now, the model predicts that the transaction is likely to be fraudulent. The logits value is 12.665 whereas the baseline value is -2.7. The key factors behind the dramatically increased probability for this transaction are V4 (which adds 10.67) and V14 (which reduces it by 4). Of course, this would mean more if we knew V4 and V14 were ... but the publicly released financial dataset doesn’t have this information."
},
{
"code": null,
"e": 4993,
"s": 4806,
"text": "As you can see, you can use instance explanations to explain how different inputs caused the resulting value to change. This can help build confidence that the model is working properly."
},
{
"code": null,
"e": 5000,
"s": 4993,
"text": "Enjoy!"
}
] |
Next Greater Even Number | Practice | GeeksforGeeks
|
Given a positive integer X. The task is to find the smallest even number E such that
E > X and all digits in X and E are same.
Note: All the digits in X should be same with digits in E.
Example 1:
Input:
X = 34722641
Output:
34724126
Explanation:
Next greater number with same
digits as in input is 34724126.
Example 2:
Input:
X = 111
Output:
-1
Explanation:
You can't rearrange the digits to get an answer.
Your Task:
You don't need to read input or print anything. Your task is to complete the function leftIndex() which takes a string X as inputs, which is representing the number and returns the required smallest even number. If no such even number exists return -1.
Expected Time Complexity: O(Log(N)! )
Expected Auxiliary Space: O(Log(N))
Constraints:
1 ≤ N ≤ 109
0
ghosh15subhradeep2 weeks ago
class Solution{ public: long long getNextEven(string x) { // Your code goes here int n=x.size(); string s=x; sort(s.begin(),s.end()); do{ next_permutation(x.begin(),x.end()); }while((x[n-1]-'0')%2!=0&&x!=s); if(x==s) return -1; return stoll(x); }};
+2
chessnoobdj4 months ago
C++ STL
long long getNextEven(string X)
{
string E = X;
while(next_permutation(E.begin(), E.end())){
if((E.back()-'0')%2 == 0)
return stoll(E);
}
return -1;
}
0
saket727404 months ago
public long getNextEven(String x)
{
// Your code goes here
while(true){
int n = x.length();
int idx = -1;
for(int i=1;i<n;i++){
if(x.charAt(i) > x.charAt(i-1))
idx = i;
}
if(idx == -1)
return -1l;
int index = idx;
for(int i=idx;i<x.length();i++){
if(x.charAt(i) > x.charAt(idx-1) && x.charAt(i) < x.charAt(idx))
index = i;
}
char arr[] = x.toCharArray();
char temp = arr[idx-1];
arr[idx-1] = arr[index];
arr[index] = temp;
Arrays.sort(arr,idx,n);
if((arr[n-1]-'0')%2 == 0){
String s = String.valueOf(arr);
return Long.parseLong(s);
}
}
}
// can someone tell where to optimise in my java code, showing runtime error.
+3
ameenul88087 months ago
long long getNextEven(string x)
{
// Your code goes here
while(true){
int idx=-1;
//finding the last peak element
for(int i=1;i<x.length();i++){
if(x[i]>x[i-1]) idx=i;
}
//if there is no peak element i.e if the string is in descending order
if(idx==-1){
return (long long)-1;
}
int index = idx;
//we have to swapp the peak element with its prevoius element
//if there exist a number after peak element which is smaller than peak but
//greater than element before peak element
//then we have to swap those two
//so that we can find the immediate greater instead of some random greater no
//swapping lower place digits result in next greater
for(int i=idx;i<x.length();i++){
if(x[i]>x[idx-1] && x[i]<x[idx]){
index = i;
}
}
swap(x[idx-1],x[index]);
//sort the remaining digits in ascending
sort(x.begin()+idx,x.end());
//if its an even number then return
//else find next greater permutation from this number
//if no even numbers are there in array or if no greater even permutation is found
//eventually there will be a permuatation in descending order
//then the loop will returrn -1
if(x[x.length()-1]%2==0){
return stoll(x);
}
}
}
0
anutiger7 months ago
long long cur = stoll(s);
while(next_permutation(s.begin(),s.end())){
int t = s[s.length() - 1] - '0';
if(t % 2 == 0 and stoll(s) > cur)
return stoll(s);
}
return -1;
+3
Shreyansh Kumar Singh9 months ago
Shreyansh Kumar Singh
This doesn't seems to be an easy question!
0
Debojyoti Sinha10 months ago
Debojyoti Sinha
Correct Answer.Correct AnswerExecution Time:0.55
class Solution{ public: long long getNextEven(string x) { long long prevX = stoll(x); next_permutation(x.begin(), x.end()); do { int lastDigit = x[x.size() - 1] - '0'; if(lastDigit % 2 == 0) { long long currX = stoll(x); return currX > prevX ? currX : -1; } } while(next_permutation(x.begin(), x.end())); return -1; }};
0
Nikhil Pratik
This comment was deleted.
0
Sathish Kumar2 years ago
Sathish Kumar
Can anyone say why in the editorial section they provided the answer for the next largest palindrome? Is there any relation for this problem?
0
mayank aggarwal2 years ago
mayank aggarwal
Using next_permutationhttps://ide.geeksforgeeks.o...
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": 365,
"s": 238,
"text": "Given a positive integer X. The task is to find the smallest even number E such that\nE > X and all digits in X and E are same."
},
{
"code": null,
"e": 424,
"s": 365,
"text": "Note: All the digits in X should be same with digits in E."
},
{
"code": null,
"e": 437,
"s": 426,
"text": "Example 1:"
},
{
"code": null,
"e": 550,
"s": 437,
"text": "Input:\nX = 34722641\nOutput:\n34724126\nExplanation:\nNext greater number with same \ndigits as in input is 34724126."
},
{
"code": null,
"e": 562,
"s": 550,
"text": "\nExample 2:"
},
{
"code": null,
"e": 650,
"s": 562,
"text": "Input:\nX = 111\nOutput:\n-1\nExplanation:\nYou can't rearrange the digits to get an answer."
},
{
"code": null,
"e": 1019,
"s": 652,
"text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function leftIndex() which takes a string X as inputs, which is representing the number and returns the required smallest even number. If no such even number exists return -1.\n\nExpected Time Complexity: O(Log(N)! )\nExpected Auxiliary Space: O(Log(N))\n\nConstraints:\n1 ≤ N ≤ 109"
},
{
"code": null,
"e": 1021,
"s": 1019,
"text": "0"
},
{
"code": null,
"e": 1050,
"s": 1021,
"text": "ghosh15subhradeep2 weeks ago"
},
{
"code": null,
"e": 1375,
"s": 1050,
"text": "class Solution{ public: long long getNextEven(string x) { // Your code goes here int n=x.size(); string s=x; sort(s.begin(),s.end()); do{ next_permutation(x.begin(),x.end()); }while((x[n-1]-'0')%2!=0&&x!=s); if(x==s) return -1; return stoll(x); }};"
},
{
"code": null,
"e": 1378,
"s": 1375,
"text": "+2"
},
{
"code": null,
"e": 1402,
"s": 1378,
"text": "chessnoobdj4 months ago"
},
{
"code": null,
"e": 1410,
"s": 1402,
"text": "C++ STL"
},
{
"code": null,
"e": 1597,
"s": 1410,
"text": "long long getNextEven(string X)\n{\n string E = X;\n while(next_permutation(E.begin(), E.end())){\n if((E.back()-'0')%2 == 0)\n return stoll(E);\n }\n return -1;\n}"
},
{
"code": null,
"e": 1599,
"s": 1597,
"text": "0"
},
{
"code": null,
"e": 1622,
"s": 1599,
"text": "saket727404 months ago"
},
{
"code": null,
"e": 2549,
"s": 1622,
"text": "public long getNextEven(String x)\n {\n // Your code goes here\n while(true){\n int n = x.length();\n int idx = -1;\n \n for(int i=1;i<n;i++){\n if(x.charAt(i) > x.charAt(i-1))\n idx = i;\n }\n \n if(idx == -1)\n return -1l;\n \n int index = idx;\n for(int i=idx;i<x.length();i++){\n if(x.charAt(i) > x.charAt(idx-1) && x.charAt(i) < x.charAt(idx))\n index = i;\n }\n \n char arr[] = x.toCharArray();\n \n char temp = arr[idx-1];\n arr[idx-1] = arr[index];\n arr[index] = temp;\n \n Arrays.sort(arr,idx,n);\n \n if((arr[n-1]-'0')%2 == 0){\n String s = String.valueOf(arr);\n return Long.parseLong(s);\n }\n }\n }"
},
{
"code": null,
"e": 2627,
"s": 2549,
"text": "// can someone tell where to optimise in my java code, showing runtime error."
},
{
"code": null,
"e": 2630,
"s": 2627,
"text": "+3"
},
{
"code": null,
"e": 2654,
"s": 2630,
"text": "ameenul88087 months ago"
},
{
"code": null,
"e": 4371,
"s": 2654,
"text": "long long getNextEven(string x)\n {\n // Your code goes here\n while(true){\n int idx=-1;\n \n //finding the last peak element \n \n for(int i=1;i<x.length();i++){\n if(x[i]>x[i-1]) idx=i;\n }\n \n //if there is no peak element i.e if the string is in descending order\n if(idx==-1){\n return (long long)-1;\n }\n \n int index = idx;\n \n //we have to swapp the peak element with its prevoius element \n //if there exist a number after peak element which is smaller than peak but \n //greater than element before peak element \n //then we have to swap those two \n //so that we can find the immediate greater instead of some random greater no\n //swapping lower place digits result in next greater \n \n for(int i=idx;i<x.length();i++){\n if(x[i]>x[idx-1] && x[i]<x[idx]){\n index = i;\n }\n }\n \n swap(x[idx-1],x[index]);\n \n //sort the remaining digits in ascending \n sort(x.begin()+idx,x.end());\n \n \n //if its an even number then return \n //else find next greater permutation from this number \n //if no even numbers are there in array or if no greater even permutation is found\n //eventually there will be a permuatation in descending order \n //then the loop will returrn -1\n if(x[x.length()-1]%2==0){\n return stoll(x);\n }\n }\n }"
},
{
"code": null,
"e": 4373,
"s": 4371,
"text": "0"
},
{
"code": null,
"e": 4394,
"s": 4373,
"text": "anutiger7 months ago"
},
{
"code": null,
"e": 4633,
"s": 4394,
"text": " long long cur = stoll(s);\n while(next_permutation(s.begin(),s.end())){\n int t = s[s.length() - 1] - '0';\n if(t % 2 == 0 and stoll(s) > cur)\n return stoll(s);\n }\n return -1;"
},
{
"code": null,
"e": 4636,
"s": 4633,
"text": "+3"
},
{
"code": null,
"e": 4670,
"s": 4636,
"text": "Shreyansh Kumar Singh9 months ago"
},
{
"code": null,
"e": 4692,
"s": 4670,
"text": "Shreyansh Kumar Singh"
},
{
"code": null,
"e": 4735,
"s": 4692,
"text": "This doesn't seems to be an easy question!"
},
{
"code": null,
"e": 4737,
"s": 4735,
"text": "0"
},
{
"code": null,
"e": 4766,
"s": 4737,
"text": "Debojyoti Sinha10 months ago"
},
{
"code": null,
"e": 4782,
"s": 4766,
"text": "Debojyoti Sinha"
},
{
"code": null,
"e": 4831,
"s": 4782,
"text": "Correct Answer.Correct AnswerExecution Time:0.55"
},
{
"code": null,
"e": 5338,
"s": 4831,
"text": "class Solution{ public: long long getNextEven(string x) { long long prevX = stoll(x); next_permutation(x.begin(), x.end()); do { int lastDigit = x[x.size() - 1] - '0'; if(lastDigit % 2 == 0) { long long currX = stoll(x); return currX > prevX ? currX : -1; } } while(next_permutation(x.begin(), x.end())); return -1; }};"
},
{
"code": null,
"e": 5340,
"s": 5338,
"text": "0"
},
{
"code": null,
"e": 5354,
"s": 5340,
"text": "Nikhil Pratik"
},
{
"code": null,
"e": 5380,
"s": 5354,
"text": "This comment was deleted."
},
{
"code": null,
"e": 5382,
"s": 5380,
"text": "0"
},
{
"code": null,
"e": 5407,
"s": 5382,
"text": "Sathish Kumar2 years ago"
},
{
"code": null,
"e": 5421,
"s": 5407,
"text": "Sathish Kumar"
},
{
"code": null,
"e": 5563,
"s": 5421,
"text": "Can anyone say why in the editorial section they provided the answer for the next largest palindrome? Is there any relation for this problem?"
},
{
"code": null,
"e": 5565,
"s": 5563,
"text": "0"
},
{
"code": null,
"e": 5592,
"s": 5565,
"text": "mayank aggarwal2 years ago"
},
{
"code": null,
"e": 5608,
"s": 5592,
"text": "mayank aggarwal"
},
{
"code": null,
"e": 5661,
"s": 5608,
"text": "Using next_permutationhttps://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 5807,
"s": 5661,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 5843,
"s": 5807,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5853,
"s": 5843,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5863,
"s": 5853,
"text": "\nContest\n"
},
{
"code": null,
"e": 5926,
"s": 5863,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6074,
"s": 5926,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 6282,
"s": 6074,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 6388,
"s": 6282,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Hands On Bayesian Statistics with Python, PyMC3 & ArviZ | by Susan Li | Towards Data Science
|
If you think Bayes’ theorem is counter-intuitive and Bayesian statistics, which builds upon Baye’s theorem, can be very hard to understand. I am with you.
There are countless reasons why we should learn Bayesian statistics, in particular, Bayesian statistics is emerging as a powerful framework to express and understand next-generation deep neural networks.
I believe that for the things we have to learn before we can do them, we learn by doing them. And nothing in life is so hard that we can’t make it easier by the way we take it.
So, this is my way of making it easier: Rather than too much of theories or terminologies at the beginning, let’s focus on the mechanics of Bayesian analysis, in particular, how to do Bayesian analysis and visualization with PyMC3 & ArviZ. Prior to memorizing the endless terminologies, we will code the solutions and visualize the results, and using the terminologies and theories to explain the models along the way.
PyMC3 is a Python library for probabilistic programming with a very simple and intuitive syntax. ArviZ, a Python library that works hand-in-hand with PyMC3 and can help us interpret and visualize posterior distributions.
And we will apply Bayesian methods to a practical problem, to show an end-to-end Bayesian analysis that move from framing the question to building models to eliciting prior probabilities to implementing in Python the final posterior distribution.
Before we start, let’s get some basic intuitions out of the way:
Bayesian models are also known as probabilistic models because they are built using probabilities. And Bayesian’s use probabilities as a tool to quantify uncertainty. Therefore, the answers we get are distributions not point estimates.
Step 1: Establish a belief about the data, including Prior and Likelihood functions.
Step 2, Use the data and probability, in accordance with our belief of the data, to update our model, check that our model agrees with the original data.
Step 3, Update our view of the data based on our model.
Since I am interested in using machine learning for price optimization, I decide to apply Bayesian methods to a Spanish High Speed Rail tickets pricing data set that can be found here. Appreciate The Gurus team for scraping the data set.
from scipy import statsimport arviz as azimport numpy as npimport matplotlib.pyplot as pltimport pymc3 as pmimport seaborn as snsimport pandas as pdfrom theano import sharedfrom sklearn import preprocessingprint('Running on PyMC3 v{}'.format(pm.__version__))data = pd.read_csv('renfe.csv')data.drop('Unnamed: 0', axis = 1, inplace=True)data = data.sample(frac=0.01, random_state=99)data.head(3)
data.isnull().sum()/len(data)
There are 12% of values in price column are missing, I decide to fill them with the mean of the respective fare types. Also fill the other two categorical columns with the most common values.
data['train_class'] = data['train_class'].fillna(data['train_class'].mode().iloc[0])data['fare'] = data['fare'].fillna(data['fare'].mode().iloc[0])data['price'] = data.groupby('fare').transform(lambda x: x.fillna(x.mean()))
az.plot_kde(data['price'].values, rug=True)plt.yticks([0], alpha=0);
The KDE plot of the rail ticket price shows a Gaussian-like distribution, except for about several dozens of data points that are far away from the mean.
Let’s assume that a Gaussian distribution is a proper description of the rail ticket price. Since we do not know the mean or the standard deviation, we must set priors for both of them. Therefore, a reasonable model could be as follows.
We will perform Gaussian inferences on the ticket price data. Here’s some of the modelling choices that go into this.
Model specifications in PyMC3 are wrapped in a with-statement.
Choices of priors:
μ, mean of a population. Normal distribution, very wide. I do not know the possible values of μ, I can set priors reflecting my ignorance. From experience I know that train ticket price can not be lower than 0 or higher than 300, so I set the boundaries of the uniform distribution to be 0 and 300. You may have different experience and set the different boundaries. That is totally fine. And if you have more reliable prior information than I do, please use it!
σ, standard deviation of a population. Can only be positive, therefore use HalfNormal distribution. Again, very wide.
Choices for ticket price likelihood function:
y is an observed variable representing the data that comes from a normal distribution with the parameters μ and σ.
Draw 1000 posterior samples using NUTS sampling.
Using PyMC3, we can write the model as follows:
The y specifies the likelihood. This is the way in which we tell PyMC3 that we want to condition for the unknown on the knows (data).
We plot the gaussian model trace. This runs on a Theano graph under the hood.
az.plot_trace(trace_g);
On the left, we have a KDE plot, — for each parameter value on the x-axis we get a probability on the y-axis that tells us how likely that parameter value is.
On the right, we get the individual sampled values at each step during the sampling. From the trace plot, we can visually get the plausible values from the posterior.
The above plot has one row for each parameter. For this model, the posterior is bi-dimensional, and so the above figure is showing the marginal distributions of each parameter.
There are a couple of things to notice here:
Our sampling chains for the individual parameters (left) seem well converged and stationary (there are no large drifts or other odd patterns).
The maximum posterior estimate of each variable (the peak in the left side distributions) is very close to the true parameters.
We can plot a joint distributions of parameters.
az.plot_joint(trace_g, kind='kde', fill_last=False);
I don’t see any correlation between these two parameters. This means we probably do not have collinearity in the model. This is good.
We can also have a detailed summary of the posterior distribution for each parameter.
az.summary(trace_g)
We can also see the above summary visually by generating a plot with the mean and Highest Posterior Density (HPD) of a distribution, and to interpret and report the results of a Bayesian inference.
az.plot_posterior(trace_g);
Unlike Frequentist inference, in Bayesian inference, we get the entire distribution of the values.
Every time ArviZ computes and reports a HPD, it will use, by default, a value of 94%.
Please note that HPD intervals are not the same as confidence intervals.
Here we can interpret as such that there is 94% probability the belief is between 63.8 euro and 64.4 euro for the mean ticket price.
We can verify the convergence of the chains formally using the Gelman Rubin test. Values close to 1.0 mean convergence.
pm.gelman_rubin(trace_g)
bfmi = pm.bfmi(trace_g)max_gr = max(np.max(gr_stats) for gr_stats in pm.gelman_rubin(trace_g).values())(pm.energyplot(trace_g, legend=False, figsize=(6, 4)).set_title("BFMI = {}\nGelman-Rubin = {}".format(bfmi, max_gr)));
Our model has converged well and the Gelman-Rubin statistic looks fine.
Posterior predictive checks (PPCs) are a great way to validate a model. The idea is to generate data from the model using parameters from draws from the posterior.
Now that we have computed the posterior, we are going to illustrate how to use the simulation results to derive predictions.
The following function will randomly draw 1000 samples of parameters from the trace. Then, for each sample, it will draw 25798 random numbers from a normal distribution specified by the values of μ and σ in that sample.
ppc = pm.sample_posterior_predictive(trace_g, samples=1000, model=model_g)np.asarray(ppc['y']).shape
Now, ppc contains 1000 generated data sets (containing 25798 samples each), each using a different parameter setting from the posterior.
_, ax = plt.subplots(figsize=(10, 5))ax.hist([y.mean() for y in ppc['y']], bins=19, alpha=0.5)ax.axvline(data.price.mean())ax.set(title='Posterior predictive of the mean', xlabel='mean(x)', ylabel='Frequency');
The inferred mean is very close to the actual rail ticket price mean.
We may be interested in how price compare under different fare types. We are going to focus on estimating the effect size, that is, quantifying the difference between two fare categories. To compare fare categories, we are going to use the mean of each fare type. Because we are Bayesian, we will work to obtain a posterior distribution of the differences of means between fare categories.
We create three variables:
The price variable, representing the ticket price.
The idx variable, a categorical dummy variable to encode the fare categories with numbers.
And finally the groups variable, with the number of fare categories (6)
price = data['price'].valuesidx = pd.Categorical(data['fare'], categories=['Flexible', 'Promo', 'Promo +', 'Adulto ida', 'Mesa', 'Individual-Flexible']).codesgroups = len(np.unique(idx))
The model for the group comparison problem is almost the same as the previous model. the only difference is that μ and σ are going to be vectors instead of scalar variables. This means that for the priors, we pass a shape argument and for the likelihood, we properly index the means and sd variables using the idx variable:
With 6 groups (fare categories), its a little hard to plot trace plot for μ and σ for every group. So, we create a summary table:
flat_fares = az.from_pymc3(trace=trace_groups)fares_gaussian = az.summary(flat_fares)fares_gaussian
It is obvious that there are significant differences between groups (i.e. fare categories) on the mean.
To make it clearer, we plot the difference between each fare category without repeating the comparison.
Cohen’s d is an appropriate effect size for the comparison between two means. Cohen’s d introduces the variability of each group by using their standard deviations.
probability of superiority (ps) is defined as the probability that a data point taken at random from one group has a larger value than one taken at random from another group.
Basically, the above plot tells us that none of the above comparison cases where the 94% HPD includes the reference value of zero. This means for all the examples, we can rule out a difference of zero. The average differences range of 6.1 euro to 63.5 euro are large enough that it can justify for customers to purchase tickets according to different fare categories.
We want to build a model to estimate the rail ticket price of each train type, and, at the same time, estimate the price of all the train types. This type of model is known as a hierarchical model or multilevel model.
Encoding the categorical variable.
The idx variable, a categorical dummy variable to encode the train types with numbers.
And finally the groups variable, with the number of train types (16)
The relevant part of the data we will model looks as above. And we are interested in whether different train types affect the ticket price.
The marginal posteriors in the left column are highly informative, “α_μ_tmp” tells us the group mean price levels, “β_μ” tells us that purchasing fare category “Promo +” increases price significantly compare to fare type “Adulto ida”, and purchasing fare category “Promo” increases price significantly compare to fare type “Promo +”, and so on (no mass under zero).
pm.traceplot(hierarchical_trace, var_names=['α_tmp'], coords={'α_tmp_dim_0': range(5)});
Among 16 train types, we may want to look at how 5 train types compare in terms of the ticket price. We can see by looking at the marginals for “α_tmp” that there is quite some difference in prices between train types; the different widths are related to how much confidence we have in each parameter estimate — the more measurements per train type, the higher our confidence will be.
Having uncertainty quantification of some of our estimates is one of the powerful things about Bayesian modelling. We’ve got a Bayesian credible interval for the price of different train types.
az.plot_forest(hierarchical_trace, var_names=['α_tmp', 'β'], combined=True);
Lastly, we may want to compute r squared:
ppc = pm.sample_posterior_predictive(hierarchical_trace, samples=2000, model=hierarchical_model)az.r2_score(data.price.values, ppc['fare_like'])
The objective of this post is to learn, practice and explain Bayesian, not to produce the best possible results from the data set. Otherwise, we would have gone with XGBoost directly.
Jupyter notebook can be found on Github, enjoy the rest of the week.
References:
docs.pymc.io
docs.pymc.io
The book: Bayesian Analysis with Python
|
[
{
"code": null,
"e": 327,
"s": 172,
"text": "If you think Bayes’ theorem is counter-intuitive and Bayesian statistics, which builds upon Baye’s theorem, can be very hard to understand. I am with you."
},
{
"code": null,
"e": 531,
"s": 327,
"text": "There are countless reasons why we should learn Bayesian statistics, in particular, Bayesian statistics is emerging as a powerful framework to express and understand next-generation deep neural networks."
},
{
"code": null,
"e": 708,
"s": 531,
"text": "I believe that for the things we have to learn before we can do them, we learn by doing them. And nothing in life is so hard that we can’t make it easier by the way we take it."
},
{
"code": null,
"e": 1127,
"s": 708,
"text": "So, this is my way of making it easier: Rather than too much of theories or terminologies at the beginning, let’s focus on the mechanics of Bayesian analysis, in particular, how to do Bayesian analysis and visualization with PyMC3 & ArviZ. Prior to memorizing the endless terminologies, we will code the solutions and visualize the results, and using the terminologies and theories to explain the models along the way."
},
{
"code": null,
"e": 1348,
"s": 1127,
"text": "PyMC3 is a Python library for probabilistic programming with a very simple and intuitive syntax. ArviZ, a Python library that works hand-in-hand with PyMC3 and can help us interpret and visualize posterior distributions."
},
{
"code": null,
"e": 1595,
"s": 1348,
"text": "And we will apply Bayesian methods to a practical problem, to show an end-to-end Bayesian analysis that move from framing the question to building models to eliciting prior probabilities to implementing in Python the final posterior distribution."
},
{
"code": null,
"e": 1660,
"s": 1595,
"text": "Before we start, let’s get some basic intuitions out of the way:"
},
{
"code": null,
"e": 1896,
"s": 1660,
"text": "Bayesian models are also known as probabilistic models because they are built using probabilities. And Bayesian’s use probabilities as a tool to quantify uncertainty. Therefore, the answers we get are distributions not point estimates."
},
{
"code": null,
"e": 1981,
"s": 1896,
"text": "Step 1: Establish a belief about the data, including Prior and Likelihood functions."
},
{
"code": null,
"e": 2135,
"s": 1981,
"text": "Step 2, Use the data and probability, in accordance with our belief of the data, to update our model, check that our model agrees with the original data."
},
{
"code": null,
"e": 2191,
"s": 2135,
"text": "Step 3, Update our view of the data based on our model."
},
{
"code": null,
"e": 2429,
"s": 2191,
"text": "Since I am interested in using machine learning for price optimization, I decide to apply Bayesian methods to a Spanish High Speed Rail tickets pricing data set that can be found here. Appreciate The Gurus team for scraping the data set."
},
{
"code": null,
"e": 2824,
"s": 2429,
"text": "from scipy import statsimport arviz as azimport numpy as npimport matplotlib.pyplot as pltimport pymc3 as pmimport seaborn as snsimport pandas as pdfrom theano import sharedfrom sklearn import preprocessingprint('Running on PyMC3 v{}'.format(pm.__version__))data = pd.read_csv('renfe.csv')data.drop('Unnamed: 0', axis = 1, inplace=True)data = data.sample(frac=0.01, random_state=99)data.head(3)"
},
{
"code": null,
"e": 2854,
"s": 2824,
"text": "data.isnull().sum()/len(data)"
},
{
"code": null,
"e": 3046,
"s": 2854,
"text": "There are 12% of values in price column are missing, I decide to fill them with the mean of the respective fare types. Also fill the other two categorical columns with the most common values."
},
{
"code": null,
"e": 3270,
"s": 3046,
"text": "data['train_class'] = data['train_class'].fillna(data['train_class'].mode().iloc[0])data['fare'] = data['fare'].fillna(data['fare'].mode().iloc[0])data['price'] = data.groupby('fare').transform(lambda x: x.fillna(x.mean()))"
},
{
"code": null,
"e": 3339,
"s": 3270,
"text": "az.plot_kde(data['price'].values, rug=True)plt.yticks([0], alpha=0);"
},
{
"code": null,
"e": 3493,
"s": 3339,
"text": "The KDE plot of the rail ticket price shows a Gaussian-like distribution, except for about several dozens of data points that are far away from the mean."
},
{
"code": null,
"e": 3730,
"s": 3493,
"text": "Let’s assume that a Gaussian distribution is a proper description of the rail ticket price. Since we do not know the mean or the standard deviation, we must set priors for both of them. Therefore, a reasonable model could be as follows."
},
{
"code": null,
"e": 3848,
"s": 3730,
"text": "We will perform Gaussian inferences on the ticket price data. Here’s some of the modelling choices that go into this."
},
{
"code": null,
"e": 3911,
"s": 3848,
"text": "Model specifications in PyMC3 are wrapped in a with-statement."
},
{
"code": null,
"e": 3930,
"s": 3911,
"text": "Choices of priors:"
},
{
"code": null,
"e": 4393,
"s": 3930,
"text": "μ, mean of a population. Normal distribution, very wide. I do not know the possible values of μ, I can set priors reflecting my ignorance. From experience I know that train ticket price can not be lower than 0 or higher than 300, so I set the boundaries of the uniform distribution to be 0 and 300. You may have different experience and set the different boundaries. That is totally fine. And if you have more reliable prior information than I do, please use it!"
},
{
"code": null,
"e": 4511,
"s": 4393,
"text": "σ, standard deviation of a population. Can only be positive, therefore use HalfNormal distribution. Again, very wide."
},
{
"code": null,
"e": 4557,
"s": 4511,
"text": "Choices for ticket price likelihood function:"
},
{
"code": null,
"e": 4672,
"s": 4557,
"text": "y is an observed variable representing the data that comes from a normal distribution with the parameters μ and σ."
},
{
"code": null,
"e": 4721,
"s": 4672,
"text": "Draw 1000 posterior samples using NUTS sampling."
},
{
"code": null,
"e": 4769,
"s": 4721,
"text": "Using PyMC3, we can write the model as follows:"
},
{
"code": null,
"e": 4903,
"s": 4769,
"text": "The y specifies the likelihood. This is the way in which we tell PyMC3 that we want to condition for the unknown on the knows (data)."
},
{
"code": null,
"e": 4981,
"s": 4903,
"text": "We plot the gaussian model trace. This runs on a Theano graph under the hood."
},
{
"code": null,
"e": 5005,
"s": 4981,
"text": "az.plot_trace(trace_g);"
},
{
"code": null,
"e": 5164,
"s": 5005,
"text": "On the left, we have a KDE plot, — for each parameter value on the x-axis we get a probability on the y-axis that tells us how likely that parameter value is."
},
{
"code": null,
"e": 5331,
"s": 5164,
"text": "On the right, we get the individual sampled values at each step during the sampling. From the trace plot, we can visually get the plausible values from the posterior."
},
{
"code": null,
"e": 5508,
"s": 5331,
"text": "The above plot has one row for each parameter. For this model, the posterior is bi-dimensional, and so the above figure is showing the marginal distributions of each parameter."
},
{
"code": null,
"e": 5553,
"s": 5508,
"text": "There are a couple of things to notice here:"
},
{
"code": null,
"e": 5696,
"s": 5553,
"text": "Our sampling chains for the individual parameters (left) seem well converged and stationary (there are no large drifts or other odd patterns)."
},
{
"code": null,
"e": 5824,
"s": 5696,
"text": "The maximum posterior estimate of each variable (the peak in the left side distributions) is very close to the true parameters."
},
{
"code": null,
"e": 5873,
"s": 5824,
"text": "We can plot a joint distributions of parameters."
},
{
"code": null,
"e": 5926,
"s": 5873,
"text": "az.plot_joint(trace_g, kind='kde', fill_last=False);"
},
{
"code": null,
"e": 6060,
"s": 5926,
"text": "I don’t see any correlation between these two parameters. This means we probably do not have collinearity in the model. This is good."
},
{
"code": null,
"e": 6146,
"s": 6060,
"text": "We can also have a detailed summary of the posterior distribution for each parameter."
},
{
"code": null,
"e": 6166,
"s": 6146,
"text": "az.summary(trace_g)"
},
{
"code": null,
"e": 6364,
"s": 6166,
"text": "We can also see the above summary visually by generating a plot with the mean and Highest Posterior Density (HPD) of a distribution, and to interpret and report the results of a Bayesian inference."
},
{
"code": null,
"e": 6392,
"s": 6364,
"text": "az.plot_posterior(trace_g);"
},
{
"code": null,
"e": 6491,
"s": 6392,
"text": "Unlike Frequentist inference, in Bayesian inference, we get the entire distribution of the values."
},
{
"code": null,
"e": 6577,
"s": 6491,
"text": "Every time ArviZ computes and reports a HPD, it will use, by default, a value of 94%."
},
{
"code": null,
"e": 6650,
"s": 6577,
"text": "Please note that HPD intervals are not the same as confidence intervals."
},
{
"code": null,
"e": 6783,
"s": 6650,
"text": "Here we can interpret as such that there is 94% probability the belief is between 63.8 euro and 64.4 euro for the mean ticket price."
},
{
"code": null,
"e": 6903,
"s": 6783,
"text": "We can verify the convergence of the chains formally using the Gelman Rubin test. Values close to 1.0 mean convergence."
},
{
"code": null,
"e": 6928,
"s": 6903,
"text": "pm.gelman_rubin(trace_g)"
},
{
"code": null,
"e": 7150,
"s": 6928,
"text": "bfmi = pm.bfmi(trace_g)max_gr = max(np.max(gr_stats) for gr_stats in pm.gelman_rubin(trace_g).values())(pm.energyplot(trace_g, legend=False, figsize=(6, 4)).set_title(\"BFMI = {}\\nGelman-Rubin = {}\".format(bfmi, max_gr)));"
},
{
"code": null,
"e": 7222,
"s": 7150,
"text": "Our model has converged well and the Gelman-Rubin statistic looks fine."
},
{
"code": null,
"e": 7386,
"s": 7222,
"text": "Posterior predictive checks (PPCs) are a great way to validate a model. The idea is to generate data from the model using parameters from draws from the posterior."
},
{
"code": null,
"e": 7511,
"s": 7386,
"text": "Now that we have computed the posterior, we are going to illustrate how to use the simulation results to derive predictions."
},
{
"code": null,
"e": 7731,
"s": 7511,
"text": "The following function will randomly draw 1000 samples of parameters from the trace. Then, for each sample, it will draw 25798 random numbers from a normal distribution specified by the values of μ and σ in that sample."
},
{
"code": null,
"e": 7832,
"s": 7731,
"text": "ppc = pm.sample_posterior_predictive(trace_g, samples=1000, model=model_g)np.asarray(ppc['y']).shape"
},
{
"code": null,
"e": 7969,
"s": 7832,
"text": "Now, ppc contains 1000 generated data sets (containing 25798 samples each), each using a different parameter setting from the posterior."
},
{
"code": null,
"e": 8180,
"s": 7969,
"text": "_, ax = plt.subplots(figsize=(10, 5))ax.hist([y.mean() for y in ppc['y']], bins=19, alpha=0.5)ax.axvline(data.price.mean())ax.set(title='Posterior predictive of the mean', xlabel='mean(x)', ylabel='Frequency');"
},
{
"code": null,
"e": 8250,
"s": 8180,
"text": "The inferred mean is very close to the actual rail ticket price mean."
},
{
"code": null,
"e": 8640,
"s": 8250,
"text": "We may be interested in how price compare under different fare types. We are going to focus on estimating the effect size, that is, quantifying the difference between two fare categories. To compare fare categories, we are going to use the mean of each fare type. Because we are Bayesian, we will work to obtain a posterior distribution of the differences of means between fare categories."
},
{
"code": null,
"e": 8667,
"s": 8640,
"text": "We create three variables:"
},
{
"code": null,
"e": 8718,
"s": 8667,
"text": "The price variable, representing the ticket price."
},
{
"code": null,
"e": 8809,
"s": 8718,
"text": "The idx variable, a categorical dummy variable to encode the fare categories with numbers."
},
{
"code": null,
"e": 8881,
"s": 8809,
"text": "And finally the groups variable, with the number of fare categories (6)"
},
{
"code": null,
"e": 9088,
"s": 8881,
"text": "price = data['price'].valuesidx = pd.Categorical(data['fare'], categories=['Flexible', 'Promo', 'Promo +', 'Adulto ida', 'Mesa', 'Individual-Flexible']).codesgroups = len(np.unique(idx))"
},
{
"code": null,
"e": 9412,
"s": 9088,
"text": "The model for the group comparison problem is almost the same as the previous model. the only difference is that μ and σ are going to be vectors instead of scalar variables. This means that for the priors, we pass a shape argument and for the likelihood, we properly index the means and sd variables using the idx variable:"
},
{
"code": null,
"e": 9542,
"s": 9412,
"text": "With 6 groups (fare categories), its a little hard to plot trace plot for μ and σ for every group. So, we create a summary table:"
},
{
"code": null,
"e": 9642,
"s": 9542,
"text": "flat_fares = az.from_pymc3(trace=trace_groups)fares_gaussian = az.summary(flat_fares)fares_gaussian"
},
{
"code": null,
"e": 9746,
"s": 9642,
"text": "It is obvious that there are significant differences between groups (i.e. fare categories) on the mean."
},
{
"code": null,
"e": 9850,
"s": 9746,
"text": "To make it clearer, we plot the difference between each fare category without repeating the comparison."
},
{
"code": null,
"e": 10015,
"s": 9850,
"text": "Cohen’s d is an appropriate effect size for the comparison between two means. Cohen’s d introduces the variability of each group by using their standard deviations."
},
{
"code": null,
"e": 10190,
"s": 10015,
"text": "probability of superiority (ps) is defined as the probability that a data point taken at random from one group has a larger value than one taken at random from another group."
},
{
"code": null,
"e": 10558,
"s": 10190,
"text": "Basically, the above plot tells us that none of the above comparison cases where the 94% HPD includes the reference value of zero. This means for all the examples, we can rule out a difference of zero. The average differences range of 6.1 euro to 63.5 euro are large enough that it can justify for customers to purchase tickets according to different fare categories."
},
{
"code": null,
"e": 10776,
"s": 10558,
"text": "We want to build a model to estimate the rail ticket price of each train type, and, at the same time, estimate the price of all the train types. This type of model is known as a hierarchical model or multilevel model."
},
{
"code": null,
"e": 10811,
"s": 10776,
"text": "Encoding the categorical variable."
},
{
"code": null,
"e": 10898,
"s": 10811,
"text": "The idx variable, a categorical dummy variable to encode the train types with numbers."
},
{
"code": null,
"e": 10967,
"s": 10898,
"text": "And finally the groups variable, with the number of train types (16)"
},
{
"code": null,
"e": 11107,
"s": 10967,
"text": "The relevant part of the data we will model looks as above. And we are interested in whether different train types affect the ticket price."
},
{
"code": null,
"e": 11473,
"s": 11107,
"text": "The marginal posteriors in the left column are highly informative, “α_μ_tmp” tells us the group mean price levels, “β_μ” tells us that purchasing fare category “Promo +” increases price significantly compare to fare type “Adulto ida”, and purchasing fare category “Promo” increases price significantly compare to fare type “Promo +”, and so on (no mass under zero)."
},
{
"code": null,
"e": 11562,
"s": 11473,
"text": "pm.traceplot(hierarchical_trace, var_names=['α_tmp'], coords={'α_tmp_dim_0': range(5)});"
},
{
"code": null,
"e": 11947,
"s": 11562,
"text": "Among 16 train types, we may want to look at how 5 train types compare in terms of the ticket price. We can see by looking at the marginals for “α_tmp” that there is quite some difference in prices between train types; the different widths are related to how much confidence we have in each parameter estimate — the more measurements per train type, the higher our confidence will be."
},
{
"code": null,
"e": 12141,
"s": 11947,
"text": "Having uncertainty quantification of some of our estimates is one of the powerful things about Bayesian modelling. We’ve got a Bayesian credible interval for the price of different train types."
},
{
"code": null,
"e": 12218,
"s": 12141,
"text": "az.plot_forest(hierarchical_trace, var_names=['α_tmp', 'β'], combined=True);"
},
{
"code": null,
"e": 12260,
"s": 12218,
"text": "Lastly, we may want to compute r squared:"
},
{
"code": null,
"e": 12405,
"s": 12260,
"text": "ppc = pm.sample_posterior_predictive(hierarchical_trace, samples=2000, model=hierarchical_model)az.r2_score(data.price.values, ppc['fare_like'])"
},
{
"code": null,
"e": 12589,
"s": 12405,
"text": "The objective of this post is to learn, practice and explain Bayesian, not to produce the best possible results from the data set. Otherwise, we would have gone with XGBoost directly."
},
{
"code": null,
"e": 12658,
"s": 12589,
"text": "Jupyter notebook can be found on Github, enjoy the rest of the week."
},
{
"code": null,
"e": 12670,
"s": 12658,
"text": "References:"
},
{
"code": null,
"e": 12683,
"s": 12670,
"text": "docs.pymc.io"
},
{
"code": null,
"e": 12696,
"s": 12683,
"text": "docs.pymc.io"
}
] |
Visualize Missing Values with Missingno | by Soner Yıldırım | Towards Data Science
|
Data is the new fuel. However, the raw data is cheap. We need to process it well to take the most value out of it. Complex, well-structured models are as good as the data we feed to them. Thus, data needs to be cleaned and processed thoroughly in order to build robust and accurate models.
One of the issues that we are likely to encounter in raw data is missing values. Consider a case where we have features (columns in a dataframe) on some observations (rows in a dataframe). If we do not have the value in a particular row-column pair, then we have a missing value. We may have only a few missing values or half of an entire column may be missing. In some cases, we can just ignore or drop the rows or columns with missing values. On the other, there might be some cases in which we cannot afford to drop even a single missing value. In any case, handling missing values process starts with exploring them in the dataset.
Pandas provides functions to check the number of missing values in the dataset. Missingno library takes it one step further and provides the distribution of missing values in the dataset by informative visualizations. Using the plots of missingno, we are able to see where the missing values are located in each column and if there is a correlation between missing values of different columns. Before handling missing values, it is very important to explore them in the dataset. Thus, I consider missingno as a highly valuable asset in data cleaning and preprocessing steps.
In this post, we will explore the functionalities of missingno plot by going through some examples.
Let’s first try to explore a dataset about the movies on streaming platforms. The dataset is available here on kaggle.
import numpy as npimport pandas as pddf = pd.read_csv("/content/MoviesOnStreamingPlatforms.csv")print(df.shape)df.head()
The dataset contains 16744 movies and 17 features that describe each movie. Pandas isna returns the missing values and we apply sum function to see the number of missing values in each column.
df.isna().sum()
“Age” and “Rotten Tomatoes” columns have lots of missing values. There are some 6 other columns with number of missing values more than 200. Let’s now use missingno to see if we can get a better intuition about the missing values.
import missingno as msno%matplotlib inline
We imported missingno library. %matplotlib inline command allows to render visualizations within the jupyter notebook. The first tool we use is missing value matrix.
msno.matrix(df)
White lines indicate missing values. “Age” and “Rotten Tomatoes” columns are dominated by while lines as we expect. But, there is an interesting trend in the other columns that have missing values. They mostly have missing values in common rows. If a row has a missing value in “Directors” columns, it is likely to have missing values in “Genres”, “Country”, “Language”, and “Runtime” columns. This is highly valuable information when handling missing values.
Heatmaps are used to visualize correlation matrices which show the correlation of values between different columns. Missingno library also provides heatmaps that show if there is any correlation between missing values in different columns.
msno.heatmap(df)
Positive correlation is proportional to the level of darkness in blue as indicated by the bar on the right side. There are positive correlations at different levels between “Directors”, “Genres”, “Country”, “Language”, and “Runtime” columns. The highest correlation is between “Language” and “Country” which is 0.8. This confirms our intuition from the missing values matrix as these columns have missing values in the same rows.
Another tool of missingno is the bar plot on missing values.
msno.bar(df)
It shows bars that are proportional to the number of non-missing values as well as providing the actual number of non-missing values. We get an idea of how much of each column is missing.
As we mentioned earlier, in order to handle missing values well, we need to understand the structure of the dataset in terms of missing values. It is not enough to just know the number of missing values. The plot of missingno library helps a lot in understanding missing values well. After this step, we can start thinking about how to handle missing values.
The following post provides a detailed guide on how to handle missing values with Pandas. Missingno and pandas can be used together in order to build a robust and efficient strategy to deal with missing values.
towardsdatascience.com
Thank you for reading. Please let me know if you have any missing values.
|
[
{
"code": null,
"e": 461,
"s": 171,
"text": "Data is the new fuel. However, the raw data is cheap. We need to process it well to take the most value out of it. Complex, well-structured models are as good as the data we feed to them. Thus, data needs to be cleaned and processed thoroughly in order to build robust and accurate models."
},
{
"code": null,
"e": 1097,
"s": 461,
"text": "One of the issues that we are likely to encounter in raw data is missing values. Consider a case where we have features (columns in a dataframe) on some observations (rows in a dataframe). If we do not have the value in a particular row-column pair, then we have a missing value. We may have only a few missing values or half of an entire column may be missing. In some cases, we can just ignore or drop the rows or columns with missing values. On the other, there might be some cases in which we cannot afford to drop even a single missing value. In any case, handling missing values process starts with exploring them in the dataset."
},
{
"code": null,
"e": 1672,
"s": 1097,
"text": "Pandas provides functions to check the number of missing values in the dataset. Missingno library takes it one step further and provides the distribution of missing values in the dataset by informative visualizations. Using the plots of missingno, we are able to see where the missing values are located in each column and if there is a correlation between missing values of different columns. Before handling missing values, it is very important to explore them in the dataset. Thus, I consider missingno as a highly valuable asset in data cleaning and preprocessing steps."
},
{
"code": null,
"e": 1772,
"s": 1672,
"text": "In this post, we will explore the functionalities of missingno plot by going through some examples."
},
{
"code": null,
"e": 1891,
"s": 1772,
"text": "Let’s first try to explore a dataset about the movies on streaming platforms. The dataset is available here on kaggle."
},
{
"code": null,
"e": 2012,
"s": 1891,
"text": "import numpy as npimport pandas as pddf = pd.read_csv(\"/content/MoviesOnStreamingPlatforms.csv\")print(df.shape)df.head()"
},
{
"code": null,
"e": 2205,
"s": 2012,
"text": "The dataset contains 16744 movies and 17 features that describe each movie. Pandas isna returns the missing values and we apply sum function to see the number of missing values in each column."
},
{
"code": null,
"e": 2221,
"s": 2205,
"text": "df.isna().sum()"
},
{
"code": null,
"e": 2452,
"s": 2221,
"text": "“Age” and “Rotten Tomatoes” columns have lots of missing values. There are some 6 other columns with number of missing values more than 200. Let’s now use missingno to see if we can get a better intuition about the missing values."
},
{
"code": null,
"e": 2495,
"s": 2452,
"text": "import missingno as msno%matplotlib inline"
},
{
"code": null,
"e": 2661,
"s": 2495,
"text": "We imported missingno library. %matplotlib inline command allows to render visualizations within the jupyter notebook. The first tool we use is missing value matrix."
},
{
"code": null,
"e": 2677,
"s": 2661,
"text": "msno.matrix(df)"
},
{
"code": null,
"e": 3137,
"s": 2677,
"text": "White lines indicate missing values. “Age” and “Rotten Tomatoes” columns are dominated by while lines as we expect. But, there is an interesting trend in the other columns that have missing values. They mostly have missing values in common rows. If a row has a missing value in “Directors” columns, it is likely to have missing values in “Genres”, “Country”, “Language”, and “Runtime” columns. This is highly valuable information when handling missing values."
},
{
"code": null,
"e": 3377,
"s": 3137,
"text": "Heatmaps are used to visualize correlation matrices which show the correlation of values between different columns. Missingno library also provides heatmaps that show if there is any correlation between missing values in different columns."
},
{
"code": null,
"e": 3394,
"s": 3377,
"text": "msno.heatmap(df)"
},
{
"code": null,
"e": 3824,
"s": 3394,
"text": "Positive correlation is proportional to the level of darkness in blue as indicated by the bar on the right side. There are positive correlations at different levels between “Directors”, “Genres”, “Country”, “Language”, and “Runtime” columns. The highest correlation is between “Language” and “Country” which is 0.8. This confirms our intuition from the missing values matrix as these columns have missing values in the same rows."
},
{
"code": null,
"e": 3885,
"s": 3824,
"text": "Another tool of missingno is the bar plot on missing values."
},
{
"code": null,
"e": 3898,
"s": 3885,
"text": "msno.bar(df)"
},
{
"code": null,
"e": 4086,
"s": 3898,
"text": "It shows bars that are proportional to the number of non-missing values as well as providing the actual number of non-missing values. We get an idea of how much of each column is missing."
},
{
"code": null,
"e": 4445,
"s": 4086,
"text": "As we mentioned earlier, in order to handle missing values well, we need to understand the structure of the dataset in terms of missing values. It is not enough to just know the number of missing values. The plot of missingno library helps a lot in understanding missing values well. After this step, we can start thinking about how to handle missing values."
},
{
"code": null,
"e": 4656,
"s": 4445,
"text": "The following post provides a detailed guide on how to handle missing values with Pandas. Missingno and pandas can be used together in order to build a robust and efficient strategy to deal with missing values."
},
{
"code": null,
"e": 4679,
"s": 4656,
"text": "towardsdatascience.com"
}
] |
Pedestrian detection in Aerial Images using RetinaNet | by Priya Dwivedi | Towards Data Science
|
Object Detection in Aerial Images is a challenging and interesting problem. With the cost of drones decreasing, there is a surge in amount of aerial data being generated. It will be very useful to have models that can extract valuable information from aerial data. Retina Net is the most famous single stage detector and in this blog, I want to test it out on an aerial images of pedestrians and bikers from the Stanford Drone Data set. See a sample image below. This is a challenging problem since most objects are only a few pixels wide, some objects are occluded and objects in shade are even harder to detect. I have read several blogs of object detection on aerial images or cars/planes but there are only a few links for pedestrian detection aerially which is especially challenging.
RetinaNet is a single stage detector that uses Feature Pyramid Network (FPN) and Focal loss for training. Feature pyramid network is a structure for multiscale object detection introduced in this paper. It combines low-resolution, semantically strong features with high-resolution, semantically weak features via a top-down pathway and lateral connections. The net result is that it produces feature maps of different scale on multiple levels in the network which helps with both classifier and regressor networks.
The Focal Loss is designed to address the single-stage object detection problems with the imbalance where there is a very large number of possible background classes and just a few foreground classes. This causes training to be inefficient as most locations are easy negatives that contribute no useful signal and the massive amount of these negative examples overwhelm the training and reduces model performance. Focal loss is based on cross entropy loss as shown below and by adjusting the gamma parameter, we can reduce the loss contribution from well classified examples.
In this blog, I want to talk about how to train a RetinaNet model on Keras. I haven’t done enough justice to the theory behind RetinaNet. I used this link to understand the model and would highly recommend it. My first trained model worked quite well in detecting objects aerially as shown in the video below. I have also open sourced the code on my Github link.
Stanford Drone Data is a massive data set of aerial images collected by drone over the Stanford campus. The data set is ideal for object detection and tracking problems. It contains about 60 aerial videos. For each video we have bounding box coordinates for the 6 classes — “Pedestrian”, “Biker”, “Skateboarder”, “Cart”, “Car” and “ Bus”. The data set is very rich in pedestrians and bikers with these 2 classes covering about 85%-95% of the annotations.
To train the Retina Net, I used this implementation in Keras. It is very well documented and works without bugs. Thanks a lot to Fizyr for open sourcing their implementation!
The main steps I followed were:
Selecting a sample of images from the massive stanford drone data set for building the model. I took about 2200 training images with 30,000+ annoations and kept around 1000 images for validation. I have put my image data set on google drive here for anyone interested in skipping this step.
Generating annotations in the format required for Retina Net. Retina Net requires all annotations to be in the format.
path/to/image.jpg,x1,y1,x2,y2,class_name
I converted Stanford annotations in this format and my train and validation annotations are uploaded to my Github.
Adjusting the anchor sizes: The Retina Net has default anchor sizes of 32, 64, 128, 256, 512. These anchor sizes work well for most objects however since we are working on aerial images, some objects may be smaller than 32. This repo provides a handy tool for checking if existing anchors suffice. In the image below annotations in green are covered by existing in anchors and those in red are ignored. As can been seen a good portion of annotations are too small for even the smallest anchor size.
So I adjusted the anchors to drop the biggest one of 512 and instead add a small anchor of size 16. This results in a noticeable improvement as shown below:
With all this we are ready to start training. I kept most other default parameters including the Resnet50 backbone and started training by:
keras_retinanet/bin/train.py --weights snapshots/resnet50_coco_best_v2.1.0.h5 --config config.ini csv train_annotations.csv labels.csv --val-annotations val_annotations.csv
Here weights are the COCO weights that can be used to jump start training. The annotations for training and validation are the input data and config.ini has the updated anchor sizes. All the files are on my Github repo too.
That’s it! The model is slow to train and I trained it overnight. I tested the accuracy of the trained model by checking for mean average precision (MAP) on the test set. As can be seen below the first trained model had a very good MAP of 0.63. The performance is especially good on car and bus classes which are easy to see aerially. The MAP on Biker class is low as this is often confused by pedestrian. I am currently working on further improving accuracy of the Biker class.
Biker: 0.4862Car:0.9363Bus: 0.7892Pedestrian: 0.7059Weighted: 0.6376
Retina Net is a powerful model that uses Feature Pyramid Networks. It is able to detect objects aerially on a very challenging data set where object sizes are quite small. I was able to train a Retina Net with half a day of work. The first version of the trained model has pretty good performance. I am still exploring how to further adapt Retina Net architecture to have a higher accuracy in aerial detection. That will be covered in my next blog.
I hope you liked the blog and try training the model yourself too.
I have my own deep learning consultancy and love to work on interesting problems. I have helped many startups deploy innovative AI based solutions. Check us out at — http://deeplearninganalytics.org/.
You can also see my other writings at: https://medium.com/@priya.dwivedi
If you have a project that we can collaborate on, then please contact me through my website or at info@deeplearninganalytics.org
Retina Net
Stanford Drone Data Set
Retina Net Keras Implementation
|
[
{
"code": null,
"e": 962,
"s": 172,
"text": "Object Detection in Aerial Images is a challenging and interesting problem. With the cost of drones decreasing, there is a surge in amount of aerial data being generated. It will be very useful to have models that can extract valuable information from aerial data. Retina Net is the most famous single stage detector and in this blog, I want to test it out on an aerial images of pedestrians and bikers from the Stanford Drone Data set. See a sample image below. This is a challenging problem since most objects are only a few pixels wide, some objects are occluded and objects in shade are even harder to detect. I have read several blogs of object detection on aerial images or cars/planes but there are only a few links for pedestrian detection aerially which is especially challenging."
},
{
"code": null,
"e": 1477,
"s": 962,
"text": "RetinaNet is a single stage detector that uses Feature Pyramid Network (FPN) and Focal loss for training. Feature pyramid network is a structure for multiscale object detection introduced in this paper. It combines low-resolution, semantically strong features with high-resolution, semantically weak features via a top-down pathway and lateral connections. The net result is that it produces feature maps of different scale on multiple levels in the network which helps with both classifier and regressor networks."
},
{
"code": null,
"e": 2053,
"s": 1477,
"text": "The Focal Loss is designed to address the single-stage object detection problems with the imbalance where there is a very large number of possible background classes and just a few foreground classes. This causes training to be inefficient as most locations are easy negatives that contribute no useful signal and the massive amount of these negative examples overwhelm the training and reduces model performance. Focal loss is based on cross entropy loss as shown below and by adjusting the gamma parameter, we can reduce the loss contribution from well classified examples."
},
{
"code": null,
"e": 2416,
"s": 2053,
"text": "In this blog, I want to talk about how to train a RetinaNet model on Keras. I haven’t done enough justice to the theory behind RetinaNet. I used this link to understand the model and would highly recommend it. My first trained model worked quite well in detecting objects aerially as shown in the video below. I have also open sourced the code on my Github link."
},
{
"code": null,
"e": 2871,
"s": 2416,
"text": "Stanford Drone Data is a massive data set of aerial images collected by drone over the Stanford campus. The data set is ideal for object detection and tracking problems. It contains about 60 aerial videos. For each video we have bounding box coordinates for the 6 classes — “Pedestrian”, “Biker”, “Skateboarder”, “Cart”, “Car” and “ Bus”. The data set is very rich in pedestrians and bikers with these 2 classes covering about 85%-95% of the annotations."
},
{
"code": null,
"e": 3046,
"s": 2871,
"text": "To train the Retina Net, I used this implementation in Keras. It is very well documented and works without bugs. Thanks a lot to Fizyr for open sourcing their implementation!"
},
{
"code": null,
"e": 3078,
"s": 3046,
"text": "The main steps I followed were:"
},
{
"code": null,
"e": 3369,
"s": 3078,
"text": "Selecting a sample of images from the massive stanford drone data set for building the model. I took about 2200 training images with 30,000+ annoations and kept around 1000 images for validation. I have put my image data set on google drive here for anyone interested in skipping this step."
},
{
"code": null,
"e": 3488,
"s": 3369,
"text": "Generating annotations in the format required for Retina Net. Retina Net requires all annotations to be in the format."
},
{
"code": null,
"e": 3529,
"s": 3488,
"text": "path/to/image.jpg,x1,y1,x2,y2,class_name"
},
{
"code": null,
"e": 3644,
"s": 3529,
"text": "I converted Stanford annotations in this format and my train and validation annotations are uploaded to my Github."
},
{
"code": null,
"e": 4143,
"s": 3644,
"text": "Adjusting the anchor sizes: The Retina Net has default anchor sizes of 32, 64, 128, 256, 512. These anchor sizes work well for most objects however since we are working on aerial images, some objects may be smaller than 32. This repo provides a handy tool for checking if existing anchors suffice. In the image below annotations in green are covered by existing in anchors and those in red are ignored. As can been seen a good portion of annotations are too small for even the smallest anchor size."
},
{
"code": null,
"e": 4300,
"s": 4143,
"text": "So I adjusted the anchors to drop the biggest one of 512 and instead add a small anchor of size 16. This results in a noticeable improvement as shown below:"
},
{
"code": null,
"e": 4440,
"s": 4300,
"text": "With all this we are ready to start training. I kept most other default parameters including the Resnet50 backbone and started training by:"
},
{
"code": null,
"e": 4614,
"s": 4440,
"text": "keras_retinanet/bin/train.py --weights snapshots/resnet50_coco_best_v2.1.0.h5 --config config.ini csv train_annotations.csv labels.csv --val-annotations val_annotations.csv"
},
{
"code": null,
"e": 4838,
"s": 4614,
"text": "Here weights are the COCO weights that can be used to jump start training. The annotations for training and validation are the input data and config.ini has the updated anchor sizes. All the files are on my Github repo too."
},
{
"code": null,
"e": 5317,
"s": 4838,
"text": "That’s it! The model is slow to train and I trained it overnight. I tested the accuracy of the trained model by checking for mean average precision (MAP) on the test set. As can be seen below the first trained model had a very good MAP of 0.63. The performance is especially good on car and bus classes which are easy to see aerially. The MAP on Biker class is low as this is often confused by pedestrian. I am currently working on further improving accuracy of the Biker class."
},
{
"code": null,
"e": 5386,
"s": 5317,
"text": "Biker: 0.4862Car:0.9363Bus: 0.7892Pedestrian: 0.7059Weighted: 0.6376"
},
{
"code": null,
"e": 5835,
"s": 5386,
"text": "Retina Net is a powerful model that uses Feature Pyramid Networks. It is able to detect objects aerially on a very challenging data set where object sizes are quite small. I was able to train a Retina Net with half a day of work. The first version of the trained model has pretty good performance. I am still exploring how to further adapt Retina Net architecture to have a higher accuracy in aerial detection. That will be covered in my next blog."
},
{
"code": null,
"e": 5902,
"s": 5835,
"text": "I hope you liked the blog and try training the model yourself too."
},
{
"code": null,
"e": 6103,
"s": 5902,
"text": "I have my own deep learning consultancy and love to work on interesting problems. I have helped many startups deploy innovative AI based solutions. Check us out at — http://deeplearninganalytics.org/."
},
{
"code": null,
"e": 6176,
"s": 6103,
"text": "You can also see my other writings at: https://medium.com/@priya.dwivedi"
},
{
"code": null,
"e": 6305,
"s": 6176,
"text": "If you have a project that we can collaborate on, then please contact me through my website or at info@deeplearninganalytics.org"
},
{
"code": null,
"e": 6316,
"s": 6305,
"text": "Retina Net"
},
{
"code": null,
"e": 6340,
"s": 6316,
"text": "Stanford Drone Data Set"
}
] |
WPF - Popup
|
Popup is a control that displays content on top of existing content, within the bounds of the application window. It is a temporary display on other content. The hierarchical inheritance of Popup class is as follows −
Child
Gets or sets the content to be hosted in the popup.
ChildProperty
Gets the identifier for the Child dependency property.
ChildTransitions
Gets or sets the collection of Transition style elements that apply to child content of a Popup.
ChildTransitionsProperty
Identifies the ChildTransitions dependency property.
HorizontalOffset
Gets or sets the distance between the left side of the application window and the left side of the popup.
HorizontalOffsetProperty
Gets the identifier for the HorizontalOffset dependency property.
IsLightDismissEnabled
Gets or sets a value that determines how the Popup can be dismissed.
IsLightDismissEnabledProperty
Identifies the IsLightDismissEnabled dependency property.
IsOpen
Gets or sets whether the popup is currently displayed on the screen.
IsOpenProperty
Gets the identifier for the IsOpen dependency property.
VerticalOffset
Gets or sets the distance between the top of the application window and the top of the popup.
VerticalOffsetProperty
Gets the identifier for the VerticalOffset dependency property.
Closed
Fires when the IsOpen property is set to false.
Opened
Fires when the IsOpen property is set to true.
Let’s create a new WPF project with the name WPFPopupControl.
Let’s create a new WPF project with the name WPFPopupControl.
When you look at the Toolbox, you will observe that there is no popup control. But you can add a popup control to you app from XAML.
When you look at the Toolbox, you will observe that there is no popup control. But you can add a popup control to you app from XAML.
The following example shows how to use Popup control. Here is the XAML code in which a Popup control and a CheckBox is created and initialized. When the user checks the CheckBox, it displays a Popup.
The following example shows how to use Popup control. Here is the XAML code in which a Popup control and a CheckBox is created and initialized. When the user checks the CheckBox, it displays a Popup.
<Window x:Class = "WPFPopupControl.MainWindow"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local = "clr-namespace:WPFPopupControl"
mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604">
<Grid>
<CheckBox Name = "PCheckBox" Margin = "198,94,208,194" Content = "Checked Me" />
<Popup IsOpen = "{Binding ElementName = PCheckBox,Path = IsChecked}"
PlacementTarget = "{Binding ElementName = PCheckBox}"
AllowsTransparency = "True" PopupAnimation = "Slide">
<Canvas Width = "125" Height = "100" Background = "LightGray">
<Canvas.RenderTransform>
<RotateTransform x:Name = "theTransform" />
</Canvas.RenderTransform>
<TextBlock TextWrapping = "Wrap" Foreground = "Blue"
Text = "Hi, this is Popup" />
</Canvas>
</Popup>
</Grid>
</Window>
When you compile and execute the above code, it will produce the following output. When you tick the checkbox, a popup will appear; and when you uncheck the checkbox, the popup will disappear.
We recommend that you execute the above example code and try the other properties and events of popup class.
31 Lectures
2.5 hours
Anadi Sharma
30 Lectures
2.5 hours
Taurius Litvinavicius
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2238,
"s": 2020,
"text": "Popup is a control that displays content on top of existing content, within the bounds of the application window. It is a temporary display on other content. The hierarchical inheritance of Popup class is as follows −"
},
{
"code": null,
"e": 2244,
"s": 2238,
"text": "Child"
},
{
"code": null,
"e": 2296,
"s": 2244,
"text": "Gets or sets the content to be hosted in the popup."
},
{
"code": null,
"e": 2310,
"s": 2296,
"text": "ChildProperty"
},
{
"code": null,
"e": 2365,
"s": 2310,
"text": "Gets the identifier for the Child dependency property."
},
{
"code": null,
"e": 2382,
"s": 2365,
"text": "ChildTransitions"
},
{
"code": null,
"e": 2479,
"s": 2382,
"text": "Gets or sets the collection of Transition style elements that apply to child content of a Popup."
},
{
"code": null,
"e": 2504,
"s": 2479,
"text": "ChildTransitionsProperty"
},
{
"code": null,
"e": 2557,
"s": 2504,
"text": "Identifies the ChildTransitions dependency property."
},
{
"code": null,
"e": 2574,
"s": 2557,
"text": "HorizontalOffset"
},
{
"code": null,
"e": 2680,
"s": 2574,
"text": "Gets or sets the distance between the left side of the application window and the left side of the popup."
},
{
"code": null,
"e": 2705,
"s": 2680,
"text": "HorizontalOffsetProperty"
},
{
"code": null,
"e": 2771,
"s": 2705,
"text": "Gets the identifier for the HorizontalOffset dependency property."
},
{
"code": null,
"e": 2794,
"s": 2771,
"text": "IsLightDismissEnabled "
},
{
"code": null,
"e": 2863,
"s": 2794,
"text": "Gets or sets a value that determines how the Popup can be dismissed."
},
{
"code": null,
"e": 2893,
"s": 2863,
"text": "IsLightDismissEnabledProperty"
},
{
"code": null,
"e": 2951,
"s": 2893,
"text": "Identifies the IsLightDismissEnabled dependency property."
},
{
"code": null,
"e": 2958,
"s": 2951,
"text": "IsOpen"
},
{
"code": null,
"e": 3027,
"s": 2958,
"text": "Gets or sets whether the popup is currently displayed on the screen."
},
{
"code": null,
"e": 3042,
"s": 3027,
"text": "IsOpenProperty"
},
{
"code": null,
"e": 3098,
"s": 3042,
"text": "Gets the identifier for the IsOpen dependency property."
},
{
"code": null,
"e": 3113,
"s": 3098,
"text": "VerticalOffset"
},
{
"code": null,
"e": 3207,
"s": 3113,
"text": "Gets or sets the distance between the top of the application window and the top of the popup."
},
{
"code": null,
"e": 3230,
"s": 3207,
"text": "VerticalOffsetProperty"
},
{
"code": null,
"e": 3294,
"s": 3230,
"text": "Gets the identifier for the VerticalOffset dependency property."
},
{
"code": null,
"e": 3301,
"s": 3294,
"text": "Closed"
},
{
"code": null,
"e": 3349,
"s": 3301,
"text": "Fires when the IsOpen property is set to false."
},
{
"code": null,
"e": 3356,
"s": 3349,
"text": "Opened"
},
{
"code": null,
"e": 3403,
"s": 3356,
"text": "Fires when the IsOpen property is set to true."
},
{
"code": null,
"e": 3465,
"s": 3403,
"text": "Let’s create a new WPF project with the name WPFPopupControl."
},
{
"code": null,
"e": 3527,
"s": 3465,
"text": "Let’s create a new WPF project with the name WPFPopupControl."
},
{
"code": null,
"e": 3660,
"s": 3527,
"text": "When you look at the Toolbox, you will observe that there is no popup control. But you can add a popup control to you app from XAML."
},
{
"code": null,
"e": 3793,
"s": 3660,
"text": "When you look at the Toolbox, you will observe that there is no popup control. But you can add a popup control to you app from XAML."
},
{
"code": null,
"e": 3993,
"s": 3793,
"text": "The following example shows how to use Popup control. Here is the XAML code in which a Popup control and a CheckBox is created and initialized. When the user checks the CheckBox, it displays a Popup."
},
{
"code": null,
"e": 4193,
"s": 3993,
"text": "The following example shows how to use Popup control. Here is the XAML code in which a Popup control and a CheckBox is created and initialized. When the user checks the CheckBox, it displays a Popup."
},
{
"code": null,
"e": 5337,
"s": 4193,
"text": "<Window x:Class = \"WPFPopupControl.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n xmlns:local = \"clr-namespace:WPFPopupControl\" \n mc:Ignorable = \"d\" Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <Grid> \n <CheckBox Name = \"PCheckBox\" Margin = \"198,94,208,194\" Content = \"Checked Me\" /> \n <Popup IsOpen = \"{Binding ElementName = PCheckBox,Path = IsChecked}\" \n PlacementTarget = \"{Binding ElementName = PCheckBox}\"\n AllowsTransparency = \"True\" PopupAnimation = \"Slide\"> \n\t\t\t\n <Canvas Width = \"125\" Height = \"100\" Background = \"LightGray\"> \n <Canvas.RenderTransform>\n <RotateTransform x:Name = \"theTransform\" /> \n </Canvas.RenderTransform> \n <TextBlock TextWrapping = \"Wrap\" Foreground = \"Blue\"\n Text = \"Hi, this is Popup\" /> \n </Canvas> \n\t\t\t\n </Popup> \n </Grid> \n\t\n</Window>"
},
{
"code": null,
"e": 5530,
"s": 5337,
"text": "When you compile and execute the above code, it will produce the following output. When you tick the checkbox, a popup will appear; and when you uncheck the checkbox, the popup will disappear."
},
{
"code": null,
"e": 5639,
"s": 5530,
"text": "We recommend that you execute the above example code and try the other properties and events of popup class."
},
{
"code": null,
"e": 5674,
"s": 5639,
"text": "\n 31 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5688,
"s": 5674,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5723,
"s": 5688,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5746,
"s": 5723,
"text": " Taurius Litvinavicius"
},
{
"code": null,
"e": 5753,
"s": 5746,
"text": " Print"
},
{
"code": null,
"e": 5764,
"s": 5753,
"text": " Add Notes"
}
] |
ByteBuffer array() method in Java with Examples - GeeksforGeeks
|
03 Jun, 2021
The array() method of java.nio.ByteBuffer class is used to return the byte array that backs the taken buffer.Modifications to this buffer’s content will cause the returned array’s content to be modified, and vice versa.Invoke the hasArray() method before invoking this method in order to ensure that this buffer has an accessible backing array.
Syntax :
public final byte[] array()
Return Value: This method returns the array that backs this buffer.Exception: This method throws the ReadOnlyBufferException, If this buffer is backed by an array but is read-only.
Below are the examples to illustrate the array() method:
Example 1:
Java
// Java program to demonstrate// array() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 4; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the int to byte typecast value in ByteBuffer bb.put((byte)20); bb.put((byte)30); bb.put((byte)40); bb.put((byte)50); // print the ByteBuffer System.out.println("ByteBuffer: " + Arrays.toString(bb.array())); // getting byte array from ByteBuffer // using array() method byte[] arr = bb.array(); // print the byte array System.out.println("\nbyte array: " + Arrays.toString(arr)); } catch (IllegalArgumentException e) { System.out.println("Exception throws: " + e); } }}
ByteBuffer: [20, 30, 40, 50]
byte array: [20, 30, 40, 50]
Example 2:
Java
// Java program to demonstrate// array() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 4; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the int to byte typecast value // in ByteBuffer bb.put((byte)20); bb.put((byte)30); bb.put((byte)40); bb.put((byte)50); bb.rewind(); // print the ByteBuffer System.out.println("Original ByteBuffer: " + Arrays.toString(bb.array())); // Creating a read-only copy of ByteBuffer // using asReadOnlyBuffer() method ByteBuffer bb1 = bb.asReadOnlyBuffer(); bb1.rewind(); // print the ByteBuffer System.out.print("\nReadOnlyBuffer ByteBuffer : "); while (bb1.hasRemaining()) System.out.print(bb1.get() + ", "); // getting byte array from read-only // ByteBuffer using array() method System.out.println("\n\nTrying to get the array" + " from bb1 for editing"); byte[] arr = bb1.array(); } catch (IllegalArgumentException e) { System.out.println("Exception throws: " + e); } catch (ReadOnlyBufferException e) { System.out.println("Exception throws: " + e); } }}
Original ByteBuffer: [20, 30, 40, 50]
ReadOnlyBuffer ByteBuffer : 20, 30, 40, 50,
Trying to get the array from bb1 for editing
Exception throws: java.nio.ReadOnlyBufferException
anikakapoor
Java-ByteBuffer
Java-Functions
Java-NIO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
Set in Java
LinkedList in Java
|
[
{
"code": null,
"e": 24518,
"s": 24490,
"text": "\n03 Jun, 2021"
},
{
"code": null,
"e": 24863,
"s": 24518,
"text": "The array() method of java.nio.ByteBuffer class is used to return the byte array that backs the taken buffer.Modifications to this buffer’s content will cause the returned array’s content to be modified, and vice versa.Invoke the hasArray() method before invoking this method in order to ensure that this buffer has an accessible backing array."
},
{
"code": null,
"e": 24873,
"s": 24863,
"text": "Syntax : "
},
{
"code": null,
"e": 24901,
"s": 24873,
"text": "public final byte[] array()"
},
{
"code": null,
"e": 25082,
"s": 24901,
"text": "Return Value: This method returns the array that backs this buffer.Exception: This method throws the ReadOnlyBufferException, If this buffer is backed by an array but is read-only."
},
{
"code": null,
"e": 25139,
"s": 25082,
"text": "Below are the examples to illustrate the array() method:"
},
{
"code": null,
"e": 25152,
"s": 25139,
"text": "Example 1: "
},
{
"code": null,
"e": 25157,
"s": 25152,
"text": "Java"
},
{
"code": "// Java program to demonstrate// array() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 4; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the int to byte typecast value in ByteBuffer bb.put((byte)20); bb.put((byte)30); bb.put((byte)40); bb.put((byte)50); // print the ByteBuffer System.out.println(\"ByteBuffer: \" + Arrays.toString(bb.array())); // getting byte array from ByteBuffer // using array() method byte[] arr = bb.array(); // print the byte array System.out.println(\"\\nbyte array: \" + Arrays.toString(arr)); } catch (IllegalArgumentException e) { System.out.println(\"Exception throws: \" + e); } }}",
"e": 26300,
"s": 25157,
"text": null
},
{
"code": null,
"e": 26360,
"s": 26300,
"text": "ByteBuffer: [20, 30, 40, 50]\n\nbyte array: [20, 30, 40, 50]"
},
{
"code": null,
"e": 26375,
"s": 26362,
"text": "Example 2: "
},
{
"code": null,
"e": 26380,
"s": 26375,
"text": "Java"
},
{
"code": "// Java program to demonstrate// array() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 4; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the int to byte typecast value // in ByteBuffer bb.put((byte)20); bb.put((byte)30); bb.put((byte)40); bb.put((byte)50); bb.rewind(); // print the ByteBuffer System.out.println(\"Original ByteBuffer: \" + Arrays.toString(bb.array())); // Creating a read-only copy of ByteBuffer // using asReadOnlyBuffer() method ByteBuffer bb1 = bb.asReadOnlyBuffer(); bb1.rewind(); // print the ByteBuffer System.out.print(\"\\nReadOnlyBuffer ByteBuffer : \"); while (bb1.hasRemaining()) System.out.print(bb1.get() + \", \"); // getting byte array from read-only // ByteBuffer using array() method System.out.println(\"\\n\\nTrying to get the array\" + \" from bb1 for editing\"); byte[] arr = bb1.array(); } catch (IllegalArgumentException e) { System.out.println(\"Exception throws: \" + e); } catch (ReadOnlyBufferException e) { System.out.println(\"Exception throws: \" + e); } }}",
"e": 28033,
"s": 26380,
"text": null
},
{
"code": null,
"e": 28215,
"s": 28033,
"text": "Original ByteBuffer: [20, 30, 40, 50]\n\nReadOnlyBuffer ByteBuffer : 20, 30, 40, 50, \n\nTrying to get the array from bb1 for editing\nException throws: java.nio.ReadOnlyBufferException"
},
{
"code": null,
"e": 28229,
"s": 28217,
"text": "anikakapoor"
},
{
"code": null,
"e": 28245,
"s": 28229,
"text": "Java-ByteBuffer"
},
{
"code": null,
"e": 28260,
"s": 28245,
"text": "Java-Functions"
},
{
"code": null,
"e": 28277,
"s": 28260,
"text": "Java-NIO package"
},
{
"code": null,
"e": 28282,
"s": 28277,
"text": "Java"
},
{
"code": null,
"e": 28287,
"s": 28282,
"text": "Java"
},
{
"code": null,
"e": 28385,
"s": 28287,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28417,
"s": 28385,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28447,
"s": 28417,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 28466,
"s": 28447,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28484,
"s": 28466,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 28515,
"s": 28484,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 28547,
"s": 28515,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 28567,
"s": 28547,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 28591,
"s": 28567,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 28603,
"s": 28591,
"text": "Set in Java"
}
] |
Android - Audio Capture
|
Android has a built in microphone through which you can capture audio and store it , or play it in your phone. There are many ways to do that but the most common way is through MediaRecorder class.
Android provides MediaRecorder class to record audio or video. In order to use MediaRecorder class ,you will first create an instance of MediaRecorder class. Its syntax is given below.
MediaRecorder myAudioRecorder = new MediaRecorder();
Now you will set the source , output and encoding format and output file. Their syntax is given below.
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
After specifying the audio source and format and its output file, we can then call the two basic methods prepare and start to start recording the audio.
myAudioRecorder.prepare();
myAudioRecorder.start();
Apart from these methods , there are other methods listed in the MediaRecorder class that allows you more control over audio and video recording.
setAudioSource()
This method specifies the source of audio to be recorded
setVideoSource()
This method specifies the source of video to be recorded
setOutputFormat()
This method specifies the audio format in which audio to be stored
setAudioEncoder()
This method specifies the audio encoder to be used
setOutputFile()
This method configures the path to the file into which the recorded audio is to be stored
stop()
This method stops the recording process.
release()
This method should be called when the recorder instance is needed.
This example provides demonstration of MediaRecorder class to capture audio and then MediaPlayer class to play that recorded audio.
To experiment with this example , you need to run this on an actual device.
Here is the content of src/MainActivity.java
package com.example.sairamkrishna.myapplication;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
import java.util.Random;
import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import android.support.v4.app.ActivityCompat;
import android.content.pm.PackageManager;
import android.support.v4.content.ContextCompat;
public class MainActivity extends AppCompatActivity {
Button buttonStart, buttonStop, buttonPlayLastRecordAudio,
buttonStopPlayingRecording ;
String AudioSavePathInDevice = null;
MediaRecorder mediaRecorder ;
Random random ;
String RandomAudioFileName = "ABCDEFGHIJKLMNOP";
public static final int RequestPermissionCode = 1;
MediaPlayer mediaPlayer ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStart = (Button) findViewById(R.id.button);
buttonStop = (Button) findViewById(R.id.button2);
buttonPlayLastRecordAudio = (Button) findViewById(R.id.button3);
buttonStopPlayingRecording = (Button)findViewById(R.id.button4);
buttonStop.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(false);
buttonStopPlayingRecording.setEnabled(false);
random = new Random();
buttonStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(checkPermission()) {
AudioSavePathInDevice =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
CreateRandomAudioFileName(5) + "AudioRecording.3gp";
MediaRecorderReady();
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buttonStart.setEnabled(false);
buttonStop.setEnabled(true);
Toast.makeText(MainActivity.this, "Recording started",
Toast.LENGTH_LONG).show();
} else {
requestPermission();
}
}
});
buttonStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mediaRecorder.stop();
buttonStop.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
buttonStart.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
Toast.makeText(MainActivity.this, "Recording Completed",
Toast.LENGTH_LONG).show();
}
});
buttonPlayLastRecordAudio.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) throws IllegalArgumentException,
SecurityException, IllegalStateException {
buttonStop.setEnabled(false);
buttonStart.setEnabled(false);
buttonStopPlayingRecording.setEnabled(true);
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(AudioSavePathInDevice);
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
Toast.makeText(MainActivity.this, "Recording Playing",
Toast.LENGTH_LONG).show();
}
});
buttonStopPlayingRecording.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
buttonStop.setEnabled(false);
buttonStart.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
if(mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
MediaRecorderReady();
}
}
});
}
public void MediaRecorderReady(){
mediaRecorder=new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(AudioSavePathInDevice);
}
public String CreateRandomAudioFileName(int string){
StringBuilder stringBuilder = new StringBuilder( string );
int i = 0 ;
while(i < string ) {
stringBuilder.append(RandomAudioFileName.
charAt(random.nextInt(RandomAudioFileName.length())));
i++ ;
}
return stringBuilder.toString();
}
private void requestPermission() {
ActivityCompat.requestPermissions(MainActivity.this, new
String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode);
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length> 0) {
boolean StoragePermission = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
boolean RecordPermission = grantResults[1] ==
PackageManager.PERMISSION_GRANTED;
if (StoragePermission && RecordPermission) {
Toast.makeText(MainActivity.this, "Permission Granted",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this,"Permission
Denied",Toast.LENGTH_LONG).show();
}
}
break;
}
}
public boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(),
WRITE_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(),
RECORD_AUDIO);
return result == PackageManager.PERMISSION_GRANTED &&
result1 == PackageManager.PERMISSION_GRANTED;
}
}
Here is the content of 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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="@drawable/abc"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Record"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_marginTop="37dp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="STOP"
android:id="@+id/button2"
android:layout_alignTop="@+id/button"
android:layout_centerHorizontal="true"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play"
android:id="@+id/button3"
android:layout_alignTop="@+id/button2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="STOP PLAYING RECORDING "
android:id="@+id/button4"
android:layout_below="@+id/button2"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
/>
</RelativeLayout>
Here is the content of Strings.xml
<resources>
<string name="app_name">My Application</string>
</resources>
Here is the content of AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.STORAGE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.sairamkrishna.myapplication.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Before starting your application, Android studio will display following images.
Now by default you will see stop and play button disable. Just press the Record button and your application will start recording the audio. It will display the following screen.
Now just press stop button and it will save the recorded audio to external sd card. When you click on stop button , the following screen would appear.
Now just press the play button and and recorded audio will just start playing on the device. The following message appears when you click on play button.
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3805,
"s": 3607,
"text": "Android has a built in microphone through which you can capture audio and store it , or play it in your phone. There are many ways to do that but the most common way is through MediaRecorder class."
},
{
"code": null,
"e": 3990,
"s": 3805,
"text": "Android provides MediaRecorder class to record audio or video. In order to use MediaRecorder class ,you will first create an instance of MediaRecorder class. Its syntax is given below."
},
{
"code": null,
"e": 4043,
"s": 3990,
"text": "MediaRecorder myAudioRecorder = new MediaRecorder();"
},
{
"code": null,
"e": 4146,
"s": 4043,
"text": "Now you will set the source , output and encoding format and output file. Their syntax is given below."
},
{
"code": null,
"e": 4391,
"s": 4146,
"text": "myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);\nmyAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);\nmyAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);\nmyAudioRecorder.setOutputFile(outputFile);"
},
{
"code": null,
"e": 4544,
"s": 4391,
"text": "After specifying the audio source and format and its output file, we can then call the two basic methods prepare and start to start recording the audio."
},
{
"code": null,
"e": 4596,
"s": 4544,
"text": "myAudioRecorder.prepare();\nmyAudioRecorder.start();"
},
{
"code": null,
"e": 4742,
"s": 4596,
"text": "Apart from these methods , there are other methods listed in the MediaRecorder class that allows you more control over audio and video recording."
},
{
"code": null,
"e": 4759,
"s": 4742,
"text": "setAudioSource()"
},
{
"code": null,
"e": 4816,
"s": 4759,
"text": "This method specifies the source of audio to be recorded"
},
{
"code": null,
"e": 4833,
"s": 4816,
"text": "setVideoSource()"
},
{
"code": null,
"e": 4890,
"s": 4833,
"text": "This method specifies the source of video to be recorded"
},
{
"code": null,
"e": 4908,
"s": 4890,
"text": "setOutputFormat()"
},
{
"code": null,
"e": 4975,
"s": 4908,
"text": "This method specifies the audio format in which audio to be stored"
},
{
"code": null,
"e": 4993,
"s": 4975,
"text": "setAudioEncoder()"
},
{
"code": null,
"e": 5044,
"s": 4993,
"text": "This method specifies the audio encoder to be used"
},
{
"code": null,
"e": 5060,
"s": 5044,
"text": "setOutputFile()"
},
{
"code": null,
"e": 5150,
"s": 5060,
"text": "This method configures the path to the file into which the recorded audio is to be stored"
},
{
"code": null,
"e": 5157,
"s": 5150,
"text": "stop()"
},
{
"code": null,
"e": 5198,
"s": 5157,
"text": "This method stops the recording process."
},
{
"code": null,
"e": 5208,
"s": 5198,
"text": "release()"
},
{
"code": null,
"e": 5275,
"s": 5208,
"text": "This method should be called when the recorder instance is needed."
},
{
"code": null,
"e": 5407,
"s": 5275,
"text": "This example provides demonstration of MediaRecorder class to capture audio and then MediaPlayer class to play that recorded audio."
},
{
"code": null,
"e": 5483,
"s": 5407,
"text": "To experiment with this example , you need to run this on an actual device."
},
{
"code": null,
"e": 5528,
"s": 5483,
"text": "Here is the content of src/MainActivity.java"
},
{
"code": null,
"e": 12178,
"s": 5528,
"text": "package com.example.sairamkrishna.myapplication;\n\nimport android.media.MediaPlayer;\nimport android.media.MediaRecorder;\n\nimport android.os.Environment;\nimport android.support.v7.app.AppCompatActivity;\n\nimport android.os.Bundle;\nimport android.view.View;\n\nimport android.widget.Button;\nimport android.widget.Toast;\n\nimport java.io.IOException;\nimport java.util.Random;\n\nimport static android.Manifest.permission.RECORD_AUDIO;\nimport static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;\n\nimport android.support.v4.app.ActivityCompat;\nimport android.content.pm.PackageManager;\nimport android.support.v4.content.ContextCompat;\n\npublic class MainActivity extends AppCompatActivity {\n\n Button buttonStart, buttonStop, buttonPlayLastRecordAudio, \n buttonStopPlayingRecording ;\n String AudioSavePathInDevice = null;\n MediaRecorder mediaRecorder ;\n Random random ;\n String RandomAudioFileName = \"ABCDEFGHIJKLMNOP\";\n public static final int RequestPermissionCode = 1;\n MediaPlayer mediaPlayer ;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n buttonStart = (Button) findViewById(R.id.button);\n buttonStop = (Button) findViewById(R.id.button2);\n buttonPlayLastRecordAudio = (Button) findViewById(R.id.button3);\n buttonStopPlayingRecording = (Button)findViewById(R.id.button4);\n\n buttonStop.setEnabled(false);\n buttonPlayLastRecordAudio.setEnabled(false);\n buttonStopPlayingRecording.setEnabled(false);\n\n random = new Random();\n\n buttonStart.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n\n if(checkPermission()) {\n\n AudioSavePathInDevice = \n Environment.getExternalStorageDirectory().getAbsolutePath() + \"/\" + \n CreateRandomAudioFileName(5) + \"AudioRecording.3gp\";\n\n MediaRecorderReady();\n\n try {\n mediaRecorder.prepare();\n mediaRecorder.start();\n } catch (IllegalStateException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n } catch (IOException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n\n buttonStart.setEnabled(false);\n buttonStop.setEnabled(true);\n\n Toast.makeText(MainActivity.this, \"Recording started\", \n Toast.LENGTH_LONG).show();\n } else {\n requestPermission();\n }\n\n }\n });\n\n buttonStop.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n mediaRecorder.stop();\n buttonStop.setEnabled(false);\n buttonPlayLastRecordAudio.setEnabled(true);\n buttonStart.setEnabled(true);\n buttonStopPlayingRecording.setEnabled(false);\n\n Toast.makeText(MainActivity.this, \"Recording Completed\", \n Toast.LENGTH_LONG).show();\n }\n });\n\n buttonPlayLastRecordAudio.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) throws IllegalArgumentException, \n SecurityException, IllegalStateException {\n \n buttonStop.setEnabled(false);\n buttonStart.setEnabled(false);\n buttonStopPlayingRecording.setEnabled(true);\n\n mediaPlayer = new MediaPlayer();\n try {\n mediaPlayer.setDataSource(AudioSavePathInDevice);\n mediaPlayer.prepare();\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n mediaPlayer.start();\n Toast.makeText(MainActivity.this, \"Recording Playing\", \n Toast.LENGTH_LONG).show();\n }\n });\n\n buttonStopPlayingRecording.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n buttonStop.setEnabled(false);\n buttonStart.setEnabled(true);\n buttonStopPlayingRecording.setEnabled(false);\n buttonPlayLastRecordAudio.setEnabled(true);\n\n if(mediaPlayer != null){\n mediaPlayer.stop();\n mediaPlayer.release();\n MediaRecorderReady();\n }\n }\n });\n \n }\n\n public void MediaRecorderReady(){\n mediaRecorder=new MediaRecorder();\n mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);\n mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);\n mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);\n mediaRecorder.setOutputFile(AudioSavePathInDevice);\n }\n\n public String CreateRandomAudioFileName(int string){\n StringBuilder stringBuilder = new StringBuilder( string );\n int i = 0 ;\n while(i < string ) { \n stringBuilder.append(RandomAudioFileName.\n charAt(random.nextInt(RandomAudioFileName.length())));\n\n i++ ;\n }\n return stringBuilder.toString();\n }\n\n private void requestPermission() {\n ActivityCompat.requestPermissions(MainActivity.this, new \n String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode);\n }\n\n @Override\n public void onRequestPermissionsResult(int requestCode, \n String permissions[], int[] grantResults) {\n switch (requestCode) {\n case RequestPermissionCode:\n if (grantResults.length> 0) {\n boolean StoragePermission = grantResults[0] == \n PackageManager.PERMISSION_GRANTED;\n boolean RecordPermission = grantResults[1] == \n PackageManager.PERMISSION_GRANTED;\n \n if (StoragePermission && RecordPermission) {\n Toast.makeText(MainActivity.this, \"Permission Granted\", \n Toast.LENGTH_LONG).show();\n } else {\n Toast.makeText(MainActivity.this,\"Permission \n Denied\",Toast.LENGTH_LONG).show();\n }\n }\n break;\n }\n }\n\n public boolean checkPermission() {\n int result = ContextCompat.checkSelfPermission(getApplicationContext(), \n WRITE_EXTERNAL_STORAGE);\n int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), \n RECORD_AUDIO);\n return result == PackageManager.PERMISSION_GRANTED && \n result1 == PackageManager.PERMISSION_GRANTED;\n }\n}"
},
{
"code": null,
"e": 12219,
"s": 12178,
"text": "Here is the content of activity_main.xml"
},
{
"code": null,
"e": 14111,
"s": 12219,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\"\n android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\">\n\n <ImageView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/imageView\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\"\n android:src=\"@drawable/abc\"/>\n\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Record\"\n android:id=\"@+id/button\"\n android:layout_below=\"@+id/imageView\"\n android:layout_alignParentLeft=\"true\"\n android:layout_marginTop=\"37dp\"\n />\n\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"STOP\"\n android:id=\"@+id/button2\"\n android:layout_alignTop=\"@+id/button\"\n android:layout_centerHorizontal=\"true\"\n />\n\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Play\"\n android:id=\"@+id/button3\"\n android:layout_alignTop=\"@+id/button2\"\n android:layout_alignParentRight=\"true\"\n android:layout_alignParentEnd=\"true\"\n />\n\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"STOP PLAYING RECORDING \"\n android:id=\"@+id/button4\"\n android:layout_below=\"@+id/button2\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"10dp\" \n />\n</RelativeLayout>"
},
{
"code": null,
"e": 14146,
"s": 14111,
"text": "Here is the content of Strings.xml"
},
{
"code": null,
"e": 14222,
"s": 14146,
"text": "<resources>\n <string name=\"app_name\">My Application</string>\n</resources>"
},
{
"code": null,
"e": 14265,
"s": 14222,
"text": "Here is the content of AndroidManifest.xml"
},
{
"code": null,
"e": 15220,
"s": 14265,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.sairamkrishna.myapplication\" >\n \n <uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\"/>\n <uses-permission android:name=\"android.permission.RECORD_AUDIO\" /> \n\t<uses-permission android:name=\"android.permission.STORAGE\" /> \n\n <application\n android:allowBackup=\"true\"\n android:icon=\"@drawable/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\"com.example.sairamkrishna.myapplication.MainActivity\"\n android:label=\"@string/app_name\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n \n </activity>\n \n </application>\n</manifest>"
},
{
"code": null,
"e": 15533,
"s": 15220,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Before starting your application, Android studio will display following images."
},
{
"code": null,
"e": 15711,
"s": 15533,
"text": "Now by default you will see stop and play button disable. Just press the Record button and your application will start recording the audio. It will display the following screen."
},
{
"code": null,
"e": 15862,
"s": 15711,
"text": "Now just press stop button and it will save the recorded audio to external sd card. When you click on stop button , the following screen would appear."
},
{
"code": null,
"e": 16016,
"s": 15862,
"text": "Now just press the play button and and recorded audio will just start playing on the device. The following message appears when you click on play button."
},
{
"code": null,
"e": 16051,
"s": 16016,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 16063,
"s": 16051,
"text": " Aditya Dua"
},
{
"code": null,
"e": 16098,
"s": 16063,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 16112,
"s": 16098,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 16144,
"s": 16112,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 16161,
"s": 16144,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 16196,
"s": 16161,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 16213,
"s": 16196,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 16248,
"s": 16213,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 16265,
"s": 16248,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 16298,
"s": 16265,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 16315,
"s": 16298,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 16322,
"s": 16315,
"text": " Print"
},
{
"code": null,
"e": 16333,
"s": 16322,
"text": " Add Notes"
}
] |
Python - Box Plots
|
Boxplots are a measure of how well distributed the data in a data set is. It divides the data set into three quartiles. This graph represents the minimum, maximum, median, first quartile and third quartile in the data set. It is also useful in comparing the distribution of data across data sets by drawing boxplots for each of them.
Boxplot can be drawn calling Series.box.plot() and DataFrame.box.plot(), or DataFrame.boxplot() to visualize the distribution of values within each column.
For instance, here is a boxplot representing five trials of 10 observations of a uniform random variable on [0,1).
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.rand(10, 5), columns=['A', 'B', 'C', 'D', 'E'])
df.plot.box(grid='True')
Its output is as follows −
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": 2863,
"s": 2529,
"text": "Boxplots are a measure of how well distributed the data in a data set is. It divides the data set into three quartiles. This graph represents the minimum, maximum, median, first quartile and third quartile in the data set. It is also useful in comparing the distribution of data across data sets by drawing boxplots for each of them."
},
{
"code": null,
"e": 3019,
"s": 2863,
"text": "Boxplot can be drawn calling Series.box.plot() and DataFrame.box.plot(), or DataFrame.boxplot() to visualize the distribution of values within each column."
},
{
"code": null,
"e": 3134,
"s": 3019,
"text": "For instance, here is a boxplot representing five trials of 10 observations of a uniform random variable on [0,1)."
},
{
"code": null,
"e": 3276,
"s": 3134,
"text": "import pandas as pd\nimport numpy as np\ndf = pd.DataFrame(np.random.rand(10, 5), columns=['A', 'B', 'C', 'D', 'E'])\ndf.plot.box(grid='True')\n "
},
{
"code": null,
"e": 3303,
"s": 3276,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 3340,
"s": 3303,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3356,
"s": 3340,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3389,
"s": 3356,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3408,
"s": 3389,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3443,
"s": 3408,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3465,
"s": 3443,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3499,
"s": 3465,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3527,
"s": 3499,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3562,
"s": 3527,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3576,
"s": 3562,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3609,
"s": 3576,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3626,
"s": 3609,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3633,
"s": 3626,
"text": " Print"
},
{
"code": null,
"e": 3644,
"s": 3633,
"text": " Add Notes"
}
] |
How to resolve CORS issue in C# ASP.NET WebAPI?
|
Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own.
For example, let us consider an application which is having its front end (UI) and back end (Service). Say the front-end is served from https://demodomain-ui.com and the backend is served from from https://demodomain-service.com/api. If an end user tries to access the application, for security reasons the browsers restrict cross-origin HTTP requests initiated from the UI.
So to overcome this, the CORS standard is needed because it allows servers to
specify not just who can access its assets, but also how the assets can be accessed.
Cross-origin requests are made using the standard HTTP request methods. Most
servers will allow GET requests, meaning they will allow resources from external
origins (say, a web page) to read their assets. HTTP requests methods like PATCH,
PUT, or DELETE. The following are the HTTP headers added by the CORS
standard −
Access-Control-Allow-Origin
Access-Control-Allow-Origin
Access-Control-Allow-Credentials
Access-Control-Allow-Credentials
Access-Control-Allow-Headers
Access-Control-Allow-Headers
Access-Control-Allow-Methods
Access-Control-Allow-Methods
Access-Control-Expose-Headers
Access-Control-Expose-Headers
Access-Control-Max-Age
Access-Control-Max-Age
Access-Control-Request-Headers
Access-Control-Request-Headers
Access-Control-Request-Method
Access-Control-Request-Method
Origin
Origin
Enabling CORS at global level −
The first is to install the Microsoft.AspNet.WebApi.Cors from the Nuget package manager.
Then Open the file App_Start/WebApiConfig.cs. Add the following code to the
WebApiConfig.Register method −
Enabling CORS at Controller and Action level −
We can also enable CORS at the controller or action method level like below.
using System.Web.Http;
using System.Web.Http.Cors;
namespace DemoWebApplication.Controllers{
[EnableCors("*", "*", "*")] //Controller level
public class DemoController : ApiController{
[EnableCors("*", "*", "*")] //Action level
public IHttpActionResult Get(int id){
return Ok();
}
}
}
Similarly, we can disable the cors by using [DisableCors] attribute.
|
[
{
"code": null,
"e": 1421,
"s": 1062,
"text": "Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own."
},
{
"code": null,
"e": 1796,
"s": 1421,
"text": "For example, let us consider an application which is having its front end (UI) and back end (Service). Say the front-end is served from https://demodomain-ui.com and the backend is served from from https://demodomain-service.com/api. If an end user tries to access the application, for security reasons the browsers restrict cross-origin HTTP requests initiated from the UI."
},
{
"code": null,
"e": 2279,
"s": 1796,
"text": "So to overcome this, the CORS standard is needed because it allows servers to\nspecify not just who can access its assets, but also how the assets can be accessed.\nCross-origin requests are made using the standard HTTP request methods. Most\nservers will allow GET requests, meaning they will allow resources from external\norigins (say, a web page) to read their assets. HTTP requests methods like PATCH,\nPUT, or DELETE. The following are the HTTP headers added by the CORS\nstandard −"
},
{
"code": null,
"e": 2307,
"s": 2279,
"text": "Access-Control-Allow-Origin"
},
{
"code": null,
"e": 2335,
"s": 2307,
"text": "Access-Control-Allow-Origin"
},
{
"code": null,
"e": 2368,
"s": 2335,
"text": "Access-Control-Allow-Credentials"
},
{
"code": null,
"e": 2401,
"s": 2368,
"text": "Access-Control-Allow-Credentials"
},
{
"code": null,
"e": 2430,
"s": 2401,
"text": "Access-Control-Allow-Headers"
},
{
"code": null,
"e": 2459,
"s": 2430,
"text": "Access-Control-Allow-Headers"
},
{
"code": null,
"e": 2488,
"s": 2459,
"text": "Access-Control-Allow-Methods"
},
{
"code": null,
"e": 2517,
"s": 2488,
"text": "Access-Control-Allow-Methods"
},
{
"code": null,
"e": 2547,
"s": 2517,
"text": "Access-Control-Expose-Headers"
},
{
"code": null,
"e": 2577,
"s": 2547,
"text": "Access-Control-Expose-Headers"
},
{
"code": null,
"e": 2600,
"s": 2577,
"text": "Access-Control-Max-Age"
},
{
"code": null,
"e": 2623,
"s": 2600,
"text": "Access-Control-Max-Age"
},
{
"code": null,
"e": 2654,
"s": 2623,
"text": "Access-Control-Request-Headers"
},
{
"code": null,
"e": 2685,
"s": 2654,
"text": "Access-Control-Request-Headers"
},
{
"code": null,
"e": 2715,
"s": 2685,
"text": "Access-Control-Request-Method"
},
{
"code": null,
"e": 2745,
"s": 2715,
"text": "Access-Control-Request-Method"
},
{
"code": null,
"e": 2752,
"s": 2745,
"text": "Origin"
},
{
"code": null,
"e": 2759,
"s": 2752,
"text": "Origin"
},
{
"code": null,
"e": 2791,
"s": 2759,
"text": "Enabling CORS at global level −"
},
{
"code": null,
"e": 2880,
"s": 2791,
"text": "The first is to install the Microsoft.AspNet.WebApi.Cors from the Nuget package manager."
},
{
"code": null,
"e": 2987,
"s": 2880,
"text": "Then Open the file App_Start/WebApiConfig.cs. Add the following code to the\nWebApiConfig.Register method −"
},
{
"code": null,
"e": 3034,
"s": 2987,
"text": "Enabling CORS at Controller and Action level −"
},
{
"code": null,
"e": 3111,
"s": 3034,
"text": "We can also enable CORS at the controller or action method level like below."
},
{
"code": null,
"e": 3432,
"s": 3111,
"text": "using System.Web.Http;\nusing System.Web.Http.Cors;\nnamespace DemoWebApplication.Controllers{\n [EnableCors(\"*\", \"*\", \"*\")] //Controller level\n public class DemoController : ApiController{\n [EnableCors(\"*\", \"*\", \"*\")] //Action level\n public IHttpActionResult Get(int id){\n return Ok();\n }\n }\n}"
},
{
"code": null,
"e": 3501,
"s": 3432,
"text": "Similarly, we can disable the cors by using [DisableCors] attribute."
}
] |
Java class Keyword
|
❮ Java Keywords
Create a class named "Main":
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Try it Yourself »
The class keyword is used to create a class.
Every line of code that runs in Java must be inside a class. A class should always start with an uppercase first letter, and the name of the java file must match the class name.
A class is like an object constructor. See the example below to see how we can use it to create an object.
Create an object of Main called "myObj" and print the value of x:
public class Main {
int x = 5;
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
Try it Yourself »
Read more about classes and objects in our Java Classes/Objects Tutorial.
❮ Java Keywords
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 18,
"s": 0,
"text": "\n❮ Java Keywords\n"
},
{
"code": null,
"e": 47,
"s": 18,
"text": "Create a class named \"Main\":"
},
{
"code": null,
"e": 156,
"s": 47,
"text": "public class Main {\n public static void main(String[] args) {\n System.out.println(\"Hello World\");\n }\n}\n"
},
{
"code": null,
"e": 176,
"s": 156,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 221,
"s": 176,
"text": "The class keyword is used to create a class."
},
{
"code": null,
"e": 399,
"s": 221,
"text": "Every line of code that runs in Java must be inside a class. A class should always start with an uppercase first letter, and the name of the java file must match the class name."
},
{
"code": null,
"e": 506,
"s": 399,
"text": "A class is like an object constructor. See the example below to see how we can use it to create an object."
},
{
"code": null,
"e": 572,
"s": 506,
"text": "Create an object of Main called \"myObj\" and print the value of x:"
},
{
"code": null,
"e": 718,
"s": 572,
"text": "public class Main {\n int x = 5;\n\n public static void main(String[] args) {\n Main myObj = new Main();\n System.out.println(myObj.x);\n }\n}\n"
},
{
"code": null,
"e": 738,
"s": 718,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 812,
"s": 738,
"text": "Read more about classes and objects in our Java Classes/Objects Tutorial."
},
{
"code": null,
"e": 830,
"s": 812,
"text": "\n❮ Java Keywords\n"
},
{
"code": null,
"e": 863,
"s": 830,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 905,
"s": 863,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1012,
"s": 905,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1031,
"s": 1012,
"text": "help@w3schools.com"
}
] |
How to insert a Python object in MySQL?
|
Assuming that a MySQL database named 'test' is present on the server and a table named employee is also created. Let the table have five fields fname, lname, age, gender, and salary.
Suppose we want to insert a tuple object containing data of a record defined as follows into the Msql database.
t1=('Steven', 'Assange', 21, 'M', 2001)
To establish an interface between MySQL and Python 3, you need to install the PyMySQL module. Then you can set up the connection using the following statements
import PyMySQL
# Open database connection
db = PyMySQL.connect("localhost","root","","test" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
Next step is to set up the insert query using data in the tuple
sql="insert into employee values(%s,%s,%d,%s,%d)" %t1
Now this query is executed using execute() method of the cursor object
cursor.execute(sql)
If you check the contents of the employee table, it will show a new record added to it.
|
[
{
"code": null,
"e": 1245,
"s": 1062,
"text": "Assuming that a MySQL database named 'test' is present on the server and a table named employee is also created. Let the table have five fields fname, lname, age, gender, and salary."
},
{
"code": null,
"e": 1357,
"s": 1245,
"text": "Suppose we want to insert a tuple object containing data of a record defined as follows into the Msql database."
},
{
"code": null,
"e": 1397,
"s": 1357,
"text": "t1=('Steven', 'Assange', 21, 'M', 2001)"
},
{
"code": null,
"e": 1557,
"s": 1397,
"text": "To establish an interface between MySQL and Python 3, you need to install the PyMySQL module. Then you can set up the connection using the following statements"
},
{
"code": null,
"e": 1720,
"s": 1557,
"text": "import PyMySQL\n# Open database connection\ndb = PyMySQL.connect(\"localhost\",\"root\",\"\",\"test\" )\n# prepare a cursor object using cursor() method\ncursor = db.cursor()"
},
{
"code": null,
"e": 1784,
"s": 1720,
"text": "Next step is to set up the insert query using data in the tuple"
},
{
"code": null,
"e": 1838,
"s": 1784,
"text": "sql=\"insert into employee values(%s,%s,%d,%s,%d)\" %t1"
},
{
"code": null,
"e": 1909,
"s": 1838,
"text": "Now this query is executed using execute() method of the cursor object"
},
{
"code": null,
"e": 1929,
"s": 1909,
"text": "cursor.execute(sql)"
},
{
"code": null,
"e": 2017,
"s": 1929,
"text": "If you check the contents of the employee table, it will show a new record added to it."
}
] |
SAS - Scatter Plots
|
A scatterplot is a type of graph which uses values from two variables plotted in a Cartesian plane. It is usually used to find out the relationship between two variables. In SAS we use PROC SGSCATTER to create scatterplots.
Please note that we create the data set named CARS1 in the first example and use the same data set for all the subsequent data sets. This data set remains in the work library till the end of the SAS session.
The basic syntax to create a scatter-plot in SAS is −
PROC sgscatter DATA = DATASET;
PLOT VARIABLE_1 * VARIABLE_2
/ datalabel = VARIABLE group = VARIABLE;
RUN;
Following is the description of parameters used −
DATASET is the name of data set.
DATASET is the name of data set.
VARIABLE is the variable used from the dataset.
VARIABLE is the variable used from the dataset.
In a simple scatterplot we choose two variables form the dataset and group them with respect a third variable. We can also label the data. The result shows how the two variables are scattered in the Cartesian plane.
PROC SQL;
create table CARS1 as
SELECT make, model, type, invoice, horsepower, length, weight
FROM
SASHELP.CARS
WHERE make in ('Audi','BMW')
;
RUN;
TITLE 'Scatterplot - Two Variables';
PROC sgscatter DATA = CARS1;
PLOT horsepower*Invoice
/ datalabel = make group = type grid;
title 'Horsepower vs. Invoice for car makers by types';
RUN;
When we execute the above code, we get the following output −
we can use an estimation parameter to predict the strength of correlation between by drawing an ellipse around the values. We use the additional options in the procedure to draw the ellipse as shown below.
proc sgscatter data = cars1;
compare y = Invoice x = (horsepower length)
/ group = type ellipse =(alpha = 0.05 type = predicted);
title
'Average Invoice vs. horsepower for cars by length';
title2
'-- with 95% prediction ellipse --'
;
format
Invoice dollar6.0;
run;
When we execute the above code, we get the following output −
We can also have a scatterplot involving more than two variables by grouping them into pairs. In the example below we consider three variables and draw a scatter plot matrix. We get 3 pairs of resulting matrix.
PROC sgscatter DATA = CARS1;
matrix horsepower invoice length
/ group = type;
title 'Horsepower vs. Invoice vs. Length for car makers by types';
RUN;
When we execute the above code, we get the following output −
50 Lectures
5.5 hours
Code And Create
124 Lectures
30 hours
Juan Galvan
162 Lectures
31.5 hours
Yossef Ayman Zedan
35 Lectures
2.5 hours
Ermin Dedic
167 Lectures
45.5 hours
Muslim Helalee
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2807,
"s": 2583,
"text": "A scatterplot is a type of graph which uses values from two variables plotted in a Cartesian plane. It is usually used to find out the relationship between two variables. In SAS we use PROC SGSCATTER to create scatterplots."
},
{
"code": null,
"e": 3015,
"s": 2807,
"text": "Please note that we create the data set named CARS1 in the first example and use the same data set for all the subsequent data sets. This data set remains in the work library till the end of the SAS session."
},
{
"code": null,
"e": 3069,
"s": 3015,
"text": "The basic syntax to create a scatter-plot in SAS is −"
},
{
"code": null,
"e": 3183,
"s": 3069,
"text": "PROC sgscatter DATA = DATASET;\n PLOT VARIABLE_1 * VARIABLE_2\n / datalabel = VARIABLE group = VARIABLE;\nRUN;\n"
},
{
"code": null,
"e": 3233,
"s": 3183,
"text": "Following is the description of parameters used −"
},
{
"code": null,
"e": 3266,
"s": 3233,
"text": "DATASET is the name of data set."
},
{
"code": null,
"e": 3299,
"s": 3266,
"text": "DATASET is the name of data set."
},
{
"code": null,
"e": 3347,
"s": 3299,
"text": "VARIABLE is the variable used from the dataset."
},
{
"code": null,
"e": 3395,
"s": 3347,
"text": "VARIABLE is the variable used from the dataset."
},
{
"code": null,
"e": 3611,
"s": 3395,
"text": "In a simple scatterplot we choose two variables form the dataset and group them with respect a third variable. We can also label the data. The result shows how the two variables are scattered in the Cartesian plane."
},
{
"code": null,
"e": 3962,
"s": 3611,
"text": "PROC SQL;\ncreate table CARS1 as\nSELECT make, model, type, invoice, horsepower, length, weight\nFROM \nSASHELP.CARS\nWHERE make in ('Audi','BMW')\n;\nRUN;\n\nTITLE 'Scatterplot - Two Variables';\nPROC sgscatter DATA = CARS1;\n PLOT horsepower*Invoice \n / datalabel = make group = type grid;\n title 'Horsepower vs. Invoice for car makers by types';\nRUN; "
},
{
"code": null,
"e": 4024,
"s": 3962,
"text": "When we execute the above code, we get the following output −"
},
{
"code": null,
"e": 4230,
"s": 4024,
"text": "we can use an estimation parameter to predict the strength of correlation between by drawing an ellipse around the values. We use the additional options in the procedure to draw the ellipse as shown below."
},
{
"code": null,
"e": 4513,
"s": 4230,
"text": "proc sgscatter data = cars1; \ncompare y = Invoice x = (horsepower length) \n / group = type ellipse =(alpha = 0.05 type = predicted); \ntitle\n'Average Invoice vs. horsepower for cars by length'; \ntitle2\n'-- with 95% prediction ellipse --'\n; \nformat\nInvoice dollar6.0;\nrun;\n"
},
{
"code": null,
"e": 4575,
"s": 4513,
"text": "When we execute the above code, we get the following output −"
},
{
"code": null,
"e": 4786,
"s": 4575,
"text": "We can also have a scatterplot involving more than two variables by grouping them into pairs. In the example below we consider three variables and draw a scatter plot matrix. We get 3 pairs of resulting matrix."
},
{
"code": null,
"e": 4949,
"s": 4786,
"text": "PROC sgscatter DATA = CARS1;\n matrix horsepower invoice length\n / group = type;\n\n title 'Horsepower vs. Invoice vs. Length for car makers by types';\nRUN; \n"
},
{
"code": null,
"e": 5011,
"s": 4949,
"text": "When we execute the above code, we get the following output −"
},
{
"code": null,
"e": 5046,
"s": 5011,
"text": "\n 50 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5063,
"s": 5046,
"text": " Code And Create"
},
{
"code": null,
"e": 5098,
"s": 5063,
"text": "\n 124 Lectures \n 30 hours \n"
},
{
"code": null,
"e": 5111,
"s": 5098,
"text": " Juan Galvan"
},
{
"code": null,
"e": 5148,
"s": 5111,
"text": "\n 162 Lectures \n 31.5 hours \n"
},
{
"code": null,
"e": 5168,
"s": 5148,
"text": " Yossef Ayman Zedan"
},
{
"code": null,
"e": 5203,
"s": 5168,
"text": "\n 35 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5216,
"s": 5203,
"text": " Ermin Dedic"
},
{
"code": null,
"e": 5253,
"s": 5216,
"text": "\n 167 Lectures \n 45.5 hours \n"
},
{
"code": null,
"e": 5269,
"s": 5253,
"text": " Muslim Helalee"
},
{
"code": null,
"e": 5276,
"s": 5269,
"text": " Print"
},
{
"code": null,
"e": 5287,
"s": 5276,
"text": " Add Notes"
}
] |
Python - Check if two lists have any element in common
|
During manipulating data using python lists, we come across a situation where we need to know if two lists are entirely different from each other or they have any element in common. This can be found out by comparing the elements in the two lists with the below approaches decribed.
In a for loop we use the in clause to check in an element is present in the list or not. We will stretch this logic to compare the elements of the lists by choosing an element from first list and checking its presence in the second list. So we will have nested for loop to do this check.
Live Demo
#Declaring lists
list1=['a',4,'%','d','e']
list2=[3,'f',6,'d','e',3]
list3=[12,3,12,15,14,15,17]
list4=[12,42,41,12,41,12]
# In[23]:
#Defining function to check for common elements in two lists
def commonelems(x,y):
common=0
for value in x:
if value in y:
common=1
if(not common):
return ("The lists have no common elements")
else:
return ("The lists have common elements")
# In[24]:
#Checking two lists for common elements
print("Comparing list1 and list2:")
print(commonelems(list1,list2))
print("\n")
print("Comparing list1 and list3:")
print(commonelems(list1,list3))
print("\n")
print("Comparing list3 and list4:")
print(commonelems(list3,list4))
Running the above code gives us the following result
Comparing list1 and list2:
The lists have common elements
Comparing list1 and list3:
The lists have no common elements
Comparing list3 and list4:
The lists have common elements
Another approach to find, if two lists have common elements is to use sets. The sets have unordered collection of unique elements. So we convert the lists into sets and then create a new set by combining the given sets. If they have some common elements then the new set will not be empty.
Live Demo
list1=['a',4,'%','d','e']
list2=[3,'f',6,'d','e',3]
# Defining function two check common elements in two lists by converting to sets
def commonelem_set(z, x):
one = set(z)
two = set(x)
if (one & two):
return ("There are common elements in both lists:", one & two)
else:
return ("There are no common elements")
# Checking common elements in two lists for
z = commonelem_set(list1, list2)
print(z)
def commonelem_any(a, b):
out = any(check in a for check in b)
# Checking condition
if out:
return ("The lists have common elements.")
else:
return ("The lists do not have common elements.")
print(commonelem_any(list1, list2))
Running the above code gives us the following result
('There are common elements in both lists:', {'d', 'e'})
The lists have common elements.
|
[
{
"code": null,
"e": 1345,
"s": 1062,
"text": "During manipulating data using python lists, we come across a situation where we need to know if two lists are entirely different from each other or they have any element in common. This can be found out by comparing the elements in the two lists with the below approaches decribed."
},
{
"code": null,
"e": 1633,
"s": 1345,
"text": "In a for loop we use the in clause to check in an element is present in the list or not. We will stretch this logic to compare the elements of the lists by choosing an element from first list and checking its presence in the second list. So we will have nested for loop to do this check."
},
{
"code": null,
"e": 1644,
"s": 1633,
"text": " Live Demo"
},
{
"code": null,
"e": 2336,
"s": 1644,
"text": "#Declaring lists\nlist1=['a',4,'%','d','e']\nlist2=[3,'f',6,'d','e',3]\nlist3=[12,3,12,15,14,15,17]\nlist4=[12,42,41,12,41,12]\n\n# In[23]:\n\n#Defining function to check for common elements in two lists\ndef commonelems(x,y):\n common=0\n for value in x:\n if value in y:\n common=1\n if(not common):\n return (\"The lists have no common elements\")\n else:\n return (\"The lists have common elements\")\n\n# In[24]:\n\n#Checking two lists for common elements\nprint(\"Comparing list1 and list2:\")\nprint(commonelems(list1,list2))\nprint(\"\\n\")\nprint(\"Comparing list1 and list3:\")\nprint(commonelems(list1,list3))\nprint(\"\\n\")\nprint(\"Comparing list3 and list4:\")\nprint(commonelems(list3,list4))"
},
{
"code": null,
"e": 2389,
"s": 2336,
"text": "Running the above code gives us the following result"
},
{
"code": null,
"e": 2566,
"s": 2389,
"text": "Comparing list1 and list2:\nThe lists have common elements\nComparing list1 and list3:\nThe lists have no common elements\nComparing list3 and list4:\nThe lists have common elements"
},
{
"code": null,
"e": 2856,
"s": 2566,
"text": "Another approach to find, if two lists have common elements is to use sets. The sets have unordered collection of unique elements. So we convert the lists into sets and then create a new set by combining the given sets. If they have some common elements then the new set will not be empty."
},
{
"code": null,
"e": 2867,
"s": 2856,
"text": " Live Demo"
},
{
"code": null,
"e": 3531,
"s": 2867,
"text": "list1=['a',4,'%','d','e']\nlist2=[3,'f',6,'d','e',3]\n\n# Defining function two check common elements in two lists by converting to sets\ndef commonelem_set(z, x):\n one = set(z)\n two = set(x)\n if (one & two):\n return (\"There are common elements in both lists:\", one & two)\n else:\n return (\"There are no common elements\")\n\n# Checking common elements in two lists for\nz = commonelem_set(list1, list2)\nprint(z)\n\ndef commonelem_any(a, b):\nout = any(check in a for check in b)\n\n# Checking condition\n if out:\n return (\"The lists have common elements.\")\n else:\n return (\"The lists do not have common elements.\")\n\nprint(commonelem_any(list1, list2))"
},
{
"code": null,
"e": 3584,
"s": 3531,
"text": "Running the above code gives us the following result"
},
{
"code": null,
"e": 3673,
"s": 3584,
"text": "('There are common elements in both lists:', {'d', 'e'})\nThe lists have common elements."
}
] |
Building a Collaborative Filtering Recommender System with ClickStream Data | by Susan Li | Towards Data Science
|
Recommender systems are everywhere, helping you find everything from books to romantic dates, hotels to restaurants.
There are all kinds of recommender systems for all sorts of situations, depends on your needs and available data.
Explicit vs Implicit
Let’s face it, explicit feedback is hard to collect as they require additional input from the users. The users give explicit feedback only when they choose to do so. As a result, most of the time, people don’t provide ratings at all (I myself totally guilty of this on Amazon!). Therefore, the amount of explicit data collected are extremely scarce.
On the other hand, implicit data is easy to collect in large quantities without any effort from the users. The goal is to convert user behavior into user preferences which indirectly reflect opinion through observing user behavior. For example, a user that bookmarked many articles by the same author probably likes that author.
Our goal today is to develop a recommender system with implicit data collection which is clickstream data, in our case.
It is very hard to find public available data for this project. I am using data from Articles sharing and reading from CI&T DeskDrop. Deskdrop is an internal communications platform that allows companies employees to share relevant articles with their peers, and collaborate around them.
The data contains about 73k users interactions on more than 3k public articles shared in the platform, more importantly, it contains rich implicit feedback, different interaction types were logged, making it possible to infer the user’s level of interest in the articles.
And we will be using Implicit Library, a Fast Python Collaborative Filtering for Implicit Datasets, for our matrix factorization.
Remove columns that we do not need.
Remove eventType == 'CONTENT REMOVED' from articles_df.
Merge interactions_df with articles_df.
This is the data set that will get us to start:
This tells us what event type each person has with each content. There are many duplicated records and we will remove them shortly.
df['eventType'].value_counts()
The eventType values are:
VIEW: The user has opened the article. A page view in a content site can mean many things. It can mean that the user is interested, or maybe user is just lost or clicking randomly.
LIKE: The user has liked the article.
BOOKMARK: The user has bookmarked the article for easy return in the future. This is a strong indication that the user finds something of interest.
COMMENT CREATED: The user left a comment on the article.
FOLLOW: The user chose to be notified on any new comment about the article.
We are going to associate each eventType with a weight or strength. It is reasonable to assume that for example, a bookmark on an article indicates a higher interest of the user on that article than a like.
event_type_strength = { 'VIEW': 1.0, 'LIKE': 2.0, 'BOOKMARK': 3.0, 'FOLLOW': 4.0, 'COMMENT CREATED': 5.0, }df['eventStrength'] = df['eventType'].apply(lambda x: event_type_strength[x])
Drop duplicated records.
Group eventStrength together with person and content.
df = df.drop_duplicates()grouped_df = df.groupby(['personId', 'contentId', 'title']).sum().reset_index()grouped_df.sample(10)
We get the final result of grouped eventStrength.
Instead of representing an explicit rating, the eventStrength can represent a “confidence” in terms of how strong the interaction was. Articles with a larger number of eventStrength by a person can carry more weight in our ratings matrix of eventStrength.
To get around “negative integer” warning, I will have to create numeric person_id and content_id columns.
Create two matrices, one for fitting the model (content-person) and one for recommendations (person-content).
Initialize the Alternating Least Squares (ALS) recommendation model.
Fit the model using the sparse content-person matrix.
We set the type of our matrix to double for the ALS function to run properly.
We are going to find the top 10 most similar articles for content_id = 450, titled “Google’s fair use victory is good for open source”, this article seems talk about Google and open source.
Get the person and content vectors from our trained model.
Calculate the vector norms.
Calculate the similarity score.
Get the top 10 contents.
Create a list of content-score tuples of most similar articles with this article.
The 1st article is itself. The other 9 articles are about Google, or opensource software, or cloud, or AI, or the other tech companies. I am sure you will agree with me that they are all some what similar with the first one!
The following function will return the top 10 recommendations chosen based on the person / content vectors for contents never interacted with for any given person.
Get the interactions score from the sparse person content matrix.
Add 1 to everything, so that articles with no interaction yet become equal to 1.
Make articles already interacted zero.
Get dot product of person vector and all content vectors.
Scale this recommendation vector between 0 and 1.
Content already interacted have their recommendation multiplied by zero.
Sort the indices of the content into order of best recommendations.
Start empty list to store titles and scores.
Append titles and scores to the list.
Get the trained person and content vectors. We convert them to csr matrices.
Create recommendations for person with id 50.
Here we have top 10 recommendations for person_id = 50. Do they make sense? Let’s get top 10 articles this person has interacted with.
grouped_df.loc[grouped_df['person_id'] == 50].sort_values(by=['eventStrength'], ascending=False)[['title', 'person_id', 'eventStrength']].head(10)
Apparently, this person is interested in articles on open source CMS such as Drupal, she also reads software development and business related articles, namely “Google”, “Slack” or “Johnson Johnson”.
The articles we recommended to her includes Drupal for digital experience, information technology vs. humanity, software development, and business articles about Google.
Pretty impressive! Let’s try one more.
We recommended the following articles to person_id = 1:
person_id = 1recommendations = recommend(person_id, sparse_person_content, person_vecs, content_vecs)print(recommendations)
The following are the articles person_id = 1 has interacted with:
grouped_df.loc[grouped_df['person_id'] == 1].sort_values(by=['eventStrength'], ascending=False)[['title', 'eventStrength', 'person_id']]
Apparently, this person has only interacted with 5 articles and she seems to have very limited interest. The articles she interacted was about learning Japanese language and / or android development.
The articles we recommended to her includes learning Japanese language, android development and user interface design. Cool!
The above spot checks look all good. But the best evaluation metrics for a recommender system is how much the system adds value to the end user and/or business, whether the system increase page views, likes, bookmarks, follows and comments. We will want to do some kind online A/B testing to evaluate these metrics.
However, before we push the recommender system online, there are other common metrics for evaluating the performance of a recommender in isolation. By following this tutorial, we were able to calculate the AUC for each person in our training set that had at least one article masked. And AUC for the most popular articles for the persons to compare.
Jupyter notebook can be found on Github. Happy Easter!
|
[
{
"code": null,
"e": 289,
"s": 172,
"text": "Recommender systems are everywhere, helping you find everything from books to romantic dates, hotels to restaurants."
},
{
"code": null,
"e": 403,
"s": 289,
"text": "There are all kinds of recommender systems for all sorts of situations, depends on your needs and available data."
},
{
"code": null,
"e": 424,
"s": 403,
"text": "Explicit vs Implicit"
},
{
"code": null,
"e": 774,
"s": 424,
"text": "Let’s face it, explicit feedback is hard to collect as they require additional input from the users. The users give explicit feedback only when they choose to do so. As a result, most of the time, people don’t provide ratings at all (I myself totally guilty of this on Amazon!). Therefore, the amount of explicit data collected are extremely scarce."
},
{
"code": null,
"e": 1103,
"s": 774,
"text": "On the other hand, implicit data is easy to collect in large quantities without any effort from the users. The goal is to convert user behavior into user preferences which indirectly reflect opinion through observing user behavior. For example, a user that bookmarked many articles by the same author probably likes that author."
},
{
"code": null,
"e": 1223,
"s": 1103,
"text": "Our goal today is to develop a recommender system with implicit data collection which is clickstream data, in our case."
},
{
"code": null,
"e": 1511,
"s": 1223,
"text": "It is very hard to find public available data for this project. I am using data from Articles sharing and reading from CI&T DeskDrop. Deskdrop is an internal communications platform that allows companies employees to share relevant articles with their peers, and collaborate around them."
},
{
"code": null,
"e": 1783,
"s": 1511,
"text": "The data contains about 73k users interactions on more than 3k public articles shared in the platform, more importantly, it contains rich implicit feedback, different interaction types were logged, making it possible to infer the user’s level of interest in the articles."
},
{
"code": null,
"e": 1913,
"s": 1783,
"text": "And we will be using Implicit Library, a Fast Python Collaborative Filtering for Implicit Datasets, for our matrix factorization."
},
{
"code": null,
"e": 1949,
"s": 1913,
"text": "Remove columns that we do not need."
},
{
"code": null,
"e": 2005,
"s": 1949,
"text": "Remove eventType == 'CONTENT REMOVED' from articles_df."
},
{
"code": null,
"e": 2045,
"s": 2005,
"text": "Merge interactions_df with articles_df."
},
{
"code": null,
"e": 2093,
"s": 2045,
"text": "This is the data set that will get us to start:"
},
{
"code": null,
"e": 2225,
"s": 2093,
"text": "This tells us what event type each person has with each content. There are many duplicated records and we will remove them shortly."
},
{
"code": null,
"e": 2256,
"s": 2225,
"text": "df['eventType'].value_counts()"
},
{
"code": null,
"e": 2282,
"s": 2256,
"text": "The eventType values are:"
},
{
"code": null,
"e": 2463,
"s": 2282,
"text": "VIEW: The user has opened the article. A page view in a content site can mean many things. It can mean that the user is interested, or maybe user is just lost or clicking randomly."
},
{
"code": null,
"e": 2501,
"s": 2463,
"text": "LIKE: The user has liked the article."
},
{
"code": null,
"e": 2649,
"s": 2501,
"text": "BOOKMARK: The user has bookmarked the article for easy return in the future. This is a strong indication that the user finds something of interest."
},
{
"code": null,
"e": 2706,
"s": 2649,
"text": "COMMENT CREATED: The user left a comment on the article."
},
{
"code": null,
"e": 2782,
"s": 2706,
"text": "FOLLOW: The user chose to be notified on any new comment about the article."
},
{
"code": null,
"e": 2989,
"s": 2782,
"text": "We are going to associate each eventType with a weight or strength. It is reasonable to assume that for example, a bookmark on an article indicates a higher interest of the user on that article than a like."
},
{
"code": null,
"e": 3187,
"s": 2989,
"text": "event_type_strength = { 'VIEW': 1.0, 'LIKE': 2.0, 'BOOKMARK': 3.0, 'FOLLOW': 4.0, 'COMMENT CREATED': 5.0, }df['eventStrength'] = df['eventType'].apply(lambda x: event_type_strength[x])"
},
{
"code": null,
"e": 3212,
"s": 3187,
"text": "Drop duplicated records."
},
{
"code": null,
"e": 3266,
"s": 3212,
"text": "Group eventStrength together with person and content."
},
{
"code": null,
"e": 3392,
"s": 3266,
"text": "df = df.drop_duplicates()grouped_df = df.groupby(['personId', 'contentId', 'title']).sum().reset_index()grouped_df.sample(10)"
},
{
"code": null,
"e": 3442,
"s": 3392,
"text": "We get the final result of grouped eventStrength."
},
{
"code": null,
"e": 3698,
"s": 3442,
"text": "Instead of representing an explicit rating, the eventStrength can represent a “confidence” in terms of how strong the interaction was. Articles with a larger number of eventStrength by a person can carry more weight in our ratings matrix of eventStrength."
},
{
"code": null,
"e": 3804,
"s": 3698,
"text": "To get around “negative integer” warning, I will have to create numeric person_id and content_id columns."
},
{
"code": null,
"e": 3914,
"s": 3804,
"text": "Create two matrices, one for fitting the model (content-person) and one for recommendations (person-content)."
},
{
"code": null,
"e": 3983,
"s": 3914,
"text": "Initialize the Alternating Least Squares (ALS) recommendation model."
},
{
"code": null,
"e": 4037,
"s": 3983,
"text": "Fit the model using the sparse content-person matrix."
},
{
"code": null,
"e": 4115,
"s": 4037,
"text": "We set the type of our matrix to double for the ALS function to run properly."
},
{
"code": null,
"e": 4305,
"s": 4115,
"text": "We are going to find the top 10 most similar articles for content_id = 450, titled “Google’s fair use victory is good for open source”, this article seems talk about Google and open source."
},
{
"code": null,
"e": 4364,
"s": 4305,
"text": "Get the person and content vectors from our trained model."
},
{
"code": null,
"e": 4392,
"s": 4364,
"text": "Calculate the vector norms."
},
{
"code": null,
"e": 4424,
"s": 4392,
"text": "Calculate the similarity score."
},
{
"code": null,
"e": 4449,
"s": 4424,
"text": "Get the top 10 contents."
},
{
"code": null,
"e": 4531,
"s": 4449,
"text": "Create a list of content-score tuples of most similar articles with this article."
},
{
"code": null,
"e": 4756,
"s": 4531,
"text": "The 1st article is itself. The other 9 articles are about Google, or opensource software, or cloud, or AI, or the other tech companies. I am sure you will agree with me that they are all some what similar with the first one!"
},
{
"code": null,
"e": 4920,
"s": 4756,
"text": "The following function will return the top 10 recommendations chosen based on the person / content vectors for contents never interacted with for any given person."
},
{
"code": null,
"e": 4986,
"s": 4920,
"text": "Get the interactions score from the sparse person content matrix."
},
{
"code": null,
"e": 5067,
"s": 4986,
"text": "Add 1 to everything, so that articles with no interaction yet become equal to 1."
},
{
"code": null,
"e": 5106,
"s": 5067,
"text": "Make articles already interacted zero."
},
{
"code": null,
"e": 5164,
"s": 5106,
"text": "Get dot product of person vector and all content vectors."
},
{
"code": null,
"e": 5214,
"s": 5164,
"text": "Scale this recommendation vector between 0 and 1."
},
{
"code": null,
"e": 5287,
"s": 5214,
"text": "Content already interacted have their recommendation multiplied by zero."
},
{
"code": null,
"e": 5355,
"s": 5287,
"text": "Sort the indices of the content into order of best recommendations."
},
{
"code": null,
"e": 5400,
"s": 5355,
"text": "Start empty list to store titles and scores."
},
{
"code": null,
"e": 5438,
"s": 5400,
"text": "Append titles and scores to the list."
},
{
"code": null,
"e": 5515,
"s": 5438,
"text": "Get the trained person and content vectors. We convert them to csr matrices."
},
{
"code": null,
"e": 5561,
"s": 5515,
"text": "Create recommendations for person with id 50."
},
{
"code": null,
"e": 5696,
"s": 5561,
"text": "Here we have top 10 recommendations for person_id = 50. Do they make sense? Let’s get top 10 articles this person has interacted with."
},
{
"code": null,
"e": 5843,
"s": 5696,
"text": "grouped_df.loc[grouped_df['person_id'] == 50].sort_values(by=['eventStrength'], ascending=False)[['title', 'person_id', 'eventStrength']].head(10)"
},
{
"code": null,
"e": 6042,
"s": 5843,
"text": "Apparently, this person is interested in articles on open source CMS such as Drupal, she also reads software development and business related articles, namely “Google”, “Slack” or “Johnson Johnson”."
},
{
"code": null,
"e": 6212,
"s": 6042,
"text": "The articles we recommended to her includes Drupal for digital experience, information technology vs. humanity, software development, and business articles about Google."
},
{
"code": null,
"e": 6251,
"s": 6212,
"text": "Pretty impressive! Let’s try one more."
},
{
"code": null,
"e": 6307,
"s": 6251,
"text": "We recommended the following articles to person_id = 1:"
},
{
"code": null,
"e": 6431,
"s": 6307,
"text": "person_id = 1recommendations = recommend(person_id, sparse_person_content, person_vecs, content_vecs)print(recommendations)"
},
{
"code": null,
"e": 6497,
"s": 6431,
"text": "The following are the articles person_id = 1 has interacted with:"
},
{
"code": null,
"e": 6634,
"s": 6497,
"text": "grouped_df.loc[grouped_df['person_id'] == 1].sort_values(by=['eventStrength'], ascending=False)[['title', 'eventStrength', 'person_id']]"
},
{
"code": null,
"e": 6834,
"s": 6634,
"text": "Apparently, this person has only interacted with 5 articles and she seems to have very limited interest. The articles she interacted was about learning Japanese language and / or android development."
},
{
"code": null,
"e": 6959,
"s": 6834,
"text": "The articles we recommended to her includes learning Japanese language, android development and user interface design. Cool!"
},
{
"code": null,
"e": 7275,
"s": 6959,
"text": "The above spot checks look all good. But the best evaluation metrics for a recommender system is how much the system adds value to the end user and/or business, whether the system increase page views, likes, bookmarks, follows and comments. We will want to do some kind online A/B testing to evaluate these metrics."
},
{
"code": null,
"e": 7625,
"s": 7275,
"text": "However, before we push the recommender system online, there are other common metrics for evaluating the performance of a recommender in isolation. By following this tutorial, we were able to calculate the AUC for each person in our training set that had at least one article masked. And AUC for the most popular articles for the persons to compare."
}
] |
Styling in React.js
|
Styling in React.js can be done in below two ways
css style sheets
inline style
We have App.js file as shown below −
import React, {Component} from 'react';
import './App.css';
class App extends Component {
render(){
return (
<div className="App">
<p className="myColoredText">Styling React Components</p>
</div>
);
}
}
export default App;
In App.js file we have imported an App.css file which contains css class myColoredText
Please note
We used name of css class in double quotes with attribute className
JSX uses camelCase notations for writing attributes on html element.
We have App.css as below −
.myColoredText{
color:blue;
background:yellow;
margin:auto;
width:20%;
padding:20px;
}
Issue with writing css classes with above approach is that the css classes becomes global once webpack build final css file.
Then css classes can get overridden by other css files having same css class.
Use of css module prevents this from happening. The css file names should end with module.css extension.
This solution creates unique css classes in workflow which prevents them from overriding
The css classes will become fileName_cssClassName__hashValue
With this logic, the above used App.css file should be renamed to App.module.css
We can use both the global and module.css files in our application.
For common css we can create a global css file without using module.css extension.
Inline styles are created using JavaScript objects (key value property).
import React, {Component} from 'react';
import './App.css';
class App extends Component {
render(){
let myInlineStyle={
boxShadow:'0 2px 3px #ccc',
border:'2px solid blue',
marginTop:'50px'
}
return (
<div className="App">
<p className="myColoredText" style={myInlineStyle}>Styling React Components</p>
</div>
);
}
}
export default App;
There is a problem with inline styling as well. For hovering the elements using mouse requires third party libraries like radium.
We can install radium as below −
on the application directory, run the following command
npm install --save radium
Add radium in jsx file.
add import for radium
import Radium from 'radium';
Once installed, add hovering object in inline styling object as below −
let myInlineStyle={
boxShadow:'0 2px 3px #ccc',
border:'2px solid blue',
marginTop:'50px',
':hover':{
background:'white'
}
}
With radium, App.js file looks like below −
import React, {Component} from 'react';
import './App.css';
import Radium from 'radium';
class App extends Component {
render(){
let myInlineStyle={
boxShadow:'0 2px 3px #ccc',
border:'2px solid blue',
marginTop:'50px',
':hover':{
background:'white'
}
}
return (
<div className="App">
<p className="myColoredText" style={myInlineStyle}>Styling React Components</p>
</div>
);
}
}
export default Radium(App);
The important thing is we have to wrap or export component in Radium like below −
export default Radium(App);
Now, on hovering it shows the background as white. This way we can handle the inline styling. It’s basically a JavaScript object.
|
[
{
"code": null,
"e": 1112,
"s": 1062,
"text": "Styling in React.js can be done in below two ways"
},
{
"code": null,
"e": 1129,
"s": 1112,
"text": "css style sheets"
},
{
"code": null,
"e": 1142,
"s": 1129,
"text": "inline style"
},
{
"code": null,
"e": 1179,
"s": 1142,
"text": "We have App.js file as shown below −"
},
{
"code": null,
"e": 1453,
"s": 1179,
"text": "import React, {Component} from 'react';\nimport './App.css';\nclass App extends Component {\n render(){\n return (\n <div className=\"App\">\n <p className=\"myColoredText\">Styling React Components</p>\n </div>\n );\n }\n}\nexport default App;"
},
{
"code": null,
"e": 1540,
"s": 1453,
"text": "In App.js file we have imported an App.css file which contains css class myColoredText"
},
{
"code": null,
"e": 1552,
"s": 1540,
"text": "Please note"
},
{
"code": null,
"e": 1620,
"s": 1552,
"text": "We used name of css class in double quotes with attribute className"
},
{
"code": null,
"e": 1689,
"s": 1620,
"text": "JSX uses camelCase notations for writing attributes on html element."
},
{
"code": null,
"e": 1716,
"s": 1689,
"text": "We have App.css as below −"
},
{
"code": null,
"e": 1818,
"s": 1716,
"text": ".myColoredText{\n color:blue;\n background:yellow;\n margin:auto;\n width:20%;\n padding:20px;\n}"
},
{
"code": null,
"e": 1943,
"s": 1818,
"text": "Issue with writing css classes with above approach is that the css classes becomes global once webpack build final css file."
},
{
"code": null,
"e": 2021,
"s": 1943,
"text": "Then css classes can get overridden by other css files having same css class."
},
{
"code": null,
"e": 2126,
"s": 2021,
"text": "Use of css module prevents this from happening. The css file names should end with module.css extension."
},
{
"code": null,
"e": 2215,
"s": 2126,
"text": "This solution creates unique css classes in workflow which prevents them from overriding"
},
{
"code": null,
"e": 2276,
"s": 2215,
"text": "The css classes will become fileName_cssClassName__hashValue"
},
{
"code": null,
"e": 2357,
"s": 2276,
"text": "With this logic, the above used App.css file should be renamed to App.module.css"
},
{
"code": null,
"e": 2425,
"s": 2357,
"text": "We can use both the global and module.css files in our application."
},
{
"code": null,
"e": 2508,
"s": 2425,
"text": "For common css we can create a global css file without using module.css extension."
},
{
"code": null,
"e": 2581,
"s": 2508,
"text": "Inline styles are created using JavaScript objects (key value property)."
},
{
"code": null,
"e": 3005,
"s": 2581,
"text": "import React, {Component} from 'react';\nimport './App.css';\nclass App extends Component {\n render(){\n let myInlineStyle={\n boxShadow:'0 2px 3px #ccc',\n border:'2px solid blue',\n marginTop:'50px'\n }\n return (\n <div className=\"App\">\n <p className=\"myColoredText\" style={myInlineStyle}>Styling React Components</p>\n </div>\n );\n }\n}\nexport default App;"
},
{
"code": null,
"e": 3135,
"s": 3005,
"text": "There is a problem with inline styling as well. For hovering the elements using mouse requires third party libraries like radium."
},
{
"code": null,
"e": 3168,
"s": 3135,
"text": "We can install radium as below −"
},
{
"code": null,
"e": 3250,
"s": 3168,
"text": "on the application directory, run the following command\nnpm install --save radium"
},
{
"code": null,
"e": 3274,
"s": 3250,
"text": "Add radium in jsx file."
},
{
"code": null,
"e": 3325,
"s": 3274,
"text": "add import for radium\nimport Radium from 'radium';"
},
{
"code": null,
"e": 3397,
"s": 3325,
"text": "Once installed, add hovering object in inline styling object as below −"
},
{
"code": null,
"e": 3543,
"s": 3397,
"text": "let myInlineStyle={\n boxShadow:'0 2px 3px #ccc',\n border:'2px solid blue',\n marginTop:'50px',\n ':hover':{\n background:'white'\n }\n}"
},
{
"code": null,
"e": 3587,
"s": 3543,
"text": "With radium, App.js file looks like below −"
},
{
"code": null,
"e": 4111,
"s": 3587,
"text": "import React, {Component} from 'react';\nimport './App.css';\nimport Radium from 'radium';\nclass App extends Component {\n render(){\n let myInlineStyle={\n boxShadow:'0 2px 3px #ccc',\n border:'2px solid blue',\n marginTop:'50px',\n ':hover':{\n background:'white'\n }\n }\n return (\n <div className=\"App\">\n <p className=\"myColoredText\" style={myInlineStyle}>Styling React Components</p>\n </div>\n );\n }\n}\nexport default Radium(App);"
},
{
"code": null,
"e": 4193,
"s": 4111,
"text": "The important thing is we have to wrap or export component in Radium like below −"
},
{
"code": null,
"e": 4221,
"s": 4193,
"text": "export default Radium(App);"
},
{
"code": null,
"e": 4351,
"s": 4221,
"text": "Now, on hovering it shows the background as white. This way we can handle the inline styling. It’s basically a JavaScript object."
}
] |
AVRO - Serialization By Generating Class
|
One can read an Avro schema into the program either by generating a class corresponding to a schema or by using the parsers library. This chapter describes how to read the schema by generating a class and Serializing the data using Avr.
To serialize the data using Avro, follow the steps as given below −
Write an Avro schema.
Write an Avro schema.
Compile the schema using Avro utility. You get the Java code corresponding to that
schema.
Compile the schema using Avro utility. You get the Java code corresponding to that
schema.
Populate the schema with the data.
Populate the schema with the data.
Serialize it using Avro library.
Serialize it using Avro library.
Suppose you want a schema with the following details −
Create an Avro schema as shown below.
Save it as emp.avsc.
{
"namespace": "tutorialspoint.com",
"type": "record",
"name": "emp",
"fields": [
{"name": "name", "type": "string"},
{"name": "id", "type": "int"},
{"name": "salary", "type": "int"},
{"name": "age", "type": "int"},
{"name": "address", "type": "string"}
]
}
After creating an Avro schema, you need to compile the created schema using Avro tools.
avro-tools-1.7.7.jar is the jar containing the tools.
java -jar <path/to/avro-tools-1.7.7.jar> compile schema <path/to/schema-file> <destination-folder>
Open the terminal in the home folder.
Create a new directory to work with Avro as shown below −
$ mkdir Avro_Work
In the newly created directory, create three sub-directories −
First named schema, to place the schema.
First named schema, to place the schema.
Second named with_code_gen, to place the generated code.
Second named with_code_gen, to place the generated code.
Third named jars, to place the jar files.
Third named jars, to place the jar files.
$ mkdir schema
$ mkdir with_code_gen
$ mkdir jars
The following screenshot shows how your Avro_work folder should look like after creating all the directories.
Now /home/Hadoop/Avro_work/jars/avro-tools-1.7.7.jar is the path for the directory where you have downloaded avro-tools-1.7.7.jar file.
Now /home/Hadoop/Avro_work/jars/avro-tools-1.7.7.jar is the path for the directory where you have downloaded avro-tools-1.7.7.jar file.
/home/Hadoop/Avro_work/schema/ is the path for the directory where your schema file emp.avsc is stored.
/home/Hadoop/Avro_work/schema/ is the path for the directory where your schema file emp.avsc is stored.
/home/Hadoop/Avro_work/with_code_gen is the directory where you want the generated class files to be stored.
/home/Hadoop/Avro_work/with_code_gen is the directory where you want the generated class files to be stored.
Now compile the schema as shown below −
$ java -jar /home/Hadoop/Avro_work/jars/avro-tools-1.7.7.jar compile schema /home/Hadoop/Avro_work/schema/emp.avsc /home/Hadoop/Avro/with_code_gen
After compiling, a package according to the name space of the schema is created in the
destination directory. Within this package, the Java source code with schema name is created. This generated source code is the Java code of the given schema which can be used in the applications directly.
For example, in this instance a package/folder, named tutorialspoint is created which contains another folder named com (since the name space is tutorialspoint.com) and within it, you can observe the generated file emp.java. The following snapshot shows emp.java −
This class is useful to create data according to schema.
The generated class contains −
Default constructor, and parameterized constructor which accept all the variables of the schema.
The setter and getter methods for all variables in the schema.
Get() method which returns the schema.
Builder methods.
First of all, copy the generated java file used in this project into the current directory or import it from where it is located.
Now we can write a new Java file and instantiate the class in the generated file (emp) to add employee data to the schema.
Let us see the procedure to create data according to the schema using apache Avro.
Instantiate the generated emp class.
emp e1=new emp( );
Using setter methods, insert the data of first employee. For example, we have created the details of the employee named Omar.
e1.setName("omar");
e1.setAge(21);
e1.setSalary(30000);
e1.setAddress("Hyderabad");
e1.setId(001);
Similarly, fill in all employee details using setter methods.
Create an object of DatumWriter interface using the SpecificDatumWriter class. This converts Java objects into in-memory serialized format. The following example instantiates SpecificDatumWriter class object for emp class.
DatumWriter<emp> empDatumWriter = new SpecificDatumWriter<emp>(emp.class);
Instantiate DataFileWriter for emp class. This class writes a sequence serialized records of data conforming to a schema, along with the schema itself, in a file. This class requires the DatumWriter object, as a parameter to the constructor.
DataFileWriter<emp> empFileWriter = new DataFileWriter<emp>(empDatumWriter);
Open a new file to store the data matching to the given schema using create() method. This method requires the schema, and the path of the file where the data is to be stored, as parameters.
In the following example, schema is passed using getSchema() method, and the data file is stored in the path − /home/Hadoop/Avro/serialized_file/emp.avro.
empFileWriter.create(e1.getSchema(),new File("/home/Hadoop/Avro/serialized_file/emp.avro"));
Add all the created records to the file using append() method as shown below −
empFileWriter.append(e1);
empFileWriter.append(e2);
empFileWriter.append(e3);
The following complete program shows how to serialize data into a file using Apache Avro −
import java.io.File;
import java.io.IOException;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.specific.SpecificDatumWriter;
public class Serialize {
public static void main(String args[]) throws IOException{
//Instantiating generated emp class
emp e1=new emp();
//Creating values according the schema
e1.setName("omar");
e1.setAge(21);
e1.setSalary(30000);
e1.setAddress("Hyderabad");
e1.setId(001);
emp e2=new emp();
e2.setName("ram");
e2.setAge(30);
e2.setSalary(40000);
e2.setAddress("Hyderabad");
e2.setId(002);
emp e3=new emp();
e3.setName("robbin");
e3.setAge(25);
e3.setSalary(35000);
e3.setAddress("Hyderabad");
e3.setId(003);
//Instantiate DatumWriter class
DatumWriter<emp> empDatumWriter = new SpecificDatumWriter<emp>(emp.class);
DataFileWriter<emp> empFileWriter = new DataFileWriter<emp>(empDatumWriter);
empFileWriter.create(e1.getSchema(), new File("/home/Hadoop/Avro_Work/with_code_gen/emp.avro"));
empFileWriter.append(e1);
empFileWriter.append(e2);
empFileWriter.append(e3);
empFileWriter.close();
System.out.println("data successfully serialized");
}
}
Browse through the directory where the generated code is placed. In this case, at home/Hadoop/Avro_work/with_code_gen.
In Terminal −
$ cd home/Hadoop/Avro_work/with_code_gen/
In GUI −
Now copy and save the above program in the file named Serialize.java
Compile and execute it as shown below −
$ javac Serialize.java
$ java Serialize
data successfully serialized
If you verify the path given in the program, you can find the generated serialized file as shown below.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2098,
"s": 1861,
"text": "One can read an Avro schema into the program either by generating a class corresponding to a schema or by using the parsers library. This chapter describes how to read the schema by generating a class and Serializing the data using Avr."
},
{
"code": null,
"e": 2166,
"s": 2098,
"text": "To serialize the data using Avro, follow the steps as given below −"
},
{
"code": null,
"e": 2188,
"s": 2166,
"text": "Write an Avro schema."
},
{
"code": null,
"e": 2210,
"s": 2188,
"text": "Write an Avro schema."
},
{
"code": null,
"e": 2301,
"s": 2210,
"text": "Compile the schema using Avro utility. You get the Java code corresponding to that\nschema."
},
{
"code": null,
"e": 2392,
"s": 2301,
"text": "Compile the schema using Avro utility. You get the Java code corresponding to that\nschema."
},
{
"code": null,
"e": 2427,
"s": 2392,
"text": "Populate the schema with the data."
},
{
"code": null,
"e": 2462,
"s": 2427,
"text": "Populate the schema with the data."
},
{
"code": null,
"e": 2495,
"s": 2462,
"text": "Serialize it using Avro library."
},
{
"code": null,
"e": 2528,
"s": 2495,
"text": "Serialize it using Avro library."
},
{
"code": null,
"e": 2583,
"s": 2528,
"text": "Suppose you want a schema with the following details −"
},
{
"code": null,
"e": 2621,
"s": 2583,
"text": "Create an Avro schema as shown below."
},
{
"code": null,
"e": 2642,
"s": 2621,
"text": "Save it as emp.avsc."
},
{
"code": null,
"e": 2946,
"s": 2642,
"text": "{\n \"namespace\": \"tutorialspoint.com\",\n \"type\": \"record\",\n \"name\": \"emp\",\n \"fields\": [\n {\"name\": \"name\", \"type\": \"string\"},\n {\"name\": \"id\", \"type\": \"int\"},\n {\"name\": \"salary\", \"type\": \"int\"},\n {\"name\": \"age\", \"type\": \"int\"},\n {\"name\": \"address\", \"type\": \"string\"}\n ]\n}\n"
},
{
"code": null,
"e": 3088,
"s": 2946,
"text": "After creating an Avro schema, you need to compile the created schema using Avro tools.\navro-tools-1.7.7.jar is the jar containing the tools."
},
{
"code": null,
"e": 3188,
"s": 3088,
"text": "java -jar <path/to/avro-tools-1.7.7.jar> compile schema <path/to/schema-file> <destination-folder>\n"
},
{
"code": null,
"e": 3226,
"s": 3188,
"text": "Open the terminal in the home folder."
},
{
"code": null,
"e": 3284,
"s": 3226,
"text": "Create a new directory to work with Avro as shown below −"
},
{
"code": null,
"e": 3303,
"s": 3284,
"text": "$ mkdir Avro_Work\n"
},
{
"code": null,
"e": 3366,
"s": 3303,
"text": "In the newly created directory, create three sub-directories −"
},
{
"code": null,
"e": 3407,
"s": 3366,
"text": "First named schema, to place the schema."
},
{
"code": null,
"e": 3448,
"s": 3407,
"text": "First named schema, to place the schema."
},
{
"code": null,
"e": 3505,
"s": 3448,
"text": "Second named with_code_gen, to place the generated code."
},
{
"code": null,
"e": 3562,
"s": 3505,
"text": "Second named with_code_gen, to place the generated code."
},
{
"code": null,
"e": 3604,
"s": 3562,
"text": "Third named jars, to place the jar files."
},
{
"code": null,
"e": 3646,
"s": 3604,
"text": "Third named jars, to place the jar files."
},
{
"code": null,
"e": 3697,
"s": 3646,
"text": "$ mkdir schema\n$ mkdir with_code_gen\n$ mkdir jars\n"
},
{
"code": null,
"e": 3807,
"s": 3697,
"text": "The following screenshot shows how your Avro_work folder should look like after creating all the directories."
},
{
"code": null,
"e": 3943,
"s": 3807,
"text": "Now /home/Hadoop/Avro_work/jars/avro-tools-1.7.7.jar is the path for the directory where you have downloaded avro-tools-1.7.7.jar file."
},
{
"code": null,
"e": 4079,
"s": 3943,
"text": "Now /home/Hadoop/Avro_work/jars/avro-tools-1.7.7.jar is the path for the directory where you have downloaded avro-tools-1.7.7.jar file."
},
{
"code": null,
"e": 4183,
"s": 4079,
"text": "/home/Hadoop/Avro_work/schema/ is the path for the directory where your schema file emp.avsc is stored."
},
{
"code": null,
"e": 4287,
"s": 4183,
"text": "/home/Hadoop/Avro_work/schema/ is the path for the directory where your schema file emp.avsc is stored."
},
{
"code": null,
"e": 4396,
"s": 4287,
"text": "/home/Hadoop/Avro_work/with_code_gen is the directory where you want the generated class files to be stored."
},
{
"code": null,
"e": 4505,
"s": 4396,
"text": "/home/Hadoop/Avro_work/with_code_gen is the directory where you want the generated class files to be stored."
},
{
"code": null,
"e": 4545,
"s": 4505,
"text": "Now compile the schema as shown below −"
},
{
"code": null,
"e": 4693,
"s": 4545,
"text": "$ java -jar /home/Hadoop/Avro_work/jars/avro-tools-1.7.7.jar compile schema /home/Hadoop/Avro_work/schema/emp.avsc /home/Hadoop/Avro/with_code_gen\n"
},
{
"code": null,
"e": 4986,
"s": 4693,
"text": "After compiling, a package according to the name space of the schema is created in the\ndestination directory. Within this package, the Java source code with schema name is created. This generated source code is the Java code of the given schema which can be used in the applications directly."
},
{
"code": null,
"e": 5252,
"s": 4986,
"text": "For example, in this instance a package/folder, named tutorialspoint is created which contains another folder named com (since the name space is tutorialspoint.com) and within it, you can observe the generated file emp.java. The following snapshot shows emp.java − "
},
{
"code": null,
"e": 5309,
"s": 5252,
"text": "This class is useful to create data according to schema."
},
{
"code": null,
"e": 5340,
"s": 5309,
"text": "The generated class contains −"
},
{
"code": null,
"e": 5437,
"s": 5340,
"text": "Default constructor, and parameterized constructor which accept all the variables of the schema."
},
{
"code": null,
"e": 5500,
"s": 5437,
"text": "The setter and getter methods for all variables in the schema."
},
{
"code": null,
"e": 5539,
"s": 5500,
"text": "Get() method which returns the schema."
},
{
"code": null,
"e": 5556,
"s": 5539,
"text": "Builder methods."
},
{
"code": null,
"e": 5686,
"s": 5556,
"text": "First of all, copy the generated java file used in this project into the current directory or import it from where it is located."
},
{
"code": null,
"e": 5809,
"s": 5686,
"text": "Now we can write a new Java file and instantiate the class in the generated file (emp) to add employee data to the schema."
},
{
"code": null,
"e": 5892,
"s": 5809,
"text": "Let us see the procedure to create data according to the schema using apache Avro."
},
{
"code": null,
"e": 5929,
"s": 5892,
"text": "Instantiate the generated emp class."
},
{
"code": null,
"e": 5949,
"s": 5929,
"text": "emp e1=new emp( );\n"
},
{
"code": null,
"e": 6075,
"s": 5949,
"text": "Using setter methods, insert the data of first employee. For example, we have created the details of the employee named Omar."
},
{
"code": null,
"e": 6175,
"s": 6075,
"text": "e1.setName(\"omar\");\ne1.setAge(21);\ne1.setSalary(30000);\ne1.setAddress(\"Hyderabad\");\ne1.setId(001);\n"
},
{
"code": null,
"e": 6237,
"s": 6175,
"text": "Similarly, fill in all employee details using setter methods."
},
{
"code": null,
"e": 6460,
"s": 6237,
"text": "Create an object of DatumWriter interface using the SpecificDatumWriter class. This converts Java objects into in-memory serialized format. The following example instantiates SpecificDatumWriter class object for emp class."
},
{
"code": null,
"e": 6536,
"s": 6460,
"text": "DatumWriter<emp> empDatumWriter = new SpecificDatumWriter<emp>(emp.class);\n"
},
{
"code": null,
"e": 6778,
"s": 6536,
"text": "Instantiate DataFileWriter for emp class. This class writes a sequence serialized records of data conforming to a schema, along with the schema itself, in a file. This class requires the DatumWriter object, as a parameter to the constructor."
},
{
"code": null,
"e": 6856,
"s": 6778,
"text": "DataFileWriter<emp> empFileWriter = new DataFileWriter<emp>(empDatumWriter);\n"
},
{
"code": null,
"e": 7047,
"s": 6856,
"text": "Open a new file to store the data matching to the given schema using create() method. This method requires the schema, and the path of the file where the data is to be stored, as parameters."
},
{
"code": null,
"e": 7202,
"s": 7047,
"text": "In the following example, schema is passed using getSchema() method, and the data file is stored in the path − /home/Hadoop/Avro/serialized_file/emp.avro."
},
{
"code": null,
"e": 7295,
"s": 7202,
"text": "empFileWriter.create(e1.getSchema(),new File(\"/home/Hadoop/Avro/serialized_file/emp.avro\"));"
},
{
"code": null,
"e": 7374,
"s": 7295,
"text": "Add all the created records to the file using append() method as shown below −"
},
{
"code": null,
"e": 7453,
"s": 7374,
"text": "empFileWriter.append(e1);\nempFileWriter.append(e2);\nempFileWriter.append(e3);\n"
},
{
"code": null,
"e": 7544,
"s": 7453,
"text": "The following complete program shows how to serialize data into a file using Apache Avro −"
},
{
"code": null,
"e": 8882,
"s": 7544,
"text": "import java.io.File;\nimport java.io.IOException;\n\nimport org.apache.avro.file.DataFileWriter;\nimport org.apache.avro.io.DatumWriter;\nimport org.apache.avro.specific.SpecificDatumWriter;\n\npublic class Serialize {\n public static void main(String args[]) throws IOException{\n\t\n //Instantiating generated emp class\n emp e1=new emp();\n\t\n //Creating values according the schema\n e1.setName(\"omar\");\n e1.setAge(21);\n e1.setSalary(30000);\n e1.setAddress(\"Hyderabad\");\n e1.setId(001);\n\t\n emp e2=new emp();\n\t\n e2.setName(\"ram\");\n e2.setAge(30);\n e2.setSalary(40000);\n e2.setAddress(\"Hyderabad\");\n e2.setId(002);\n\t\n emp e3=new emp();\n\t\n e3.setName(\"robbin\");\n e3.setAge(25);\n e3.setSalary(35000);\n e3.setAddress(\"Hyderabad\");\n e3.setId(003);\n\t\n //Instantiate DatumWriter class\n DatumWriter<emp> empDatumWriter = new SpecificDatumWriter<emp>(emp.class);\n DataFileWriter<emp> empFileWriter = new DataFileWriter<emp>(empDatumWriter);\n\t\n empFileWriter.create(e1.getSchema(), new File(\"/home/Hadoop/Avro_Work/with_code_gen/emp.avro\"));\n\t\n empFileWriter.append(e1);\n empFileWriter.append(e2);\n empFileWriter.append(e3);\n\t\n empFileWriter.close();\n\t\n System.out.println(\"data successfully serialized\");\n }\n}"
},
{
"code": null,
"e": 9001,
"s": 8882,
"text": "Browse through the directory where the generated code is placed. In this case, at home/Hadoop/Avro_work/with_code_gen."
},
{
"code": null,
"e": 9015,
"s": 9001,
"text": "In Terminal −"
},
{
"code": null,
"e": 9058,
"s": 9015,
"text": "$ cd home/Hadoop/Avro_work/with_code_gen/\n"
},
{
"code": null,
"e": 9067,
"s": 9058,
"text": "In GUI −"
},
{
"code": null,
"e": 9136,
"s": 9067,
"text": "Now copy and save the above program in the file named Serialize.java"
},
{
"code": null,
"e": 9176,
"s": 9136,
"text": "Compile and execute it as shown below −"
},
{
"code": null,
"e": 9217,
"s": 9176,
"text": "$ javac Serialize.java\n$ java Serialize\n"
},
{
"code": null,
"e": 9247,
"s": 9217,
"text": "data successfully serialized\n"
},
{
"code": null,
"e": 9351,
"s": 9247,
"text": "If you verify the path given in the program, you can find the generated serialized file as shown below."
},
{
"code": null,
"e": 9358,
"s": 9351,
"text": " Print"
},
{
"code": null,
"e": 9369,
"s": 9358,
"text": " Add Notes"
}
] |
What are Lvalues and Rvalues in C++?
|
An lvalue (locator value) represents an object that occupies some identifiable location in memory (i.e. has an address).
rvalues are defined by exclusion. Every expression is either an lvalue or an rvalue, so, an rvalue is an expression that does not represent an object occupying some identifiable location in memory.
For example, An assignment expects an lvalue as its left operand, so the following is valid −
int i = 10;
But this is not:
int i;
10 = i;
This is because i has an address in memory and is a lvalue. While 10 doesn't have an identifiable memory location and hence is an rvalue. So assigning the value of i to 10 doesn't make any sense.
|
[
{
"code": null,
"e": 1183,
"s": 1062,
"text": "An lvalue (locator value) represents an object that occupies some identifiable location in memory (i.e. has an address)."
},
{
"code": null,
"e": 1381,
"s": 1183,
"text": "rvalues are defined by exclusion. Every expression is either an lvalue or an rvalue, so, an rvalue is an expression that does not represent an object occupying some identifiable location in memory."
},
{
"code": null,
"e": 1475,
"s": 1381,
"text": "For example, An assignment expects an lvalue as its left operand, so the following is valid −"
},
{
"code": null,
"e": 1519,
"s": 1475,
"text": "int i = 10;\nBut this is not:\nint i;\n10 = i;"
},
{
"code": null,
"e": 1715,
"s": 1519,
"text": "This is because i has an address in memory and is a lvalue. While 10 doesn't have an identifiable memory location and hence is an rvalue. So assigning the value of i to 10 doesn't make any sense."
}
] |
Order-Agnostic Binary Search
|
20 Jun, 2022
Order-Agnostic Binary Search is a modified version of Binary Search algorithm. Here in this modified binary search comes with one more condition checking. The intuition behind this algorithm is what if the order of the sorted array is not given. So here check that the value of the first element is greater or smaller than the last element.
If the first element is smaller than the last element-then if the search key value X is less than the middle of the interval then the end pointer will be changed to middle -1 otherwise start will be changed to middle + 1.
If the first element is greater than the last element-then if the search key value X is less than the middle of the interval then the start pointer will move to the next element of the middle element otherwise the end pointer will move previous to the middle element.
In the end, if the search key value matches with the middle element then the element which was given to the search is found.
Implementation of Order-Agnostic Binary Search:
Let us see the implementation of Order-Agnostic Binary Search with the help of an example.
Given an array, arr[ ] of size N and an element X and the array is sorted in any order(ascending or descending), the task is to find whether the element x is present in the array or not. If yes, then print its index, else print -1.
Examples:
Input: arr[] = {40, 10, 5, 2, 1}, N=5, X=10Output: 1Explanation:
The array is sorted in descending order and the element is present at index 1.
Input: arr[] = {1}, N=1, X=10Output: -1
Approach: The brute force idea would be to linearly traverse the array and check whether the element is present in the array or not. Optimization to this algorithm would be to use binary search if the order of sorting of the array was known – ascending/descending. A variation of binary search can be used i.e, Order-Agnostic Binary search as stated below:
Follow the steps below to solve the problem using Order-Agnostic Binary Search:
Initialize a boolean variable isAsc as true if arr[start] is less than arr[end] else set it as false.
Traverse over a while loop till start is less than equal to end and perform the following steps:Initialize the variable middle as the average of start and end.If arr[middle] equals X, then return the value of middle as the answer,If the array is in ascending order then perform the following steps:If arr[middle] is less than X, then set the value of start as middle+1 else set the value of end as middle-1.Else, if arr[middle] is less than X, then set the value of end as middle-1 else set the value of start as middle+1.
Initialize the variable middle as the average of start and end.
If arr[middle] equals X, then return the value of middle as the answer,
If the array is in ascending order then perform the following steps:If arr[middle] is less than X, then set the value of start as middle+1 else set the value of end as middle-1.
If arr[middle] is less than X, then set the value of start as middle+1 else set the value of end as middle-1.
Else, if arr[middle] is less than X, then set the value of end as middle-1 else set the value of start as middle+1.
After performing the above steps, return the value of -1 as the answer as the element is not found.
Iterative implementation of Order-Agnostic Binary Search.
C++
Java
Python
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // An iterative binary search function.int binarySearch(int arr[], int start, int end, int x){ // Checking the sorted order of the given array bool isAsc = arr[start] < arr[end]; while (start <= end) { int middle = start + (end - start) / 2; // Check if x is present at mid if (arr[middle] == x) return middle; // Ascending order if (isAsc == true) { // If x greater, ignore left half if (arr[middle] < x) start = middle + 1; // If x smaller, ignore right half else end = middle - 1; } // Descending order else { // If x smaller, ignore left half if (arr[middle] > x) start = middle + 1; // If x greater, ignore right half else end = middle - 1; } } // Element is not present return -1;} // Driver Codeint main(){ int arr[] = { 40, 10, 5, 2, 1 }; int x = 10; int n = sizeof(arr) / sizeof(arr[0]); cout << binarySearch(arr, 0, n - 1, x); return 0;}
// Java program for the above approachimport java.util.*;class GFG { // An iterative binary search function.static int binarySearch(int arr[], int start, int end, int x){ // Checking the sorted order of the given array boolean isAsc = arr[start] < arr[end]; while (start <= end) { int middle = start + (end - start) / 2; // Check if x is present at mid if (arr[middle] == x) return middle; // Ascending order if (isAsc == true) { // If x greater, ignore left half if (arr[middle] < x) start = middle + 1; // If x smaller, ignore right half else end = middle - 1; } // Descending order else { // If x smaller, ignore left half if (arr[middle] > x) start = middle + 1; // If x greater, ignore right half else end = middle - 1; } } // Element is not present return -1;} // Driver Code public static void main(String[] args) { int arr[] = { 40, 10, 5, 2, 1 }; int x = 10; int n = arr.length; System.out.println(binarySearch(arr, 0, n - 1, x)); }} // This code is contributed by sanjoy_62.
# Python program for the above approach # An iterative binary search function.def binarySearch(arr, start, end, x): # Checking the sorted order of the given array isAsc = arr[start] < arr[end] while (start <= end): middle = start + (end - start) // 2 # Check if x is present at mid if (arr[middle] == x): return middle # Ascending order if (isAsc == True): # If x greater, ignore left half if (arr[middle] < x): start = middle + 1 # If x smaller, ignore right half else: end = middle - 1 # Descending order else: # If x smaller, ignore left half if (arr[middle] > x): start = middle + 1 # If x greater, ignore right half else: end = middle - 1 # Element is not present return -1 # Driver Codearr = [ 40, 10, 5, 2, 1 ]x = 10n = len(arr)print(binarySearch(arr, 0, n - 1, x)) # This code is ciontributed by Samim Hossain Mondal.
// C# program for the above approachusing System;using System.Collections.Generic; class GFG { // An iterative binary search function.static int binarySearch(int[] arr, int start, int end, int x){ // Checking the sorted order of the given array bool isAsc = arr[start] < arr[end]; while (start <= end) { int middle = start + (end - start) / 2; // Check if x is present at mid if (arr[middle] == x) return middle; // Ascending order if (isAsc == true) { // If x greater, ignore left half if (arr[middle] < x) start = middle + 1; // If x smaller, ignore right half else end = middle - 1; } // Descending order else { // If x smaller, ignore left half if (arr[middle] > x) start = middle + 1; // If x greater, ignore right half else end = middle - 1; } } // Element is not present return -1;} // Driver Code public static void Main(String[] args) { int[] arr = { 40, 10, 5, 2, 1 }; int x = 10; int n = arr.Length; Console.Write(binarySearch(arr, 0, n - 1, x)); }} // This code is contributed by code_hunt.
<script> // JavaScript Program to implement // the above approach // An iterative binary search function. function binarySearch(arr, start, end, x) { // Checking the sorted order of the given array let isAsc = arr[start] < arr[end]; while (start <= end) { let middle = start + Math.floor((end - start) / 2); // Check if x is present at mid if (arr[middle] == x) return middle; // Ascending order if (isAsc == true) { // If x greater, ignore left half if (arr[middle] < x) start = middle + 1; // If x smaller, ignore right half else end = middle - 1; } // Descending order else { // If x smaller, ignore left half if (arr[middle] > x) start = middle + 1; // If x greater, ignore right half else end = middle - 1; } } // Element is not present return -1; } // Driver Code let arr = [40, 10, 5, 2, 1]; let x = 10; let n = arr.length; document.write(binarySearch(arr, 0, n - 1, x)); // This code is contributed by Potta Lokesh </script>
1
Time Complexity: O(log(N)).Auxiliary Space: O(1)
Recursive implementation of Order-Agnostic Binary Search :
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // A recursive binary search function.// It returns location of x in given// array arr[l..r] is present,// otherwise -1int binarySearch(int arr[], int start, int end, int x){ bool isAsc = arr[start] < arr[end]; if (end >= start) { int middle = start + (end - start) / 2; // If the element is present // at the middle itself if (arr[middle] == x) return middle; if (isAsc == true) { // If element is smaller than mid, // then it can only be // present in left subarray if (arr[middle] > x) return binarySearch( arr, start, middle - 1, x); // Else the element can only be present // in right subarray return binarySearch(arr, middle + 1, end, x); } else { if (arr[middle] < x) return binarySearch(arr, start, middle - 1, x); // Else the element can only be present // in left subarray return binarySearch(arr, middle + 1, end, x); } } // Element not found return -1;} // Driver Codeint main(void){ int arr[] = { 40, 10, 5, 2, 1 }; int x = 10; int n = sizeof(arr) / sizeof(arr[0]); cout << binarySearch(arr, 0, n - 1, x); return 0;}
// Java program for the above approachimport java.util.*; class GFG { // A recursive binary search function. // It returns location of x in given // array arr[l..r] is present, // otherwise -1 static int binarySearch(int arr[], int start, int end, int x) { boolean isAsc = arr[start] < arr[end]; if (end >= start) { int middle = start + (end - start) / 2; // If the element is present // at the middle itself if (arr[middle] == x) return middle; if (isAsc == true) { // If element is smaller than mid, // then it can only be // present in left subarray if (arr[middle] > x) return binarySearch(arr, start, middle - 1, x); // Else the element can only be present // in right subarray return binarySearch(arr, middle + 1, end, x); } else { if (arr[middle] < x) return binarySearch(arr, start, middle - 1, x); // Else the element can only be present // in left subarray return binarySearch(arr, middle + 1, end, x); } } // Element not found return -1; } // Driver Code public static void main(String[] args) { int arr[] = { 40, 10, 5, 2, 1 }; int x = 10; int n = arr.length; System.out.print(binarySearch(arr, 0, n - 1, x)); }} // This code is contributed by Rajput-Ji
# Python program for the above approach # A recursive binary search function.# It returns location of x in given# array arr[l..r] is present,# otherwise -1def binarySearch(arr, start, end, x): isAsc = arr[start] < arr[end] if (end >= start): middle = (int)(start + (end - start) / 2) # If the element is present # at the middle itself if (arr[middle] == x): return middle if (isAsc == True): # If element is smaller than mid, # then it can only be # present in left subarray if (arr[middle] > x): return binarySearch( arr, start, middle - 1, x) # Else the element can only be present # in right subarray return binarySearch(arr, middle + 1, end, x) else: if (arr[middle] < x): return binarySearch(arr, start, middle - 1, x) # Else the element can only be present # in left subarray return binarySearch(arr, middle + 1, end, x) # Element not found return -1 # Driver Code arr = [40, 10, 5, 2, 1]x = 10n = len(arr)print(binarySearch(arr, 0, n - 1, x)) # This code is contributed by Taranpreet
// C# program for the above approachusing System; public class GFG { // A recursive binary search function. // It returns location of x in given // array arr[l..r] is present, // otherwise -1 static int binarySearch(int []arr, int start, int end, int x) { bool isAsc = arr[start] < arr[end]; if (end >= start) { int middle = start + (end - start) / 2; // If the element is present // at the middle itself if (arr[middle] == x) return middle; if (isAsc == true) { // If element is smaller than mid, // then it can only be // present in left subarray if (arr[middle] > x) return binarySearch(arr, start, middle - 1, x); // Else the element can only be present // in right subarray return binarySearch(arr, middle + 1, end, x); } else { if (arr[middle] < x) return binarySearch(arr, start, middle - 1, x); // Else the element can only be present // in left subarray return binarySearch(arr, middle + 1, end, x); } } // Element not found return -1; } // Driver Code public static void Main(String[] args) { int []arr = { 40, 10, 5, 2, 1 }; int x = 10; int n = arr.Length; Console.Write(binarySearch(arr, 0, n - 1, x)); }} // This code contributed by Rajput-Ji
<script>// javascript program for the above approach // A recursive binary search function. // It returns location of x in given // array arr[l..r] is present, // otherwise -1 function binarySearch(arr , start , end , x) { let isAsc = arr[start] < arr[end]; if (end >= start) { var middle = start + parseInt((end - start) / 2); // If the element is present // at the middle itself if (arr[middle] == x) return middle; if (isAsc == true) { // If element is smaller than mid, // then it can only be // present in left subarray if (arr[middle] > x) return binarySearch(arr, start, middle - 1, x); // Else the element can only be present // in right subarray return binarySearch(arr, middle + 1, end, x); } else { if (arr[middle] < x) return binarySearch(arr, start, middle - 1, x); // Else the element can only be present // in left subarray return binarySearch(arr, middle + 1, end, x); } } // Element not found return -1; } // Driver Code var arr = [ 40, 10, 5, 2, 1 ]; var x = 10; var n = arr.length; document.write(binarySearch(arr, 0, n - 1, x)); // This code is contributed by Rajput-Ji</script>
1
Time Complexity: O(log(N)).Auxiliary Space: O(1)
sanjoy_62
lokeshpotta20
code_hunt
samim2000
Rajput-Ji
singhh3010
Binary Search
Divide and Conquer
Searching
Searching
Divide and Conquer
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n20 Jun, 2022"
},
{
"code": null,
"e": 393,
"s": 52,
"text": "Order-Agnostic Binary Search is a modified version of Binary Search algorithm. Here in this modified binary search comes with one more condition checking. The intuition behind this algorithm is what if the order of the sorted array is not given. So here check that the value of the first element is greater or smaller than the last element."
},
{
"code": null,
"e": 615,
"s": 393,
"text": "If the first element is smaller than the last element-then if the search key value X is less than the middle of the interval then the end pointer will be changed to middle -1 otherwise start will be changed to middle + 1."
},
{
"code": null,
"e": 883,
"s": 615,
"text": "If the first element is greater than the last element-then if the search key value X is less than the middle of the interval then the start pointer will move to the next element of the middle element otherwise the end pointer will move previous to the middle element."
},
{
"code": null,
"e": 1008,
"s": 883,
"text": "In the end, if the search key value matches with the middle element then the element which was given to the search is found."
},
{
"code": null,
"e": 1056,
"s": 1008,
"text": "Implementation of Order-Agnostic Binary Search:"
},
{
"code": null,
"e": 1147,
"s": 1056,
"text": "Let us see the implementation of Order-Agnostic Binary Search with the help of an example."
},
{
"code": null,
"e": 1379,
"s": 1147,
"text": "Given an array, arr[ ] of size N and an element X and the array is sorted in any order(ascending or descending), the task is to find whether the element x is present in the array or not. If yes, then print its index, else print -1."
},
{
"code": null,
"e": 1389,
"s": 1379,
"text": "Examples:"
},
{
"code": null,
"e": 1456,
"s": 1389,
"text": "Input: arr[] = {40, 10, 5, 2, 1}, N=5, X=10Output: 1Explanation: "
},
{
"code": null,
"e": 1535,
"s": 1456,
"text": "The array is sorted in descending order and the element is present at index 1."
},
{
"code": null,
"e": 1575,
"s": 1535,
"text": "Input: arr[] = {1}, N=1, X=10Output: -1"
},
{
"code": null,
"e": 1932,
"s": 1575,
"text": "Approach: The brute force idea would be to linearly traverse the array and check whether the element is present in the array or not. Optimization to this algorithm would be to use binary search if the order of sorting of the array was known – ascending/descending. A variation of binary search can be used i.e, Order-Agnostic Binary search as stated below:"
},
{
"code": null,
"e": 2012,
"s": 1932,
"text": "Follow the steps below to solve the problem using Order-Agnostic Binary Search:"
},
{
"code": null,
"e": 2114,
"s": 2012,
"text": "Initialize a boolean variable isAsc as true if arr[start] is less than arr[end] else set it as false."
},
{
"code": null,
"e": 2638,
"s": 2114,
"text": "Traverse over a while loop till start is less than equal to end and perform the following steps:Initialize the variable middle as the average of start and end.If arr[middle] equals X, then return the value of middle as the answer,If the array is in ascending order then perform the following steps:If arr[middle] is less than X, then set the value of start as middle+1 else set the value of end as middle-1.Else, if arr[middle] is less than X, then set the value of end as middle-1 else set the value of start as middle+1."
},
{
"code": null,
"e": 2702,
"s": 2638,
"text": "Initialize the variable middle as the average of start and end."
},
{
"code": null,
"e": 2774,
"s": 2702,
"text": "If arr[middle] equals X, then return the value of middle as the answer,"
},
{
"code": null,
"e": 2953,
"s": 2774,
"text": "If the array is in ascending order then perform the following steps:If arr[middle] is less than X, then set the value of start as middle+1 else set the value of end as middle-1."
},
{
"code": null,
"e": 3064,
"s": 2953,
"text": "If arr[middle] is less than X, then set the value of start as middle+1 else set the value of end as middle-1."
},
{
"code": null,
"e": 3180,
"s": 3064,
"text": "Else, if arr[middle] is less than X, then set the value of end as middle-1 else set the value of start as middle+1."
},
{
"code": null,
"e": 3280,
"s": 3180,
"text": "After performing the above steps, return the value of -1 as the answer as the element is not found."
},
{
"code": null,
"e": 3338,
"s": 3280,
"text": "Iterative implementation of Order-Agnostic Binary Search."
},
{
"code": null,
"e": 3342,
"s": 3338,
"text": "C++"
},
{
"code": null,
"e": 3347,
"s": 3342,
"text": "Java"
},
{
"code": null,
"e": 3354,
"s": 3347,
"text": "Python"
},
{
"code": null,
"e": 3357,
"s": 3354,
"text": "C#"
},
{
"code": null,
"e": 3368,
"s": 3357,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // An iterative binary search function.int binarySearch(int arr[], int start, int end, int x){ // Checking the sorted order of the given array bool isAsc = arr[start] < arr[end]; while (start <= end) { int middle = start + (end - start) / 2; // Check if x is present at mid if (arr[middle] == x) return middle; // Ascending order if (isAsc == true) { // If x greater, ignore left half if (arr[middle] < x) start = middle + 1; // If x smaller, ignore right half else end = middle - 1; } // Descending order else { // If x smaller, ignore left half if (arr[middle] > x) start = middle + 1; // If x greater, ignore right half else end = middle - 1; } } // Element is not present return -1;} // Driver Codeint main(){ int arr[] = { 40, 10, 5, 2, 1 }; int x = 10; int n = sizeof(arr) / sizeof(arr[0]); cout << binarySearch(arr, 0, n - 1, x); return 0;}",
"e": 4563,
"s": 3368,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;class GFG { // An iterative binary search function.static int binarySearch(int arr[], int start, int end, int x){ // Checking the sorted order of the given array boolean isAsc = arr[start] < arr[end]; while (start <= end) { int middle = start + (end - start) / 2; // Check if x is present at mid if (arr[middle] == x) return middle; // Ascending order if (isAsc == true) { // If x greater, ignore left half if (arr[middle] < x) start = middle + 1; // If x smaller, ignore right half else end = middle - 1; } // Descending order else { // If x smaller, ignore left half if (arr[middle] > x) start = middle + 1; // If x greater, ignore right half else end = middle - 1; } } // Element is not present return -1;} // Driver Code public static void main(String[] args) { int arr[] = { 40, 10, 5, 2, 1 }; int x = 10; int n = arr.length; System.out.println(binarySearch(arr, 0, n - 1, x)); }} // This code is contributed by sanjoy_62.",
"e": 5822,
"s": 4563,
"text": null
},
{
"code": "# Python program for the above approach # An iterative binary search function.def binarySearch(arr, start, end, x): # Checking the sorted order of the given array isAsc = arr[start] < arr[end] while (start <= end): middle = start + (end - start) // 2 # Check if x is present at mid if (arr[middle] == x): return middle # Ascending order if (isAsc == True): # If x greater, ignore left half if (arr[middle] < x): start = middle + 1 # If x smaller, ignore right half else: end = middle - 1 # Descending order else: # If x smaller, ignore left half if (arr[middle] > x): start = middle + 1 # If x greater, ignore right half else: end = middle - 1 # Element is not present return -1 # Driver Codearr = [ 40, 10, 5, 2, 1 ]x = 10n = len(arr)print(binarySearch(arr, 0, n - 1, x)) # This code is ciontributed by Samim Hossain Mondal.",
"e": 6885,
"s": 5822,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG { // An iterative binary search function.static int binarySearch(int[] arr, int start, int end, int x){ // Checking the sorted order of the given array bool isAsc = arr[start] < arr[end]; while (start <= end) { int middle = start + (end - start) / 2; // Check if x is present at mid if (arr[middle] == x) return middle; // Ascending order if (isAsc == true) { // If x greater, ignore left half if (arr[middle] < x) start = middle + 1; // If x smaller, ignore right half else end = middle - 1; } // Descending order else { // If x smaller, ignore left half if (arr[middle] > x) start = middle + 1; // If x greater, ignore right half else end = middle - 1; } } // Element is not present return -1;} // Driver Code public static void Main(String[] args) { int[] arr = { 40, 10, 5, 2, 1 }; int x = 10; int n = arr.Length; Console.Write(binarySearch(arr, 0, n - 1, x)); }} // This code is contributed by code_hunt.",
"e": 8178,
"s": 6885,
"text": null
},
{
"code": "<script> // JavaScript Program to implement // the above approach // An iterative binary search function. function binarySearch(arr, start, end, x) { // Checking the sorted order of the given array let isAsc = arr[start] < arr[end]; while (start <= end) { let middle = start + Math.floor((end - start) / 2); // Check if x is present at mid if (arr[middle] == x) return middle; // Ascending order if (isAsc == true) { // If x greater, ignore left half if (arr[middle] < x) start = middle + 1; // If x smaller, ignore right half else end = middle - 1; } // Descending order else { // If x smaller, ignore left half if (arr[middle] > x) start = middle + 1; // If x greater, ignore right half else end = middle - 1; } } // Element is not present return -1; } // Driver Code let arr = [40, 10, 5, 2, 1]; let x = 10; let n = arr.length; document.write(binarySearch(arr, 0, n - 1, x)); // This code is contributed by Potta Lokesh </script>",
"e": 9664,
"s": 8178,
"text": null
},
{
"code": null,
"e": 9669,
"s": 9667,
"text": "1"
},
{
"code": null,
"e": 9722,
"s": 9673,
"text": "Time Complexity: O(log(N)).Auxiliary Space: O(1)"
},
{
"code": null,
"e": 9783,
"s": 9724,
"text": "Recursive implementation of Order-Agnostic Binary Search :"
},
{
"code": null,
"e": 9789,
"s": 9785,
"text": "C++"
},
{
"code": null,
"e": 9794,
"s": 9789,
"text": "Java"
},
{
"code": null,
"e": 9802,
"s": 9794,
"text": "Python3"
},
{
"code": null,
"e": 9805,
"s": 9802,
"text": "C#"
},
{
"code": null,
"e": 9816,
"s": 9805,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // A recursive binary search function.// It returns location of x in given// array arr[l..r] is present,// otherwise -1int binarySearch(int arr[], int start, int end, int x){ bool isAsc = arr[start] < arr[end]; if (end >= start) { int middle = start + (end - start) / 2; // If the element is present // at the middle itself if (arr[middle] == x) return middle; if (isAsc == true) { // If element is smaller than mid, // then it can only be // present in left subarray if (arr[middle] > x) return binarySearch( arr, start, middle - 1, x); // Else the element can only be present // in right subarray return binarySearch(arr, middle + 1, end, x); } else { if (arr[middle] < x) return binarySearch(arr, start, middle - 1, x); // Else the element can only be present // in left subarray return binarySearch(arr, middle + 1, end, x); } } // Element not found return -1;} // Driver Codeint main(void){ int arr[] = { 40, 10, 5, 2, 1 }; int x = 10; int n = sizeof(arr) / sizeof(arr[0]); cout << binarySearch(arr, 0, n - 1, x); return 0;}",
"e": 11334,
"s": 9816,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG { // A recursive binary search function. // It returns location of x in given // array arr[l..r] is present, // otherwise -1 static int binarySearch(int arr[], int start, int end, int x) { boolean isAsc = arr[start] < arr[end]; if (end >= start) { int middle = start + (end - start) / 2; // If the element is present // at the middle itself if (arr[middle] == x) return middle; if (isAsc == true) { // If element is smaller than mid, // then it can only be // present in left subarray if (arr[middle] > x) return binarySearch(arr, start, middle - 1, x); // Else the element can only be present // in right subarray return binarySearch(arr, middle + 1, end, x); } else { if (arr[middle] < x) return binarySearch(arr, start, middle - 1, x); // Else the element can only be present // in left subarray return binarySearch(arr, middle + 1, end, x); } } // Element not found return -1; } // Driver Code public static void main(String[] args) { int arr[] = { 40, 10, 5, 2, 1 }; int x = 10; int n = arr.length; System.out.print(binarySearch(arr, 0, n - 1, x)); }} // This code is contributed by Rajput-Ji",
"e": 12682,
"s": 11334,
"text": null
},
{
"code": "# Python program for the above approach # A recursive binary search function.# It returns location of x in given# array arr[l..r] is present,# otherwise -1def binarySearch(arr, start, end, x): isAsc = arr[start] < arr[end] if (end >= start): middle = (int)(start + (end - start) / 2) # If the element is present # at the middle itself if (arr[middle] == x): return middle if (isAsc == True): # If element is smaller than mid, # then it can only be # present in left subarray if (arr[middle] > x): return binarySearch( arr, start, middle - 1, x) # Else the element can only be present # in right subarray return binarySearch(arr, middle + 1, end, x) else: if (arr[middle] < x): return binarySearch(arr, start, middle - 1, x) # Else the element can only be present # in left subarray return binarySearch(arr, middle + 1, end, x) # Element not found return -1 # Driver Code arr = [40, 10, 5, 2, 1]x = 10n = len(arr)print(binarySearch(arr, 0, n - 1, x)) # This code is contributed by Taranpreet",
"e": 14047,
"s": 12682,
"text": null
},
{
"code": "// C# program for the above approachusing System; public class GFG { // A recursive binary search function. // It returns location of x in given // array arr[l..r] is present, // otherwise -1 static int binarySearch(int []arr, int start, int end, int x) { bool isAsc = arr[start] < arr[end]; if (end >= start) { int middle = start + (end - start) / 2; // If the element is present // at the middle itself if (arr[middle] == x) return middle; if (isAsc == true) { // If element is smaller than mid, // then it can only be // present in left subarray if (arr[middle] > x) return binarySearch(arr, start, middle - 1, x); // Else the element can only be present // in right subarray return binarySearch(arr, middle + 1, end, x); } else { if (arr[middle] < x) return binarySearch(arr, start, middle - 1, x); // Else the element can only be present // in left subarray return binarySearch(arr, middle + 1, end, x); } } // Element not found return -1; } // Driver Code public static void Main(String[] args) { int []arr = { 40, 10, 5, 2, 1 }; int x = 10; int n = arr.Length; Console.Write(binarySearch(arr, 0, n - 1, x)); }} // This code contributed by Rajput-Ji",
"e": 15385,
"s": 14047,
"text": null
},
{
"code": "<script>// javascript program for the above approach // A recursive binary search function. // It returns location of x in given // array arr[l..r] is present, // otherwise -1 function binarySearch(arr , start , end , x) { let isAsc = arr[start] < arr[end]; if (end >= start) { var middle = start + parseInt((end - start) / 2); // If the element is present // at the middle itself if (arr[middle] == x) return middle; if (isAsc == true) { // If element is smaller than mid, // then it can only be // present in left subarray if (arr[middle] > x) return binarySearch(arr, start, middle - 1, x); // Else the element can only be present // in right subarray return binarySearch(arr, middle + 1, end, x); } else { if (arr[middle] < x) return binarySearch(arr, start, middle - 1, x); // Else the element can only be present // in left subarray return binarySearch(arr, middle + 1, end, x); } } // Element not found return -1; } // Driver Code var arr = [ 40, 10, 5, 2, 1 ]; var x = 10; var n = arr.length; document.write(binarySearch(arr, 0, n - 1, x)); // This code is contributed by Rajput-Ji</script>",
"e": 16871,
"s": 15385,
"text": null
},
{
"code": null,
"e": 16876,
"s": 16874,
"text": "1"
},
{
"code": null,
"e": 16929,
"s": 16880,
"text": "Time Complexity: O(log(N)).Auxiliary Space: O(1)"
},
{
"code": null,
"e": 16941,
"s": 16931,
"text": "sanjoy_62"
},
{
"code": null,
"e": 16955,
"s": 16941,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 16965,
"s": 16955,
"text": "code_hunt"
},
{
"code": null,
"e": 16975,
"s": 16965,
"text": "samim2000"
},
{
"code": null,
"e": 16985,
"s": 16975,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 16996,
"s": 16985,
"text": "singhh3010"
},
{
"code": null,
"e": 17010,
"s": 16996,
"text": "Binary Search"
},
{
"code": null,
"e": 17029,
"s": 17010,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 17039,
"s": 17029,
"text": "Searching"
},
{
"code": null,
"e": 17049,
"s": 17039,
"text": "Searching"
},
{
"code": null,
"e": 17068,
"s": 17049,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 17082,
"s": 17068,
"text": "Binary Search"
}
] |
How to find Nth highest salary from a table
|
17 Jan, 2022
Finding Nth highest salary in a table is the most common question asked in interviews. Here is a way to do this task using dense_rank() function.
Consider the following table: Employee
Query :
select * from(
select ename, sal, dense_rank()
over(order by sal desc)r from Employee)
where r=&n;
To find to the 2nd highest sal set n = 2
To find 3rd highest sal set n = 3 and so on.
Output :
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.
DENSE_RANK :
DENSE_RANK computes the rank of a row in an ordered group of rows and returns the rank as a NUMBER. The ranks are consecutive integers beginning with 1.This function accepts arguments as any numeric data type and returns NUMBER.As an analytic function, DENSE_RANK computes the rank of each row returned from a query with respect to the other rows, based on the values of the value_exprs in the order_by_clause.In the above query the rank is returned based on sal of the employee table. In case of tie, it assigns equal rank to all the rows.
DENSE_RANK computes the rank of a row in an ordered group of rows and returns the rank as a NUMBER. The ranks are consecutive integers beginning with 1.
This function accepts arguments as any numeric data type and returns NUMBER.
As an analytic function, DENSE_RANK computes the rank of each row returned from a query with respect to the other rows, based on the values of the value_exprs in the order_by_clause.
In the above query the rank is returned based on sal of the employee table. In case of tie, it assigns equal rank to all the rows.
Alternate Solution :—————————————————————————————————————————————————————————————————————–
CREATE TABLE `Employee` (
`ENAME` varchar(225) COLLATE utf8_unicode_ci NOT NULL,
`SAL` bigint(20) unsigned NOT NULL,
PRIMARY KEY (`ENAME`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
————————————————————————————————————————————————————-
6th highest
mysql> select * from ((select * from Employee
ORDER BY `sal` DESC limit 6 ) AS T)
ORDER BY T.`sal` ASC limit 1;
Alternate use of Limit:
select * from Employee ORDER BY `sal` ASC limit 5,1; // will return 6th highest
+-------+-----+
| ENAME | SAL |
+-------+-----+
| B | 300 |
+-------+-----+
1 row in set (0.00 sec)
——————————————————————————————————————————————————–
mysql> select * from Employee;
+-------+-----+
| ENAME | SAL |
+-------+-----+
| A | 100 |
| B | 300 |
| C | 200 |
| D | 500 |
| F | 400 |
| G | 600 |
| H | 700 |
| I | 800 |
+-------+-----+
8 rows in set (0.00 sec)
Thanks to Vijay for suggesting this alternate solution.
Alternate Solution –Suppose the task is to find the employee with the Nth highest salary from the above table. We can do this as follows:
Find the employees with top N distinct salaries.Find the lowest salary among the salaries fetched by the above query, this will give us the Nth highest salary.Find the details of the employee whose salary is the lowest salary fetched by the above query.
Find the employees with top N distinct salaries.
Find the lowest salary among the salaries fetched by the above query, this will give us the Nth highest salary.
Find the details of the employee whose salary is the lowest salary fetched by the above query.
Query:
SELECT * FROM Employee WHERE sal =
(
SELECT MIN(sal) FROM Employee
WHERE sal IN (
SELECT DISTINCT TOP N
sal FROM Employee
ORDER BY sal DESC
)
)
The above query will fetch the details of the employee with the Nth highest salary. Let us see how:
Consider N = 4.
Starting with the most inner query, the query: “SELECT DISTINCT TOP 4 sal FROM Employee ORDER BY sal DESC” will produce the below result:
51000
39800
35000
31500
The next outer query is: “SELECT MIN(sal) FROM Employee WHERE sal IN ( Result_Set_of_Previous_Query )“. This will return the below result:
31500
You can see that the above returned result is the required 4th highest salary.
Next is the most outer query, which is: “SELECT * FROM Employee WHERE sal = Result_of_Previous_Query“. This query will return the details of employees with 4th highest salary.
________________________
ename sal
________________________
F | 31500
|
________________________
Another Solution –Here N = nth Highest Salary eg. 3rd Highest salary : N=3 .
SELECT ename,sal from Employee e1 where
N-1 = (SELECT COUNT(DISTINCT sal)from Employee e2 where e2.sal > e1.sal)
Solution using Limit :
Select Salary from table_name order by Salary DESC limit n-1,1;
Here we are ordering our salary in descending order so we will get highest salary first and then subsequently lower salaries.
Limit clause has two components, First component is to skip number of rows from top and second component is display number of rows we want.
let us see with an example :
To find 4th Highest salary query will be :
Select Salary from table_name order by Salary DESC limit 3,1;
Here we are skipping 3 rows from Top and returning only 1 row after skipping .
You can also find names of employees having Nth Highest Salary
Select Emp_name from table_name where Salary =( Select Salary from table_name order by Salary DESC limit n-1,1);
There can be another question like find Nth Lowest Salary . In order to that , just reverse order using ASC ( if you don’t specify by default column will be ordered in ascending order).
Select Salary from table_name order by Salary limit n-1,1;
16. Nth highest salary (Top 50 SQL Interview Questions) | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribers16. Nth highest salary (Top 50 SQL Interview Questions) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:36•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=orEkHRYo6jU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
&t=176s
This article is contributed by Rishav Shandilya. 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.
real1107055
RohanPrajapati
rajgirisanket
unikam18
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
Difference between DELETE, DROP and TRUNCATE
Difference between SQL and NoSQL
Window functions in SQL
MySQL | Group_CONCAT() Function
Difference between DELETE and TRUNCATE
Difference between DDL and DML in DBMS
SQL Correlated Subqueries
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Jan, 2022"
},
{
"code": null,
"e": 201,
"s": 54,
"text": "Finding Nth highest salary in a table is the most common question asked in interviews. Here is a way to do this task using dense_rank() function. "
},
{
"code": null,
"e": 241,
"s": 201,
"text": "Consider the following table: Employee "
},
{
"code": null,
"e": 252,
"s": 243,
"text": "Query : "
},
{
"code": null,
"e": 440,
"s": 252,
"text": "select * from(\nselect ename, sal, dense_rank() \nover(order by sal desc)r from Employee) \nwhere r=&n;\n\nTo find to the 2nd highest sal set n = 2\nTo find 3rd highest sal set n = 3 and so on."
},
{
"code": null,
"e": 451,
"s": 440,
"text": "Output : "
},
{
"code": null,
"e": 460,
"s": 451,
"text": "Chapters"
},
{
"code": null,
"e": 487,
"s": 460,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 537,
"s": 487,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 560,
"s": 537,
"text": "captions off, selected"
},
{
"code": null,
"e": 568,
"s": 560,
"text": "English"
},
{
"code": null,
"e": 592,
"s": 568,
"text": "This is a modal window."
},
{
"code": null,
"e": 661,
"s": 592,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 683,
"s": 661,
"text": "End of dialog window."
},
{
"code": null,
"e": 699,
"s": 685,
"text": "DENSE_RANK : "
},
{
"code": null,
"e": 1242,
"s": 699,
"text": "DENSE_RANK computes the rank of a row in an ordered group of rows and returns the rank as a NUMBER. The ranks are consecutive integers beginning with 1.This function accepts arguments as any numeric data type and returns NUMBER.As an analytic function, DENSE_RANK computes the rank of each row returned from a query with respect to the other rows, based on the values of the value_exprs in the order_by_clause.In the above query the rank is returned based on sal of the employee table. In case of tie, it assigns equal rank to all the rows. "
},
{
"code": null,
"e": 1395,
"s": 1242,
"text": "DENSE_RANK computes the rank of a row in an ordered group of rows and returns the rank as a NUMBER. The ranks are consecutive integers beginning with 1."
},
{
"code": null,
"e": 1472,
"s": 1395,
"text": "This function accepts arguments as any numeric data type and returns NUMBER."
},
{
"code": null,
"e": 1655,
"s": 1472,
"text": "As an analytic function, DENSE_RANK computes the rank of each row returned from a query with respect to the other rows, based on the values of the value_exprs in the order_by_clause."
},
{
"code": null,
"e": 1788,
"s": 1655,
"text": "In the above query the rank is returned based on sal of the employee table. In case of tie, it assigns equal rank to all the rows. "
},
{
"code": null,
"e": 1880,
"s": 1788,
"text": "Alternate Solution :—————————————————————————————————————————————————————————————————————– "
},
{
"code": null,
"e": 2086,
"s": 1880,
"text": "CREATE TABLE `Employee` ( \n`ENAME` varchar(225) COLLATE utf8_unicode_ci NOT NULL, \n`SAL` bigint(20) unsigned NOT NULL, \nPRIMARY KEY (`ENAME`) \n) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; "
},
{
"code": null,
"e": 2141,
"s": 2086,
"text": "————————————————————————————————————————————————————- "
},
{
"code": null,
"e": 2493,
"s": 2141,
"text": "6th highest\nmysql> select * from ((select * from Employee \n ORDER BY `sal` DESC limit 6 ) AS T) \n ORDER BY T.`sal` ASC limit 1;\nAlternate use of Limit:\nselect * from Employee ORDER BY `sal` ASC limit 5,1; // will return 6th highest \n\n\n+-------+-----+\n| ENAME | SAL |\n+-------+-----+\n| B | 300 |\n+-------+-----+\n1 row in set (0.00 sec) "
},
{
"code": null,
"e": 2546,
"s": 2493,
"text": "——————————————————————————————————————————————————– "
},
{
"code": null,
"e": 2795,
"s": 2546,
"text": "mysql> select * from Employee;\n+-------+-----+\n| ENAME | SAL |\n+-------+-----+\n| A | 100 |\n| B | 300 |\n| C | 200 |\n| D | 500 |\n| F | 400 |\n| G | 600 |\n| H | 700 |\n| I | 800 |\n+-------+-----+\n8 rows in set (0.00 sec) "
},
{
"code": null,
"e": 2853,
"s": 2795,
"text": "Thanks to Vijay for suggesting this alternate solution. "
},
{
"code": null,
"e": 2992,
"s": 2853,
"text": "Alternate Solution –Suppose the task is to find the employee with the Nth highest salary from the above table. We can do this as follows: "
},
{
"code": null,
"e": 3246,
"s": 2992,
"text": "Find the employees with top N distinct salaries.Find the lowest salary among the salaries fetched by the above query, this will give us the Nth highest salary.Find the details of the employee whose salary is the lowest salary fetched by the above query."
},
{
"code": null,
"e": 3295,
"s": 3246,
"text": "Find the employees with top N distinct salaries."
},
{
"code": null,
"e": 3407,
"s": 3295,
"text": "Find the lowest salary among the salaries fetched by the above query, this will give us the Nth highest salary."
},
{
"code": null,
"e": 3502,
"s": 3407,
"text": "Find the details of the employee whose salary is the lowest salary fetched by the above query."
},
{
"code": null,
"e": 3511,
"s": 3502,
"text": "Query: "
},
{
"code": null,
"e": 3840,
"s": 3511,
"text": "SELECT * FROM Employee WHERE sal = \n (\n SELECT MIN(sal) FROM Employee \n WHERE sal IN (\n SELECT DISTINCT TOP N\n sal FROM Employee \n ORDER BY sal DESC\n )\n )"
},
{
"code": null,
"e": 3941,
"s": 3840,
"text": "The above query will fetch the details of the employee with the Nth highest salary. Let us see how: "
},
{
"code": null,
"e": 3957,
"s": 3941,
"text": "Consider N = 4."
},
{
"code": null,
"e": 4097,
"s": 3957,
"text": "Starting with the most inner query, the query: “SELECT DISTINCT TOP 4 sal FROM Employee ORDER BY sal DESC” will produce the below result: "
},
{
"code": null,
"e": 4121,
"s": 4097,
"text": "51000\n39800\n35000\n31500"
},
{
"code": null,
"e": 4260,
"s": 4121,
"text": "The next outer query is: “SELECT MIN(sal) FROM Employee WHERE sal IN ( Result_Set_of_Previous_Query )“. This will return the below result:"
},
{
"code": null,
"e": 4266,
"s": 4260,
"text": "31500"
},
{
"code": null,
"e": 4345,
"s": 4266,
"text": "You can see that the above returned result is the required 4th highest salary."
},
{
"code": null,
"e": 4523,
"s": 4345,
"text": "Next is the most outer query, which is: “SELECT * FROM Employee WHERE sal = Result_of_Previous_Query“. This query will return the details of employees with 4th highest salary. "
},
{
"code": null,
"e": 4656,
"s": 4523,
"text": "________________________\nename sal\n________________________\n F | 31500\n |\n________________________"
},
{
"code": null,
"e": 4733,
"s": 4656,
"text": "Another Solution –Here N = nth Highest Salary eg. 3rd Highest salary : N=3 ."
},
{
"code": null,
"e": 4856,
"s": 4733,
"text": "SELECT ename,sal from Employee e1 where \n N-1 = (SELECT COUNT(DISTINCT sal)from Employee e2 where e2.sal > e1.sal) "
},
{
"code": null,
"e": 4880,
"s": 4856,
"text": "Solution using Limit : "
},
{
"code": null,
"e": 4948,
"s": 4880,
"text": " Select Salary from table_name order by Salary DESC limit n-1,1;"
},
{
"code": null,
"e": 5083,
"s": 4948,
"text": " Here we are ordering our salary in descending order so we will get highest salary first and then subsequently lower salaries. "
},
{
"code": null,
"e": 5233,
"s": 5083,
"text": " Limit clause has two components, First component is to skip number of rows from top and second component is display number of rows we want. "
},
{
"code": null,
"e": 5265,
"s": 5233,
"text": " let us see with an example :"
},
{
"code": null,
"e": 5312,
"s": 5265,
"text": " To find 4th Highest salary query will be :"
},
{
"code": null,
"e": 5375,
"s": 5312,
"text": " Select Salary from table_name order by Salary DESC limit 3,1;"
},
{
"code": null,
"e": 5458,
"s": 5375,
"text": " Here we are skipping 3 rows from Top and returning only 1 row after skipping ."
},
{
"code": null,
"e": 5523,
"s": 5458,
"text": " You can also find names of employees having Nth Highest Salary "
},
{
"code": null,
"e": 5636,
"s": 5523,
"text": "Select Emp_name from table_name where Salary =( Select Salary from table_name order by Salary DESC limit n-1,1);"
},
{
"code": null,
"e": 5822,
"s": 5636,
"text": "There can be another question like find Nth Lowest Salary . In order to that , just reverse order using ASC ( if you don’t specify by default column will be ordered in ascending order)."
},
{
"code": null,
"e": 5882,
"s": 5822,
"text": " Select Salary from table_name order by Salary limit n-1,1;"
},
{
"code": null,
"e": 6810,
"s": 5882,
"text": "16. Nth highest salary (Top 50 SQL Interview Questions) | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribers16. Nth highest salary (Top 50 SQL Interview Questions) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:36•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=orEkHRYo6jU\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 6819,
"s": 6810,
"text": "&t=176s "
},
{
"code": null,
"e": 7119,
"s": 6819,
"text": "This article is contributed by Rishav Shandilya. 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."
},
{
"code": null,
"e": 7131,
"s": 7119,
"text": "real1107055"
},
{
"code": null,
"e": 7146,
"s": 7131,
"text": "RohanPrajapati"
},
{
"code": null,
"e": 7160,
"s": 7146,
"text": "rajgirisanket"
},
{
"code": null,
"e": 7169,
"s": 7160,
"text": "unikam18"
},
{
"code": null,
"e": 7173,
"s": 7169,
"text": "SQL"
},
{
"code": null,
"e": 7177,
"s": 7173,
"text": "SQL"
},
{
"code": null,
"e": 7275,
"s": 7177,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7286,
"s": 7275,
"text": "CTE in SQL"
},
{
"code": null,
"e": 7352,
"s": 7286,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 7376,
"s": 7352,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 7421,
"s": 7376,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 7454,
"s": 7421,
"text": "Difference between SQL and NoSQL"
},
{
"code": null,
"e": 7478,
"s": 7454,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 7510,
"s": 7478,
"text": "MySQL | Group_CONCAT() Function"
},
{
"code": null,
"e": 7549,
"s": 7510,
"text": "Difference between DELETE and TRUNCATE"
},
{
"code": null,
"e": 7588,
"s": 7549,
"text": "Difference between DDL and DML in DBMS"
}
] |
Ternary number system or Base 3 numbers
|
18 Nov, 2021
A number system can be considered as a mathematical notation of numbers using a set of digits or symbols. In simpler words, the number system is a method of representing numbers. Every number system is identified with the help of its base or radix.
For example, Binary, Octal, Decimal and Hexadecimal Number systems are used in microprocessor programming. In this article, one such number system is discussed.
Ternary Number System: If the Base value of a number system is 3, then this representation is known as a ternary representation. The digits in this system are 0, 1, and 2. There is also a number system called Balanced Ternary which comprises the digits −1, 0 and +1. The Ternary representation of a number is compact than of binary number system.
Steps to Convert Decimal to Ternary:
Divide the number by 3.Get the integer quotient for the next iteration.Get the remainder for the ternary digit.Repeat the steps until the quotient is equal to 0.
Divide the number by 3.
Get the integer quotient for the next iteration.
Get the remainder for the ternary digit.
Repeat the steps until the quotient is equal to 0.
For example: let N = 101. The following image illustrates the step by step conversion of 10110 to the base-3.
Below is the implementation for the Decimal to Binary and Vice-Versa:
C++
Java
Python3
C#
Javascript
// C++ program to convert decimal// number to ternary number #include <cstdio>#include <iostream>#include <math.h>using namespace std; // Function to convert a decimal// number to a ternary numbervoid convertToTernary(int N){ // Base case if (N == 0) return; // Finding the remainder // when N is divided by 3 int x = N % 3; N /= 3; if (x < 0) N += 1; // Recursive function to // call the function for // the integer division // of the value N/3 convertToTernary(N); // Handling the negative cases if (x < 0) cout << x + (3 * -1); else cout << x;} // Function to convert the decimal to ternaryvoid convert(int Decimal){ cout << "Ternary number of " << Decimal << " is: "; // If the number is greater // than 0, compute the // ternary representation // of the number if (Decimal != 0) { convertToTernary(Decimal); } else cout << "0" << endl;} // Driver codeint main(){ int Decimal = 2747; convert(Decimal); return 0;}
// Java program to convert decimal// number to ternary numberimport java.io.*; class GFG{ // Function to convert a decimal// number to a ternary numberstatic void convertToTernary(int N){ // Base case if (N == 0) return; // Finding the remainder // when N is divided by 3 int x = N % 3; N /= 3; if (x < 0) N += 1; // Recursive function to // call the function for // the integer division // of the value N/3 convertToTernary(N); // Handling the negative cases if (x < 0) System.out.print( x + (3 * -1)); else System.out.print( x);} // Function to convert the decimal to ternarystatic void convert(int Decimal){ System.out.print("Ternary number of " +Decimal +" is: "); // If the number is greater // than 0, compute the // ternary representation // of the number if (Decimal != 0) { convertToTernary(Decimal); } else System.out.println("0" );} // Driver Codepublic static void main (String[] args){ int Decimal = 2747; convert(Decimal); }} // This code is contributed by shivanisinghss2110
# Python3 program to convert decimal# number to ternary number # Function to convert a decimal# number to a ternary numberdef convertToTernary(N): # Base case if (N == 0): return; # Finding the remainder # when N is divided by 3 x = N % 3; N //= 3; if (x < 0): N += 1; # Recursive function to # call the function for # the integer division # of the value N/3 convertToTernary(N); # Handling the negative cases if (x < 0): print(x + (3 * -1), end = ""); else: print(x, end = ""); # Function to convert the# decimal to ternarydef convert(Decimal): print("Ternary number of ", Decimal, " is: ", end = ""); # If the number is greater # than 0, compute the # ternary representation # of the number if (Decimal != 0): convertToTernary(Decimal); else: print("0", end = ""); # Driver Codeif __name__ == '__main__': Decimal = 2747; convert(Decimal); # This code is contributed by Rajput-Ji
// C# program to convert decimal// number to ternary numberusing System; class GFG{ // Function to convert a decimal // number to a ternary number static void convertToTernary(int N) { // Base case if (N == 0) return; // Finding the remainder // when N is divided by 3 int x = N % 3; N /= 3; if (x < 0) N += 1; // Recursive function to // call the function for // the integer division // of the value N/3 convertToTernary(N); // Handling the negative cases if (x < 0) Console.Write( x + (3 * -1)); else Console.Write( x); } // Function to convert the decimal to ternary static void convert(int Decimal) { Console.Write("Ternary number of " +Decimal +" is: "); // If the number is greater // than 0, compute the // ternary representation // of the number if (Decimal != 0) { convertToTernary(Decimal); } else Console.WriteLine("0" ); } // Driver Code public static void Main (string[] args) { int Decimal = 2747; convert(Decimal); }} // This code is contributed by AnkitRai01
<script> // Javascript program to convert decimal // number to ternary number // Function to convert a decimal // number to a ternary number function convertToTernary(N) { // Base case if (N == 0) return; // Finding the remainder // when N is divided by 3 let x = N % 3; N = parseInt(N / 3, 10); if (x < 0) N += 1; // Recursive function to // call the function for // the integer division // of the value N/3 convertToTernary(N); // Handling the negative cases if (x < 0) document.write(x + (3 * -1)); else document.write(x); } // Function to convert the decimal to ternary function convert(Decimal) { document.write("Ternary number of " + Decimal + " is: "); // If the number is greater // than 0, compute the // ternary representation // of the number if (Decimal != 0) { convertToTernary(Decimal); } else document.write("0" + "</br>"); } let Decimal = 2747; convert(Decimal); // This code is contributed by divyeshrabadiya07.</script>
Ternary number of 2747 is: 10202202
Time Complexity: O(log3N)
Auxiliary Space: O(log3N)
Steps to Convert Ternary to Decimal:
Connect each digit from the ternary number with its corresponding power of three.Multiply each digit with its corresponding power of three and Add up all of the numbers you got.
Connect each digit from the ternary number with its corresponding power of three.
Multiply each digit with its corresponding power of three and Add up all of the numbers you got.
For example: let N = 10202. The following image illustrates the step by step conversion of 102023 to the base-10.
Below is the implementation for the Decimal to Binary and Vice-Versa:
C++
Java
Python3
C#
Javascript
// C++ program to convert a// ternary number to decimal number #include <cstdio>#include <iostream>#include <math.h>using namespace std; // Function to convert a ternary// number to a decimal numbervoid convertToDecimal(int N){ cout << "Decimal number of " << N << " is: "; // If the number is greater than 0, // compute the decimal // representation of the number if (N != 0) { int decimalNumber = 0, i = 0, remainder; // Loop to iterate through // the number while (N != 0) { remainder = N % 10; N /= 10; // Computing the decimal digit decimalNumber += remainder * pow(3, i); ++i; } cout << decimalNumber << endl; } else cout << "0" << endl;} // Driver codeint main(){ int Ternary = 10202202; convertToDecimal(Ternary); return 0;}
// Java program to convert a// ternary number to decimal numberclass GFG{ // Function to convert a ternary// number to a decimal numberstatic void convertToDecimal(int N){ System.out.print("Decimal number of " + N + " is: "); // If the number is greater than 0, // compute the decimal // representation of the number if (N != 0) { int decimalNumber = 0, i = 0, remainder; // Loop to iterate through // the number while (N != 0) { remainder = N % 10; N /= 10; // Computing the decimal digit decimalNumber += remainder * Math.pow(3, i); ++i; } System.out.print(decimalNumber + "\n"); } else System.out.print("0" + "\n");} // Driver codepublic static void main(String[] args){ int Ternary = 10202202; convertToDecimal(Ternary);}} // This code is contributed by Rajput-Ji
# Python3 program to convert a# ternary number to decimal numberimport math; # Function to convert a ternary# number to a decimal numberdef convertToDecimal(N): print("Decimal number of", N, "is:", end = " "); # If the number is greater than 0, # compute the decimal # representation of the number if (N != 0): decimalNumber = 0; i = 0; remainder = 0; # Loop to iterate through # the number while (N != 0): remainder = N % 10; N = N // 10; # Computing the decimal digit decimalNumber += remainder * math.pow(3, i); i += 1; print(decimalNumber); else: print("0"); # Driver codeTernary = 10202202;convertToDecimal(Ternary); # This code is contributed by Code_Mech
// C# program to convert a ternary// number to decimal numberusing System; class GFG{ // Function to convert a ternary// number to a decimal numberstatic void convertToDecimal(int N){ Console.Write("Decimal number of " + N + " is: "); // If the number is greater than // 0, compute the decimal // representation of the number if (N != 0) { int decimalNumber = 0; int i = 0, remainder; // Loop to iterate through // the number while (N != 0) { remainder = N % 10; N /= 10; // Computing the decimal digit decimalNumber += remainder * (int)Math.Pow(3, i); ++i; } Console.Write(decimalNumber + "\n"); } else Console.Write("0" + "\n");} // Driver codepublic static void Main(){ int Ternary = 10202202; convertToDecimal(Ternary);}} // This code is contributed by shivanisinghss2110
<script> // Javascript program to convert a ternary// number to decimal number // Function to convert a ternary// number to a decimal numberfunction convertToDecimal(N){ document.write("Decimal number of " + N + " is: "); // If the number is greater than // 0, compute the decimal // representation of the number if (N != 0) { let decimalNumber = 0; let i = 0, remainder; // Loop to iterate through // the number while (N != 0) { remainder = N % 10; N = parseInt(N / 10, 10); // Computing the decimal digit decimalNumber += remainder * Math.pow(3, i); ++i; } document.write(decimalNumber + "</br>"); } else document.write("0" + "</br>");} // Driver codelet Ternary = 10202202; convertToDecimal(Ternary); // This code is contributed by divyesh072019 </script>
Output:
Decimal number of 10202202 is: 2747
Time Complexity: O(log10N)
Auxiliary Space: O(1)
shivanisinghss2110
ankthon
Rajput-Ji
Code_Mech
divyeshrabadiya07
divyesh072019
subham348
base-conversion
number-theory
Mathematical
number-theory
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 Nov, 2021"
},
{
"code": null,
"e": 304,
"s": 54,
"text": "A number system can be considered as a mathematical notation of numbers using a set of digits or symbols. In simpler words, the number system is a method of representing numbers. Every number system is identified with the help of its base or radix. "
},
{
"code": null,
"e": 465,
"s": 304,
"text": "For example, Binary, Octal, Decimal and Hexadecimal Number systems are used in microprocessor programming. In this article, one such number system is discussed."
},
{
"code": null,
"e": 813,
"s": 465,
"text": "Ternary Number System: If the Base value of a number system is 3, then this representation is known as a ternary representation. The digits in this system are 0, 1, and 2. There is also a number system called Balanced Ternary which comprises the digits −1, 0 and +1. The Ternary representation of a number is compact than of binary number system. "
},
{
"code": null,
"e": 851,
"s": 813,
"text": "Steps to Convert Decimal to Ternary: "
},
{
"code": null,
"e": 1013,
"s": 851,
"text": "Divide the number by 3.Get the integer quotient for the next iteration.Get the remainder for the ternary digit.Repeat the steps until the quotient is equal to 0."
},
{
"code": null,
"e": 1037,
"s": 1013,
"text": "Divide the number by 3."
},
{
"code": null,
"e": 1086,
"s": 1037,
"text": "Get the integer quotient for the next iteration."
},
{
"code": null,
"e": 1127,
"s": 1086,
"text": "Get the remainder for the ternary digit."
},
{
"code": null,
"e": 1178,
"s": 1127,
"text": "Repeat the steps until the quotient is equal to 0."
},
{
"code": null,
"e": 1290,
"s": 1178,
"text": "For example: let N = 101. The following image illustrates the step by step conversion of 10110 to the base-3. "
},
{
"code": null,
"e": 1361,
"s": 1290,
"text": "Below is the implementation for the Decimal to Binary and Vice-Versa: "
},
{
"code": null,
"e": 1365,
"s": 1361,
"text": "C++"
},
{
"code": null,
"e": 1370,
"s": 1365,
"text": "Java"
},
{
"code": null,
"e": 1378,
"s": 1370,
"text": "Python3"
},
{
"code": null,
"e": 1381,
"s": 1378,
"text": "C#"
},
{
"code": null,
"e": 1392,
"s": 1381,
"text": "Javascript"
},
{
"code": "// C++ program to convert decimal// number to ternary number #include <cstdio>#include <iostream>#include <math.h>using namespace std; // Function to convert a decimal// number to a ternary numbervoid convertToTernary(int N){ // Base case if (N == 0) return; // Finding the remainder // when N is divided by 3 int x = N % 3; N /= 3; if (x < 0) N += 1; // Recursive function to // call the function for // the integer division // of the value N/3 convertToTernary(N); // Handling the negative cases if (x < 0) cout << x + (3 * -1); else cout << x;} // Function to convert the decimal to ternaryvoid convert(int Decimal){ cout << \"Ternary number of \" << Decimal << \" is: \"; // If the number is greater // than 0, compute the // ternary representation // of the number if (Decimal != 0) { convertToTernary(Decimal); } else cout << \"0\" << endl;} // Driver codeint main(){ int Decimal = 2747; convert(Decimal); return 0;}",
"e": 2443,
"s": 1392,
"text": null
},
{
"code": "// Java program to convert decimal// number to ternary numberimport java.io.*; class GFG{ // Function to convert a decimal// number to a ternary numberstatic void convertToTernary(int N){ // Base case if (N == 0) return; // Finding the remainder // when N is divided by 3 int x = N % 3; N /= 3; if (x < 0) N += 1; // Recursive function to // call the function for // the integer division // of the value N/3 convertToTernary(N); // Handling the negative cases if (x < 0) System.out.print( x + (3 * -1)); else System.out.print( x);} // Function to convert the decimal to ternarystatic void convert(int Decimal){ System.out.print(\"Ternary number of \" +Decimal +\" is: \"); // If the number is greater // than 0, compute the // ternary representation // of the number if (Decimal != 0) { convertToTernary(Decimal); } else System.out.println(\"0\" );} // Driver Codepublic static void main (String[] args){ int Decimal = 2747; convert(Decimal); }} // This code is contributed by shivanisinghss2110",
"e": 3557,
"s": 2443,
"text": null
},
{
"code": "# Python3 program to convert decimal# number to ternary number # Function to convert a decimal# number to a ternary numberdef convertToTernary(N): # Base case if (N == 0): return; # Finding the remainder # when N is divided by 3 x = N % 3; N //= 3; if (x < 0): N += 1; # Recursive function to # call the function for # the integer division # of the value N/3 convertToTernary(N); # Handling the negative cases if (x < 0): print(x + (3 * -1), end = \"\"); else: print(x, end = \"\"); # Function to convert the# decimal to ternarydef convert(Decimal): print(\"Ternary number of \", Decimal, \" is: \", end = \"\"); # If the number is greater # than 0, compute the # ternary representation # of the number if (Decimal != 0): convertToTernary(Decimal); else: print(\"0\", end = \"\"); # Driver Codeif __name__ == '__main__': Decimal = 2747; convert(Decimal); # This code is contributed by Rajput-Ji",
"e": 4582,
"s": 3557,
"text": null
},
{
"code": "// C# program to convert decimal// number to ternary numberusing System; class GFG{ // Function to convert a decimal // number to a ternary number static void convertToTernary(int N) { // Base case if (N == 0) return; // Finding the remainder // when N is divided by 3 int x = N % 3; N /= 3; if (x < 0) N += 1; // Recursive function to // call the function for // the integer division // of the value N/3 convertToTernary(N); // Handling the negative cases if (x < 0) Console.Write( x + (3 * -1)); else Console.Write( x); } // Function to convert the decimal to ternary static void convert(int Decimal) { Console.Write(\"Ternary number of \" +Decimal +\" is: \"); // If the number is greater // than 0, compute the // ternary representation // of the number if (Decimal != 0) { convertToTernary(Decimal); } else Console.WriteLine(\"0\" ); } // Driver Code public static void Main (string[] args) { int Decimal = 2747; convert(Decimal); }} // This code is contributed by AnkitRai01",
"e": 5870,
"s": 4582,
"text": null
},
{
"code": "<script> // Javascript program to convert decimal // number to ternary number // Function to convert a decimal // number to a ternary number function convertToTernary(N) { // Base case if (N == 0) return; // Finding the remainder // when N is divided by 3 let x = N % 3; N = parseInt(N / 3, 10); if (x < 0) N += 1; // Recursive function to // call the function for // the integer division // of the value N/3 convertToTernary(N); // Handling the negative cases if (x < 0) document.write(x + (3 * -1)); else document.write(x); } // Function to convert the decimal to ternary function convert(Decimal) { document.write(\"Ternary number of \" + Decimal + \" is: \"); // If the number is greater // than 0, compute the // ternary representation // of the number if (Decimal != 0) { convertToTernary(Decimal); } else document.write(\"0\" + \"</br>\"); } let Decimal = 2747; convert(Decimal); // This code is contributed by divyeshrabadiya07.</script>",
"e": 7092,
"s": 5870,
"text": null
},
{
"code": null,
"e": 7128,
"s": 7092,
"text": "Ternary number of 2747 is: 10202202"
},
{
"code": null,
"e": 7156,
"s": 7130,
"text": "Time Complexity: O(log3N)"
},
{
"code": null,
"e": 7182,
"s": 7156,
"text": "Auxiliary Space: O(log3N)"
},
{
"code": null,
"e": 7219,
"s": 7182,
"text": "Steps to Convert Ternary to Decimal:"
},
{
"code": null,
"e": 7397,
"s": 7219,
"text": "Connect each digit from the ternary number with its corresponding power of three.Multiply each digit with its corresponding power of three and Add up all of the numbers you got."
},
{
"code": null,
"e": 7479,
"s": 7397,
"text": "Connect each digit from the ternary number with its corresponding power of three."
},
{
"code": null,
"e": 7576,
"s": 7479,
"text": "Multiply each digit with its corresponding power of three and Add up all of the numbers you got."
},
{
"code": null,
"e": 7692,
"s": 7576,
"text": "For example: let N = 10202. The following image illustrates the step by step conversion of 102023 to the base-10. "
},
{
"code": null,
"e": 7763,
"s": 7692,
"text": "Below is the implementation for the Decimal to Binary and Vice-Versa: "
},
{
"code": null,
"e": 7767,
"s": 7763,
"text": "C++"
},
{
"code": null,
"e": 7772,
"s": 7767,
"text": "Java"
},
{
"code": null,
"e": 7780,
"s": 7772,
"text": "Python3"
},
{
"code": null,
"e": 7783,
"s": 7780,
"text": "C#"
},
{
"code": null,
"e": 7794,
"s": 7783,
"text": "Javascript"
},
{
"code": "// C++ program to convert a// ternary number to decimal number #include <cstdio>#include <iostream>#include <math.h>using namespace std; // Function to convert a ternary// number to a decimal numbervoid convertToDecimal(int N){ cout << \"Decimal number of \" << N << \" is: \"; // If the number is greater than 0, // compute the decimal // representation of the number if (N != 0) { int decimalNumber = 0, i = 0, remainder; // Loop to iterate through // the number while (N != 0) { remainder = N % 10; N /= 10; // Computing the decimal digit decimalNumber += remainder * pow(3, i); ++i; } cout << decimalNumber << endl; } else cout << \"0\" << endl;} // Driver codeint main(){ int Ternary = 10202202; convertToDecimal(Ternary); return 0;}",
"e": 8714,
"s": 7794,
"text": null
},
{
"code": "// Java program to convert a// ternary number to decimal numberclass GFG{ // Function to convert a ternary// number to a decimal numberstatic void convertToDecimal(int N){ System.out.print(\"Decimal number of \" + N + \" is: \"); // If the number is greater than 0, // compute the decimal // representation of the number if (N != 0) { int decimalNumber = 0, i = 0, remainder; // Loop to iterate through // the number while (N != 0) { remainder = N % 10; N /= 10; // Computing the decimal digit decimalNumber += remainder * Math.pow(3, i); ++i; } System.out.print(decimalNumber + \"\\n\"); } else System.out.print(\"0\" + \"\\n\");} // Driver codepublic static void main(String[] args){ int Ternary = 10202202; convertToDecimal(Ternary);}} // This code is contributed by Rajput-Ji",
"e": 9686,
"s": 8714,
"text": null
},
{
"code": "# Python3 program to convert a# ternary number to decimal numberimport math; # Function to convert a ternary# number to a decimal numberdef convertToDecimal(N): print(\"Decimal number of\", N, \"is:\", end = \" \"); # If the number is greater than 0, # compute the decimal # representation of the number if (N != 0): decimalNumber = 0; i = 0; remainder = 0; # Loop to iterate through # the number while (N != 0): remainder = N % 10; N = N // 10; # Computing the decimal digit decimalNumber += remainder * math.pow(3, i); i += 1; print(decimalNumber); else: print(\"0\"); # Driver codeTernary = 10202202;convertToDecimal(Ternary); # This code is contributed by Code_Mech",
"e": 10496,
"s": 9686,
"text": null
},
{
"code": "// C# program to convert a ternary// number to decimal numberusing System; class GFG{ // Function to convert a ternary// number to a decimal numberstatic void convertToDecimal(int N){ Console.Write(\"Decimal number of \" + N + \" is: \"); // If the number is greater than // 0, compute the decimal // representation of the number if (N != 0) { int decimalNumber = 0; int i = 0, remainder; // Loop to iterate through // the number while (N != 0) { remainder = N % 10; N /= 10; // Computing the decimal digit decimalNumber += remainder * (int)Math.Pow(3, i); ++i; } Console.Write(decimalNumber + \"\\n\"); } else Console.Write(\"0\" + \"\\n\");} // Driver codepublic static void Main(){ int Ternary = 10202202; convertToDecimal(Ternary);}} // This code is contributed by shivanisinghss2110",
"e": 11483,
"s": 10496,
"text": null
},
{
"code": "<script> // Javascript program to convert a ternary// number to decimal number // Function to convert a ternary// number to a decimal numberfunction convertToDecimal(N){ document.write(\"Decimal number of \" + N + \" is: \"); // If the number is greater than // 0, compute the decimal // representation of the number if (N != 0) { let decimalNumber = 0; let i = 0, remainder; // Loop to iterate through // the number while (N != 0) { remainder = N % 10; N = parseInt(N / 10, 10); // Computing the decimal digit decimalNumber += remainder * Math.pow(3, i); ++i; } document.write(decimalNumber + \"</br>\"); } else document.write(\"0\" + \"</br>\");} // Driver codelet Ternary = 10202202; convertToDecimal(Ternary); // This code is contributed by divyesh072019 </script>",
"e": 12406,
"s": 11483,
"text": null
},
{
"code": null,
"e": 12414,
"s": 12406,
"text": "Output:"
},
{
"code": null,
"e": 12450,
"s": 12414,
"text": "Decimal number of 10202202 is: 2747"
},
{
"code": null,
"e": 12477,
"s": 12450,
"text": "Time Complexity: O(log10N)"
},
{
"code": null,
"e": 12499,
"s": 12477,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 12518,
"s": 12499,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 12526,
"s": 12518,
"text": "ankthon"
},
{
"code": null,
"e": 12536,
"s": 12526,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 12546,
"s": 12536,
"text": "Code_Mech"
},
{
"code": null,
"e": 12564,
"s": 12546,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 12578,
"s": 12564,
"text": "divyesh072019"
},
{
"code": null,
"e": 12588,
"s": 12578,
"text": "subham348"
},
{
"code": null,
"e": 12604,
"s": 12588,
"text": "base-conversion"
},
{
"code": null,
"e": 12618,
"s": 12604,
"text": "number-theory"
},
{
"code": null,
"e": 12631,
"s": 12618,
"text": "Mathematical"
},
{
"code": null,
"e": 12645,
"s": 12631,
"text": "number-theory"
},
{
"code": null,
"e": 12658,
"s": 12645,
"text": "Mathematical"
}
] |
Python String | replace()
|
08 Jul, 2022
replace() is an inbuilt function in the Python programming language that returns a copy of the string where all occurrences of a substring are replaced with another substring.
Syntax :
string.replace(old, new, count)
Parameters :
old – old substring you want to replace. new – new substring which would replace the old substring.count – the number of times you want to replace the old substring with the new substring. (Optional )
Return Value : It returns a copy of the string where all occurrences of a substring are replaced with another substring.
Note:
If count is not specified then all the occurrences of the old substring are replaced with the new substring.
This method returns the copy of the string i.e. it does not change the original string.
Below is the code demonstrating replace() :
Example 1:
Python3
# Python3 program to demonstrate the # use of replace() method string = "geeks for geeks geeks geeks geeks" # Prints the string by replacing all# geeks by Geeks print(string.replace("geeks", "Geeks")) # Prints the string by replacing only# 3 occurrence of Geeks print(string.replace("geeks", "GeeksforGeeks", 3))
Output :
Geeks for Geeks Geeks Geeks Geeks
GeeksforGeeks for GeeksforGeeks GeeksforGeeks geeks geeks
Example 2:
Python3
# Python3 program to demonstrate the# use of replace() method string = "geeks for geeks geeks geeks geeks" # Prints the string by replacing# e by aprint(string.replace("e", "a")) # Prints the string by replacing only# 3 occurrence of ek by aprint(string.replace("ek", "a", 3))
Output:
gaaks for gaaks gaaks gaaks gaaks
geas for geas geas geeks geeks
nidhi_biet
xav1f6wh5lioybigrv64zv6genhitzictg7xhha5
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Jul, 2022"
},
{
"code": null,
"e": 230,
"s": 52,
"text": "replace() is an inbuilt function in the Python programming language that returns a copy of the string where all occurrences of a substring are replaced with another substring. "
},
{
"code": null,
"e": 240,
"s": 230,
"text": "Syntax : "
},
{
"code": null,
"e": 272,
"s": 240,
"text": "string.replace(old, new, count)"
},
{
"code": null,
"e": 287,
"s": 272,
"text": "Parameters : "
},
{
"code": null,
"e": 490,
"s": 287,
"text": "old – old substring you want to replace. new – new substring which would replace the old substring.count – the number of times you want to replace the old substring with the new substring. (Optional ) "
},
{
"code": null,
"e": 613,
"s": 490,
"text": "Return Value : It returns a copy of the string where all occurrences of a substring are replaced with another substring. "
},
{
"code": null,
"e": 620,
"s": 613,
"text": "Note: "
},
{
"code": null,
"e": 729,
"s": 620,
"text": "If count is not specified then all the occurrences of the old substring are replaced with the new substring."
},
{
"code": null,
"e": 819,
"s": 729,
"text": "This method returns the copy of the string i.e. it does not change the original string. "
},
{
"code": null,
"e": 865,
"s": 819,
"text": "Below is the code demonstrating replace() : "
},
{
"code": null,
"e": 877,
"s": 865,
"text": "Example 1: "
},
{
"code": null,
"e": 885,
"s": 877,
"text": "Python3"
},
{
"code": "# Python3 program to demonstrate the # use of replace() method string = \"geeks for geeks geeks geeks geeks\" # Prints the string by replacing all# geeks by Geeks print(string.replace(\"geeks\", \"Geeks\")) # Prints the string by replacing only# 3 occurrence of Geeks print(string.replace(\"geeks\", \"GeeksforGeeks\", 3))",
"e": 1207,
"s": 885,
"text": null
},
{
"code": null,
"e": 1218,
"s": 1207,
"text": "Output : "
},
{
"code": null,
"e": 1310,
"s": 1218,
"text": "Geeks for Geeks Geeks Geeks Geeks\nGeeksforGeeks for GeeksforGeeks GeeksforGeeks geeks geeks"
},
{
"code": null,
"e": 1321,
"s": 1310,
"text": "Example 2:"
},
{
"code": null,
"e": 1329,
"s": 1321,
"text": "Python3"
},
{
"code": "# Python3 program to demonstrate the# use of replace() method string = \"geeks for geeks geeks geeks geeks\" # Prints the string by replacing# e by aprint(string.replace(\"e\", \"a\")) # Prints the string by replacing only# 3 occurrence of ek by aprint(string.replace(\"ek\", \"a\", 3))",
"e": 1609,
"s": 1329,
"text": null
},
{
"code": null,
"e": 1619,
"s": 1609,
"text": "Output: "
},
{
"code": null,
"e": 1684,
"s": 1619,
"text": "gaaks for gaaks gaaks gaaks gaaks\ngeas for geas geas geeks geeks"
},
{
"code": null,
"e": 1697,
"s": 1686,
"text": "nidhi_biet"
},
{
"code": null,
"e": 1738,
"s": 1697,
"text": "xav1f6wh5lioybigrv64zv6genhitzictg7xhha5"
},
{
"code": null,
"e": 1752,
"s": 1738,
"text": "python-string"
},
{
"code": null,
"e": 1759,
"s": 1752,
"text": "Python"
}
] |
Magic Square
|
The magic square is a square matrix, whose order is odd and where the sum of the elements for each row or each column or each diagonal is same.
The sum of each row or each column or each diagonal can be found using this formula. n(n2+ 1)/2
Here are the rules to construct a magic square −
We will start from the middle column of the first row, of the matrix, and always go to the top left corner to place next number
If the row exceeds, or the row is not in the matrix, then, change the column as left column and place the number at last row of the matrix, and go for top left corner again.
If the column exceeds, or the column is not in the matrix, then change the row as top row and place the number at last column of that matrix, then go to the top left corner again.
When the top left corner is not vacant or both row and column exceeds the range, then place the number at the bottom of the last-placed number.
Input:
The order of the matrix 5
Output:
15 8 1 24 17
16 14 7 5 23
22 20 13 6 4
3 21 19 12 10
9 2 25 18 11
createSquare(mat, r, c)
Input: The matrix.
Output: Row and Column.
Begin
count := 1
fill all elements in mat to 0
range := r * c
i := 0
j := c/2
mat[i, j] := count //center of top row
while count < range, do
increase count by 1
if both i and j crosses the matrix range, then
increase i by 1
else if only i crosses the matrix range, then
i := c – 1
decrease j by 1
else if only j crosses the matrix range, then
j := c – 1
decrease i by 1
else if i and j are in the matrix and element in (i, j) ≠ 0, then
increase i by 1
else
decrease i and j by 1
mat[i, j] := count
done
display the matrix mat
End
#include<iostream>
#include<iomanip>
using namespace std;
void createSquare(int **array, int r, int c) {
int i, j, count = 1, range;
for(i = 0; i<r; i++)
for(j = 0; j<c; j++)
array[i][j] = 0; //initialize all elements with 0
range = r*c;
i = 0;
j = c/2;
array[i][j] = count;
while(count < range) {
count++;
if((i-1) < 0 && (j-1) < 0) //when both row and column crosses the range
i++;
else if((i-1) <0) { //when only row crosses range, set i to last row, and decrease j
i = r-1;
j--;
}else if((j-1) < 0) { //when only col crosses range, set j to last column, and decrease i
j = c-1;
i--;
}else if(array[i-1][j-1] != 0) //when diagonal element is not empty, go to next row
i++;
else{
i--;
j--;
}
array[i][j] = count;
}
// Printing the square
for(i = 0; i<r; i++) {
for(j = 0; j<c; j++)
cout <<setw(3) << array[i][j];
cout << endl;
}
}
main() {
int** matrix;
int row, col;
cout << "Enter the order(odd) of square matrix :";
cin >> row;
col = row;
matrix = new int*[row];
for(int i = 0; i<row; i++) {
matrix[i] = new int[col];
}
createSquare(matrix, row, col);
}
Enter the order(odd) of square matrix :5
15 8 1 24 17
16 14 7 5 23
22 20 13 6 4
3 21 19 12 10
9 2 25 18 11
|
[
{
"code": null,
"e": 1332,
"s": 1187,
"text": "The magic square is a square matrix, whose order is odd and where the sum of the elements for each row or each column or each diagonal is same. "
},
{
"code": null,
"e": 1428,
"s": 1332,
"text": "The sum of each row or each column or each diagonal can be found using this formula. n(n2+ 1)/2"
},
{
"code": null,
"e": 1477,
"s": 1428,
"text": "Here are the rules to construct a magic square −"
},
{
"code": null,
"e": 1605,
"s": 1477,
"text": "We will start from the middle column of the first row, of the matrix, and always go to the top left corner to place next number"
},
{
"code": null,
"e": 1779,
"s": 1605,
"text": "If the row exceeds, or the row is not in the matrix, then, change the column as left column and place the number at last row of the matrix, and go for top left corner again."
},
{
"code": null,
"e": 1959,
"s": 1779,
"text": "If the column exceeds, or the column is not in the matrix, then change the row as top row and place the number at last column of that matrix, then go to the top left corner again."
},
{
"code": null,
"e": 2103,
"s": 1959,
"text": "When the top left corner is not vacant or both row and column exceeds the range, then place the number at the bottom of the last-placed number."
},
{
"code": null,
"e": 2219,
"s": 2103,
"text": "Input:\nThe order of the matrix 5\nOutput:\n15 8 1 24 17\n16 14 7 5 23\n22 20 13 6 4\n3 21 19 12 10\n9 2 25 18 11"
},
{
"code": null,
"e": 2243,
"s": 2219,
"text": "createSquare(mat, r, c)"
},
{
"code": null,
"e": 2262,
"s": 2243,
"text": "Input: The matrix."
},
{
"code": null,
"e": 2286,
"s": 2262,
"text": "Output: Row and Column."
},
{
"code": null,
"e": 2950,
"s": 2286,
"text": "Begin\n count := 1\n fill all elements in mat to 0\n range := r * c\n i := 0\n j := c/2\n mat[i, j] := count //center of top row\n\n while count < range, do\n increase count by 1\n if both i and j crosses the matrix range, then\n increase i by 1\n else if only i crosses the matrix range, then\n i := c – 1\n decrease j by 1\n else if only j crosses the matrix range, then\n j := c – 1\n decrease i by 1\n else if i and j are in the matrix and element in (i, j) ≠ 0, then\n increase i by 1\n else\n decrease i and j by 1\n mat[i, j] := count\n done\n display the matrix mat\nEnd"
},
{
"code": null,
"e": 4263,
"s": 2950,
"text": "#include<iostream>\n#include<iomanip>\nusing namespace std;\n\nvoid createSquare(int **array, int r, int c) {\n int i, j, count = 1, range;\n for(i = 0; i<r; i++)\n for(j = 0; j<c; j++)\n array[i][j] = 0; //initialize all elements with 0\n\n range = r*c;\n i = 0;\n j = c/2;\n array[i][j] = count;\n\n while(count < range) {\n count++;\n if((i-1) < 0 && (j-1) < 0) //when both row and column crosses the range\n i++; \n else if((i-1) <0) { //when only row crosses range, set i to last row, and decrease j\n i = r-1;\n j--;\n }else if((j-1) < 0) { //when only col crosses range, set j to last column, and decrease i\n j = c-1;\n i--; \n }else if(array[i-1][j-1] != 0) //when diagonal element is not empty, go to next row\n i++;\n else{\n i--;\n j--;\n }\n array[i][j] = count;\n }\n\n // Printing the square\n for(i = 0; i<r; i++) {\n for(j = 0; j<c; j++)\n cout <<setw(3) << array[i][j];\n cout << endl;\n }\n}\n\nmain() {\n int** matrix;\n int row, col;\n cout << \"Enter the order(odd) of square matrix :\";\n cin >> row;\n col = row;\n \n matrix = new int*[row];\n \n for(int i = 0; i<row; i++) {\n matrix[i] = new int[col];\n }\n createSquare(matrix, row, col);\n}"
},
{
"code": null,
"e": 4379,
"s": 4263,
"text": "Enter the order(odd) of square matrix :5\n15 8 1 24 17\n16 14 7 5 23\n22 20 13 6 4\n 3 21 19 12 10\n 9 2 25 18 11"
}
] |
Recursive Descent Parser
|
01 Jun, 2021
Prerequisite – Construction of LL(1) Parsing Table, Classification of top down parsers Parsing is the process to determine whether the start symbol can derive the program or not. If the Parsing is successful then the program is a valid program otherwise the program is invalid. There are generally two types of Parsers:
Top-Down Parsers: In this Parsing technique we expand the start symbol to the whole program.Recursive Descent and LL parsers are the Top-Down parsers.Bottom-Up Parsers: In this Parsing technique we reduce the whole program to start symbol.Operator Precedence Parser, LR(0) Parser, SLR Parser, LALR Parser and CLR Parser are the Bottom-Up parsers.
Top-Down Parsers: In this Parsing technique we expand the start symbol to the whole program.Recursive Descent and LL parsers are the Top-Down parsers.
In this Parsing technique we expand the start symbol to the whole program.
Recursive Descent and LL parsers are the Top-Down parsers.
Bottom-Up Parsers: In this Parsing technique we reduce the whole program to start symbol.Operator Precedence Parser, LR(0) Parser, SLR Parser, LALR Parser and CLR Parser are the Bottom-Up parsers.
In this Parsing technique we reduce the whole program to start symbol.
Operator Precedence Parser, LR(0) Parser, SLR Parser, LALR Parser and CLR Parser are the Bottom-Up parsers.
Recursive Descent Parser: It is a kind of Top-Down Parser. A top-down parser builds the parse tree from the top to down, starting with the start non-terminal. A Predictive Parser is a special case of Recursive Descent Parser, where no Back Tracking is required. By carefully writing a grammar means eliminating left recursion and left factoring from it, the resulting grammar will be a grammar that can be parsed by a recursive descent parser.Example:
**Here e is EpsilonFor Recursive Descent Parser, we are going to write one program for every variable.
Example:
Grammar: E --> i E'
E' --> + i E' | e
C
int main(){ // E is a start symbol. E(); // if lookahead = $, it represents the end of the string // Here l is lookahead. if (l == '$') printf("Parsing Successful");} // Definition of E, as per the given productionE(){ if (l == 'i') { match('i'); E'(); }} // Definition of E' as per the given productionE'() { if (l == '+') { match('+'); match('i'); E'(); }//The second condition of E' else if ( l == 'e' ) { match('e'); } return ();} // Match functionmatch(char t){ if (l == t) { l = getchar(); } else printf("Error");}
bibouda512
Ranajit pal
chakkritip
Compiler Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Issues in the design of a code generator
Peephole Optimization in Compiler Design
Directed Acyclic graph in Compiler Design (with examples)
Type Checking in Compiler Design
Difference between Compiler and Interpreter
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n01 Jun, 2021"
},
{
"code": null,
"e": 376,
"s": 54,
"text": "Prerequisite – Construction of LL(1) Parsing Table, Classification of top down parsers Parsing is the process to determine whether the start symbol can derive the program or not. If the Parsing is successful then the program is a valid program otherwise the program is invalid. There are generally two types of Parsers: "
},
{
"code": null,
"e": 723,
"s": 376,
"text": "Top-Down Parsers: In this Parsing technique we expand the start symbol to the whole program.Recursive Descent and LL parsers are the Top-Down parsers.Bottom-Up Parsers: In this Parsing technique we reduce the whole program to start symbol.Operator Precedence Parser, LR(0) Parser, SLR Parser, LALR Parser and CLR Parser are the Bottom-Up parsers."
},
{
"code": null,
"e": 874,
"s": 723,
"text": "Top-Down Parsers: In this Parsing technique we expand the start symbol to the whole program.Recursive Descent and LL parsers are the Top-Down parsers."
},
{
"code": null,
"e": 949,
"s": 874,
"text": "In this Parsing technique we expand the start symbol to the whole program."
},
{
"code": null,
"e": 1008,
"s": 949,
"text": "Recursive Descent and LL parsers are the Top-Down parsers."
},
{
"code": null,
"e": 1205,
"s": 1008,
"text": "Bottom-Up Parsers: In this Parsing technique we reduce the whole program to start symbol.Operator Precedence Parser, LR(0) Parser, SLR Parser, LALR Parser and CLR Parser are the Bottom-Up parsers."
},
{
"code": null,
"e": 1276,
"s": 1205,
"text": "In this Parsing technique we reduce the whole program to start symbol."
},
{
"code": null,
"e": 1384,
"s": 1276,
"text": "Operator Precedence Parser, LR(0) Parser, SLR Parser, LALR Parser and CLR Parser are the Bottom-Up parsers."
},
{
"code": null,
"e": 1836,
"s": 1384,
"text": "Recursive Descent Parser: It is a kind of Top-Down Parser. A top-down parser builds the parse tree from the top to down, starting with the start non-terminal. A Predictive Parser is a special case of Recursive Descent Parser, where no Back Tracking is required. By carefully writing a grammar means eliminating left recursion and left factoring from it, the resulting grammar will be a grammar that can be parsed by a recursive descent parser.Example:"
},
{
"code": null,
"e": 1943,
"s": 1838,
"text": "**Here e is EpsilonFor Recursive Descent Parser, we are going to write one program for every variable. "
},
{
"code": null,
"e": 1990,
"s": 1943,
"text": "Example:\nGrammar: E --> i E'\nE' --> + i E' | e"
},
{
"code": null,
"e": 1994,
"s": 1992,
"text": "C"
},
{
"code": "int main(){ // E is a start symbol. E(); // if lookahead = $, it represents the end of the string // Here l is lookahead. if (l == '$') printf(\"Parsing Successful\");} // Definition of E, as per the given productionE(){ if (l == 'i') { match('i'); E'(); }} // Definition of E' as per the given productionE'() { if (l == '+') { match('+'); match('i'); E'(); }//The second condition of E' else if ( l == 'e' ) { match('e'); } return ();} // Match functionmatch(char t){ if (l == t) { l = getchar(); } else printf(\"Error\");}",
"e": 2630,
"s": 1994,
"text": null
},
{
"code": null,
"e": 2641,
"s": 2630,
"text": "bibouda512"
},
{
"code": null,
"e": 2653,
"s": 2641,
"text": "Ranajit pal"
},
{
"code": null,
"e": 2664,
"s": 2653,
"text": "chakkritip"
},
{
"code": null,
"e": 2680,
"s": 2664,
"text": "Compiler Design"
},
{
"code": null,
"e": 2688,
"s": 2680,
"text": "GATE CS"
},
{
"code": null,
"e": 2786,
"s": 2688,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2827,
"s": 2786,
"text": "Issues in the design of a code generator"
},
{
"code": null,
"e": 2868,
"s": 2827,
"text": "Peephole Optimization in Compiler Design"
},
{
"code": null,
"e": 2926,
"s": 2868,
"text": "Directed Acyclic graph in Compiler Design (with examples)"
},
{
"code": null,
"e": 2959,
"s": 2926,
"text": "Type Checking in Compiler Design"
},
{
"code": null,
"e": 3003,
"s": 2959,
"text": "Difference between Compiler and Interpreter"
},
{
"code": null,
"e": 3023,
"s": 3003,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 3047,
"s": 3023,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 3060,
"s": 3047,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 3087,
"s": 3060,
"text": "Types of Operating Systems"
}
] |
Angular ng Bootstrap Accordion Component
|
06 Jul, 2021
Angular ng bootstrap is a bootstrap framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites.
In this article we will know how to use Accordion in angular ng bootstrap. Accordion is used to display collapsible content that presents information in a limited amount of space.
Installation syntax:
ng add @ng-bootstrap/ng-bootstrap
Approach:
First, install the angular ng bootstrap using the above-mentioned command.
Import ng bootstrap module in module.tsimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';
imports: [
NgbModule
]
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
imports: [
NgbModule
]
In app.component.html make a accordion component.
Serve the app using ng serve.
Example:
pp.component.html
<ngb-accordion #acc="ngbAccordion" activeIds="ngb-panel-0"> <ngb-panel title="GeeksforGeeks"> <ng-template ngbPanelContent> Content1 </ng-template> </ngb-panel> <ngb-panel> <ng-template ngbPanelTitle> <span>Angular 10</span> </ng-template> <ng-template ngbPanelContent> Content2 </ng-template> </ngb-panel> <ngb-panel title="Ng bootstrap" [disabled]="true"> <ng-template ngbPanelContent> Content3 </ng-template> </ngb-panel>4</ngb-accordion>
app.module.ts
import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule }from '@angular/forms';import { BrowserModule }from '@angular/platform-browser';import { BrowserAnimationsModule }from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { }
Output:
Reference: https://ng-bootstrap.github.io/#/components/accordion/examples
Angular-ng-bootstrap
AngularJS
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": "\n06 Jul, 2021"
},
{
"code": null,
"e": 212,
"s": 28,
"text": "Angular ng bootstrap is a bootstrap framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites."
},
{
"code": null,
"e": 392,
"s": 212,
"text": "In this article we will know how to use Accordion in angular ng bootstrap. Accordion is used to display collapsible content that presents information in a limited amount of space."
},
{
"code": null,
"e": 413,
"s": 392,
"text": "Installation syntax:"
},
{
"code": null,
"e": 447,
"s": 413,
"text": "ng add @ng-bootstrap/ng-bootstrap"
},
{
"code": null,
"e": 457,
"s": 447,
"text": "Approach:"
},
{
"code": null,
"e": 532,
"s": 457,
"text": "First, install the angular ng bootstrap using the above-mentioned command."
},
{
"code": null,
"e": 654,
"s": 532,
"text": "Import ng bootstrap module in module.tsimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';\n\nimports: [\n NgbModule\n]\n"
},
{
"code": null,
"e": 737,
"s": 654,
"text": "import { NgbModule } from '@ng-bootstrap/ng-bootstrap';\n\nimports: [\n NgbModule\n]\n"
},
{
"code": null,
"e": 787,
"s": 737,
"text": "In app.component.html make a accordion component."
},
{
"code": null,
"e": 817,
"s": 787,
"text": "Serve the app using ng serve."
},
{
"code": null,
"e": 828,
"s": 819,
"text": "Example:"
},
{
"code": null,
"e": 846,
"s": 828,
"text": "pp.component.html"
},
{
"code": "<ngb-accordion #acc=\"ngbAccordion\" activeIds=\"ngb-panel-0\"> <ngb-panel title=\"GeeksforGeeks\"> <ng-template ngbPanelContent> Content1 </ng-template> </ngb-panel> <ngb-panel> <ng-template ngbPanelTitle> <span>Angular 10</span> </ng-template> <ng-template ngbPanelContent> Content2 </ng-template> </ngb-panel> <ngb-panel title=\"Ng bootstrap\" [disabled]=\"true\"> <ng-template ngbPanelContent> Content3 </ng-template> </ngb-panel>4</ngb-accordion>",
"e": 1364,
"s": 846,
"text": null
},
{
"code": null,
"e": 1378,
"s": 1364,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule }from '@angular/forms';import { BrowserModule }from '@angular/platform-browser';import { BrowserAnimationsModule }from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { }",
"e": 1982,
"s": 1378,
"text": null
},
{
"code": null,
"e": 1990,
"s": 1982,
"text": "Output:"
},
{
"code": null,
"e": 2064,
"s": 1990,
"text": "Reference: https://ng-bootstrap.github.io/#/components/accordion/examples"
},
{
"code": null,
"e": 2085,
"s": 2064,
"text": "Angular-ng-bootstrap"
},
{
"code": null,
"e": 2095,
"s": 2085,
"text": "AngularJS"
},
{
"code": null,
"e": 2112,
"s": 2095,
"text": "Web Technologies"
}
] |
Scala Map tail() method with example
|
13 Aug, 2019
The tail() method is utilized to display all the elements of the map except the first one.
Method Definition: def tail: Map[A, B]
Return Type: It returns all the elements of the stated map except the first one.
Example #1:
// Scala program of tail()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -> "geeks", 4 -> "for", 2 -> "cs") // Applying tail method val result = m1.tail // Displays output println(result) }}
Map(4 -> for, 2 -> cs)
Example #2:
// Scala program of tail()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -> "geeks", 4 -> "for", 3 -> "geeks") // Applying tail method val result = m1.tail // Displays output println(result) }}
Map(4 -> for)
Scala
Scala-Map
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Aug, 2019"
},
{
"code": null,
"e": 119,
"s": 28,
"text": "The tail() method is utilized to display all the elements of the map except the first one."
},
{
"code": null,
"e": 158,
"s": 119,
"text": "Method Definition: def tail: Map[A, B]"
},
{
"code": null,
"e": 239,
"s": 158,
"text": "Return Type: It returns all the elements of the stated map except the first one."
},
{
"code": null,
"e": 251,
"s": 239,
"text": "Example #1:"
},
{
"code": "// Scala program of tail()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -> \"geeks\", 4 -> \"for\", 2 -> \"cs\") // Applying tail method val result = m1.tail // Displays output println(result) }}",
"e": 604,
"s": 251,
"text": null
},
{
"code": null,
"e": 628,
"s": 604,
"text": "Map(4 -> for, 2 -> cs)\n"
},
{
"code": null,
"e": 640,
"s": 628,
"text": "Example #2:"
},
{
"code": "// Scala program of tail()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -> \"geeks\", 4 -> \"for\", 3 -> \"geeks\") // Applying tail method val result = m1.tail // Displays output println(result) }}",
"e": 996,
"s": 640,
"text": null
},
{
"code": null,
"e": 1011,
"s": 996,
"text": "Map(4 -> for)\n"
},
{
"code": null,
"e": 1017,
"s": 1011,
"text": "Scala"
},
{
"code": null,
"e": 1027,
"s": 1017,
"text": "Scala-Map"
},
{
"code": null,
"e": 1040,
"s": 1027,
"text": "Scala-Method"
},
{
"code": null,
"e": 1046,
"s": 1040,
"text": "Scala"
}
] |
Check if two numbers are co-prime or not - GeeksforGeeks
|
20 Apr, 2021
Two numbers A and B are said to be Co-Prime or mutually prime if the Greatest Common Divisor of them is 1. You have been given two numbers A and B, find if they are Co-prime or not.Examples :
Input : 2 3
Output : Co-Prime
Input : 4 8
Output : Not Co-Prime
C++
Java
Python3
C#
PHP
Javascript
// CPP program to check if two// numbers are co-prime or not#include<bits/stdc++.h>using namespace std; // function to check and print if// two numbers are co-prime or notvoid coprime(int a, int b) { if ( __gcd(a, b) == 1) cout << "Co-Prime" << endl; else cout << "Not Co-Prime" << endl; } // driver codeint main(){ int a = 5, b = 6; coprime(a, b); a = 8, b = 16; coprime(a, b); return 0;}
// Java program to check if two// numbers are co-prime or notclass GFG { // Recursive function to // return gcd of a and b static int __gcd(int a, int b) { // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a-b, b); return __gcd(a, b-a); } // function to check and print if // two numbers are co-prime or not static void coprime(int a, int b) { if ( __gcd(a, b) == 1) System.out.println("Co-Prime"); else System.out.println("Not Co-Prime"); } //driver code public static void main (String[] args) { int a = 5, b = 6; coprime(a, b); a = 8; b = 16; coprime(a, b); }} // This code is contributed by Anant Agarwal.
# Python3 program to check if two# numbers are co-prime or not # Recursive function to# return gcd of a and bdef __gcd(a, b): # Everything divides 0 if (a == 0 or b == 0): return 0 # base case if (a == b): return a # a is greater if (a > b): return __gcd(a - b, b) return __gcd(a, b - a) # Function to check and print if# two numbers are co-prime or notdef coprime(a, b): if ( __gcd(a, b) == 1): print("Co-Prime") else: print("Not Co-Prime") # Driver codea = 5; b = 6coprime(a, b) a = 8; b = 16coprime(a, b) # This code is contributed by Anant Agarwal
// C# program to check if two// numbers are co-prime or notusing System; class GFG { // Recursive function to // return gcd of a and b static int __gcd(int a, int b) { // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a); } // function to check and print if // two numbers are co-prime or not static void coprime(int a, int b) { if (__gcd(a, b) == 1) Console.WriteLine("Co-Prime"); else Console.WriteLine("Not Co-Prime"); } // Driver code public static void Main() { int a = 5, b = 6; coprime(a, b); a = 8; b = 16; coprime(a, b); }} // This code is contributed by Anant Agarwal.
<?php// PHP program to check if two// numbers are co-prime or not // Recursive function to// return gcd of a and bfunction __gcd($a, $b) { // Everything divides 0 if ($a == 0 || $b == 0) return 0; // base case if ($a == $b) return $a; // a is greater if ($a > $b) return __gcd($a - $b, $b); return __gcd($a, $b - $a); } // function to check and print if // two numbers are co-prime or notfunction coprime($a, $b){ if (__gcd($a, $b) == 1) echo "Co-Prime","\n"; else echo "Not Co-Prime","\n";} // Driver Code$a = 5; $b = 6;coprime($a, $b);$a = 8;$b = 16;coprime($a, $b); // This code is contributed by aj_36?>
<script> // Javascript program to check if two// numbers are co-prime or not // Recursive function to// return gcd of a and bfunction __gcd(a, b){ // Everything divides 0 if (a == 0 || b == 0) return 0; // Base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a);} // Function to check and print if// two numbers are co-prime or notfunction coprime(a, b){ if (__gcd(a, b) == 1) document.write("Co-Prime" + "<br>"); else document.write("Not Co-Prime"); } // Driver Codevar a = 5, b = 6;coprime(a, b); a = 8; b = 16;coprime(a, b); // This code is contributed by Kirti </script>
Output :
Co-Prime
Not Co-Prime
This article is contributed by Dibyendu Roy Chaudhuri. 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.
jit_t
Kirti_Mangal
GCD-LCM
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find sum of elements in a given array
Program for factorial of a number
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
Interfaces in Java
|
[
{
"code": null,
"e": 24871,
"s": 24843,
"text": "\n20 Apr, 2021"
},
{
"code": null,
"e": 25065,
"s": 24871,
"text": "Two numbers A and B are said to be Co-Prime or mutually prime if the Greatest Common Divisor of them is 1. You have been given two numbers A and B, find if they are Co-prime or not.Examples : "
},
{
"code": null,
"e": 25130,
"s": 25065,
"text": "Input : 2 3\nOutput : Co-Prime\n\nInput : 4 8\nOutput : Not Co-Prime"
},
{
"code": null,
"e": 25138,
"s": 25134,
"text": "C++"
},
{
"code": null,
"e": 25143,
"s": 25138,
"text": "Java"
},
{
"code": null,
"e": 25151,
"s": 25143,
"text": "Python3"
},
{
"code": null,
"e": 25154,
"s": 25151,
"text": "C#"
},
{
"code": null,
"e": 25158,
"s": 25154,
"text": "PHP"
},
{
"code": null,
"e": 25169,
"s": 25158,
"text": "Javascript"
},
{
"code": "// CPP program to check if two// numbers are co-prime or not#include<bits/stdc++.h>using namespace std; // function to check and print if// two numbers are co-prime or notvoid coprime(int a, int b) { if ( __gcd(a, b) == 1) cout << \"Co-Prime\" << endl; else cout << \"Not Co-Prime\" << endl; } // driver codeint main(){ int a = 5, b = 6; coprime(a, b); a = 8, b = 16; coprime(a, b); return 0;}",
"e": 25615,
"s": 25169,
"text": null
},
{
"code": "// Java program to check if two// numbers are co-prime or notclass GFG { // Recursive function to // return gcd of a and b static int __gcd(int a, int b) { // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a-b, b); return __gcd(a, b-a); } // function to check and print if // two numbers are co-prime or not static void coprime(int a, int b) { if ( __gcd(a, b) == 1) System.out.println(\"Co-Prime\"); else System.out.println(\"Not Co-Prime\"); } //driver code public static void main (String[] args) { int a = 5, b = 6; coprime(a, b); a = 8; b = 16; coprime(a, b); }} // This code is contributed by Anant Agarwal.",
"e": 26563,
"s": 25615,
"text": null
},
{
"code": "# Python3 program to check if two# numbers are co-prime or not # Recursive function to# return gcd of a and bdef __gcd(a, b): # Everything divides 0 if (a == 0 or b == 0): return 0 # base case if (a == b): return a # a is greater if (a > b): return __gcd(a - b, b) return __gcd(a, b - a) # Function to check and print if# two numbers are co-prime or notdef coprime(a, b): if ( __gcd(a, b) == 1): print(\"Co-Prime\") else: print(\"Not Co-Prime\") # Driver codea = 5; b = 6coprime(a, b) a = 8; b = 16coprime(a, b) # This code is contributed by Anant Agarwal",
"e": 27196,
"s": 26563,
"text": null
},
{
"code": "// C# program to check if two// numbers are co-prime or notusing System; class GFG { // Recursive function to // return gcd of a and b static int __gcd(int a, int b) { // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a); } // function to check and print if // two numbers are co-prime or not static void coprime(int a, int b) { if (__gcd(a, b) == 1) Console.WriteLine(\"Co-Prime\"); else Console.WriteLine(\"Not Co-Prime\"); } // Driver code public static void Main() { int a = 5, b = 6; coprime(a, b); a = 8; b = 16; coprime(a, b); }} // This code is contributed by Anant Agarwal.",
"e": 28086,
"s": 27196,
"text": null
},
{
"code": "<?php// PHP program to check if two// numbers are co-prime or not // Recursive function to// return gcd of a and bfunction __gcd($a, $b) { // Everything divides 0 if ($a == 0 || $b == 0) return 0; // base case if ($a == $b) return $a; // a is greater if ($a > $b) return __gcd($a - $b, $b); return __gcd($a, $b - $a); } // function to check and print if // two numbers are co-prime or notfunction coprime($a, $b){ if (__gcd($a, $b) == 1) echo \"Co-Prime\",\"\\n\"; else echo \"Not Co-Prime\",\"\\n\";} // Driver Code$a = 5; $b = 6;coprime($a, $b);$a = 8;$b = 16;coprime($a, $b); // This code is contributed by aj_36?>",
"e": 28812,
"s": 28086,
"text": null
},
{
"code": "<script> // Javascript program to check if two// numbers are co-prime or not // Recursive function to// return gcd of a and bfunction __gcd(a, b){ // Everything divides 0 if (a == 0 || b == 0) return 0; // Base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a);} // Function to check and print if// two numbers are co-prime or notfunction coprime(a, b){ if (__gcd(a, b) == 1) document.write(\"Co-Prime\" + \"<br>\"); else document.write(\"Not Co-Prime\"); } // Driver Codevar a = 5, b = 6;coprime(a, b); a = 8; b = 16;coprime(a, b); // This code is contributed by Kirti </script>",
"e": 29531,
"s": 28812,
"text": null
},
{
"code": null,
"e": 29541,
"s": 29531,
"text": "Output : "
},
{
"code": null,
"e": 29563,
"s": 29541,
"text": "Co-Prime\nNot Co-Prime"
},
{
"code": null,
"e": 29998,
"s": 29563,
"text": "This article is contributed by Dibyendu Roy Chaudhuri. 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. "
},
{
"code": null,
"e": 30004,
"s": 29998,
"text": "jit_t"
},
{
"code": null,
"e": 30017,
"s": 30004,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 30025,
"s": 30017,
"text": "GCD-LCM"
},
{
"code": null,
"e": 30038,
"s": 30025,
"text": "Mathematical"
},
{
"code": null,
"e": 30057,
"s": 30038,
"text": "School Programming"
},
{
"code": null,
"e": 30070,
"s": 30057,
"text": "Mathematical"
},
{
"code": null,
"e": 30168,
"s": 30070,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30177,
"s": 30168,
"text": "Comments"
},
{
"code": null,
"e": 30190,
"s": 30177,
"text": "Old Comments"
},
{
"code": null,
"e": 30214,
"s": 30190,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 30257,
"s": 30214,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 30271,
"s": 30257,
"text": "Prime Numbers"
},
{
"code": null,
"e": 30320,
"s": 30271,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 30354,
"s": 30320,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 30372,
"s": 30354,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30388,
"s": 30372,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 30407,
"s": 30388,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 30432,
"s": 30407,
"text": "Reverse a string in Java"
}
] |
\theta - Tex Command
|
\theta - Used to create lower case Greek theta symbol.
{ \theta}
\theta command draws theta symbol.
\theta
θ
\theta
θ
\theta
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 8041,
"s": 7986,
"text": "\\theta - Used to create lower case Greek theta symbol."
},
{
"code": null,
"e": 8051,
"s": 8041,
"text": "{ \\theta}"
},
{
"code": null,
"e": 8086,
"s": 8051,
"text": "\\theta command draws theta symbol."
},
{
"code": null,
"e": 8100,
"s": 8086,
"text": "\n\\theta\n\nθ\n\n\n"
},
{
"code": null,
"e": 8112,
"s": 8100,
"text": "\\theta\n\nθ\n\n"
},
{
"code": null,
"e": 8119,
"s": 8112,
"text": "\\theta"
},
{
"code": null,
"e": 8151,
"s": 8119,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8164,
"s": 8151,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8197,
"s": 8164,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8210,
"s": 8197,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8242,
"s": 8210,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8278,
"s": 8242,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8313,
"s": 8278,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8330,
"s": 8313,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8363,
"s": 8330,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8377,
"s": 8363,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8409,
"s": 8377,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8424,
"s": 8409,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8431,
"s": 8424,
"text": " Print"
},
{
"code": null,
"e": 8442,
"s": 8431,
"text": " Add Notes"
}
] |
12 Python Tips and Tricks For Writing Better Code | by Pavel Tech | Towards Data Science
|
F-Strings provide a concise and convenient way to embed Python expressions inside string literals for formatting.
First, let’s define two variables name and age that you want to include in our print statement.
name = "Pavel"age = 23
To not deal with string concatenation or using commas inside the print statement, you can use Python’s improved String formatting syntax “f-Strings” which has been released with Python 3.6.
Simply put a lowercase or uppercase letter “f” before the string with the variables or expressions inside the curly braces.
F-Strings are a great new way to format strings and are more readable, faster, concise, and less prone to error than other ways of formatting!
The Python help function is used to look up the documentation of modules, functions, classes, keywords etc.
Simply pass an object inside the help function to retrieve the documentation for that object:
The default sys module contains a function getsizeof that takes an object and returns its size in bytes. The object can be of any type.
Only the memory consumption directly attributed to the object is accounted for and not the memory consumption of objects it refers to.
Normally to check more than two conditions, you would have to use logical operators such as and/or
if a < b and b < c:
In Python, there is a better way to write this using Comparison operator Chaining.
The chaining of operators can be written as follows:
if a < b < c:
List comprehensions are another and often times more elegant way of making lists.
Rather than creating an empty list and adding each element to the end, you can simply define the list and its contents at the same time by following this format:
new_list = [expression for item in iterable (if conditional)]
In Python, it is possible to multiply not only numbers but strings too.
You can assign multiple values to multiple variables by separating variables and values with commas:
This also works when destructuring/unpacking sequences such as lists or tuples and is a more elegant way of assigning elements of a sequence to individual variables as there is no need to use a loop or separately index each element of the sequence.
In many other programming languages swapping the values of two or more variables could only be done by defining an additional temp (temporary) variable.
Say you want to swap x and y:
temp = xx = yy = temp
In Python, there is a simple one-line construct to swap variables, similar to the concept of assignments of values to multiple variables in one-line.
The following code does the same as above but without the use of any temporary variable:
Enum is a class in Python for creating enumerations, which are a set of symbolic names attached to unique, constant values.
In order to create an Enum, it is necessary to create a class which is the name of the Enum that you want.
All that is left to do is list the variables and set them equal to the values that you want:
To access the enum memberPaulas an example, you can just do Person.Paul which will return 0 .
In Python, the example above can be shortened by listing the variables beside each other and setting them equal to the range function:
Often when looping through a list you want to access not only the index with a position in the list but the actual element as well.
Let’s define a list of characters:
x = ['a', 'b', 'c']
Instead of looping through it the standard way, to access the element and index:
Enumerate is a built-in function of Python and allows us to loop over an iterable and have an automatic counter. It essentially pairs every element in our list with the corresponding index. Most of the newcomers and even some advanced programmers are unaware of it.
You can change the variables i and v to variable names that you might prefer. For example, for index, count in enumerate(x).
dir() is a powerful inbuilt function in Python3, which returns a list of the attributes and methods of any object i.e. functions, modules, strings, lists, dictionaries etc.
This can be very useful when having little to no information about the module and helps to learn new modules faster.
The dir() is often used for debugging purposes. The ability of dir() to list out all the attributes of the parameter passed, is really useful when handling a lot of classes and functions, separately.
Sometimes called the Splat or Scatter operator * works when the arguments in a list/tuple need to be unpacked for a function call requiring separate positional arguments.
For instance, the built-in range() function expects separate start and stop arguments. You can use the * operator to unpack the arguments out of a list or tuple when writing a function call:
Let’s define a simple list x = [1,2,3,4,5]
A common example of unpacking operator would be using print:
print(*x) // Result: 1 2 3 4 5
This simply prints out each element of the list beside each other separated by space as the unpack operator takes all the elements in the list and passes them as a parameter, so the translation of the code above would be print(1,2,3,4,5).
This Python trick is used quite often in functions, to ‘pack’ all the arguments that the method call receives into one single variable.
The function func above can take an unlimited amount of arguments (args[0] and args[1] would give you the first and second argument respectively).
In a similar way, dictionaries can deliver keyword arguments with the ** operator.
Let’s define a Python dictionary called person:
person = {"name": "Paul", "age": 23, "location": "London"}
You can use the ** operator to pass in a dictionary to a function.
The passed-in dictionary will decompose the keys as the function keyword arguments and then take the value as the actual value that’s passed for that argument.
Thank you for reading and I hope you found this article useful!
If there are tips you think I should have included or other suggestions then please do comment. 💬
Happy coding! 💻☕️
|
[
{
"code": null,
"e": 286,
"s": 172,
"text": "F-Strings provide a concise and convenient way to embed Python expressions inside string literals for formatting."
},
{
"code": null,
"e": 382,
"s": 286,
"text": "First, let’s define two variables name and age that you want to include in our print statement."
},
{
"code": null,
"e": 405,
"s": 382,
"text": "name = \"Pavel\"age = 23"
},
{
"code": null,
"e": 595,
"s": 405,
"text": "To not deal with string concatenation or using commas inside the print statement, you can use Python’s improved String formatting syntax “f-Strings” which has been released with Python 3.6."
},
{
"code": null,
"e": 719,
"s": 595,
"text": "Simply put a lowercase or uppercase letter “f” before the string with the variables or expressions inside the curly braces."
},
{
"code": null,
"e": 862,
"s": 719,
"text": "F-Strings are a great new way to format strings and are more readable, faster, concise, and less prone to error than other ways of formatting!"
},
{
"code": null,
"e": 970,
"s": 862,
"text": "The Python help function is used to look up the documentation of modules, functions, classes, keywords etc."
},
{
"code": null,
"e": 1064,
"s": 970,
"text": "Simply pass an object inside the help function to retrieve the documentation for that object:"
},
{
"code": null,
"e": 1200,
"s": 1064,
"text": "The default sys module contains a function getsizeof that takes an object and returns its size in bytes. The object can be of any type."
},
{
"code": null,
"e": 1335,
"s": 1200,
"text": "Only the memory consumption directly attributed to the object is accounted for and not the memory consumption of objects it refers to."
},
{
"code": null,
"e": 1434,
"s": 1335,
"text": "Normally to check more than two conditions, you would have to use logical operators such as and/or"
},
{
"code": null,
"e": 1454,
"s": 1434,
"text": "if a < b and b < c:"
},
{
"code": null,
"e": 1537,
"s": 1454,
"text": "In Python, there is a better way to write this using Comparison operator Chaining."
},
{
"code": null,
"e": 1590,
"s": 1537,
"text": "The chaining of operators can be written as follows:"
},
{
"code": null,
"e": 1604,
"s": 1590,
"text": "if a < b < c:"
},
{
"code": null,
"e": 1686,
"s": 1604,
"text": "List comprehensions are another and often times more elegant way of making lists."
},
{
"code": null,
"e": 1848,
"s": 1686,
"text": "Rather than creating an empty list and adding each element to the end, you can simply define the list and its contents at the same time by following this format:"
},
{
"code": null,
"e": 1910,
"s": 1848,
"text": "new_list = [expression for item in iterable (if conditional)]"
},
{
"code": null,
"e": 1982,
"s": 1910,
"text": "In Python, it is possible to multiply not only numbers but strings too."
},
{
"code": null,
"e": 2083,
"s": 1982,
"text": "You can assign multiple values to multiple variables by separating variables and values with commas:"
},
{
"code": null,
"e": 2332,
"s": 2083,
"text": "This also works when destructuring/unpacking sequences such as lists or tuples and is a more elegant way of assigning elements of a sequence to individual variables as there is no need to use a loop or separately index each element of the sequence."
},
{
"code": null,
"e": 2485,
"s": 2332,
"text": "In many other programming languages swapping the values of two or more variables could only be done by defining an additional temp (temporary) variable."
},
{
"code": null,
"e": 2515,
"s": 2485,
"text": "Say you want to swap x and y:"
},
{
"code": null,
"e": 2537,
"s": 2515,
"text": "temp = xx = yy = temp"
},
{
"code": null,
"e": 2687,
"s": 2537,
"text": "In Python, there is a simple one-line construct to swap variables, similar to the concept of assignments of values to multiple variables in one-line."
},
{
"code": null,
"e": 2776,
"s": 2687,
"text": "The following code does the same as above but without the use of any temporary variable:"
},
{
"code": null,
"e": 2900,
"s": 2776,
"text": "Enum is a class in Python for creating enumerations, which are a set of symbolic names attached to unique, constant values."
},
{
"code": null,
"e": 3007,
"s": 2900,
"text": "In order to create an Enum, it is necessary to create a class which is the name of the Enum that you want."
},
{
"code": null,
"e": 3100,
"s": 3007,
"text": "All that is left to do is list the variables and set them equal to the values that you want:"
},
{
"code": null,
"e": 3194,
"s": 3100,
"text": "To access the enum memberPaulas an example, you can just do Person.Paul which will return 0 ."
},
{
"code": null,
"e": 3329,
"s": 3194,
"text": "In Python, the example above can be shortened by listing the variables beside each other and setting them equal to the range function:"
},
{
"code": null,
"e": 3461,
"s": 3329,
"text": "Often when looping through a list you want to access not only the index with a position in the list but the actual element as well."
},
{
"code": null,
"e": 3496,
"s": 3461,
"text": "Let’s define a list of characters:"
},
{
"code": null,
"e": 3516,
"s": 3496,
"text": "x = ['a', 'b', 'c']"
},
{
"code": null,
"e": 3597,
"s": 3516,
"text": "Instead of looping through it the standard way, to access the element and index:"
},
{
"code": null,
"e": 3863,
"s": 3597,
"text": "Enumerate is a built-in function of Python and allows us to loop over an iterable and have an automatic counter. It essentially pairs every element in our list with the corresponding index. Most of the newcomers and even some advanced programmers are unaware of it."
},
{
"code": null,
"e": 3988,
"s": 3863,
"text": "You can change the variables i and v to variable names that you might prefer. For example, for index, count in enumerate(x)."
},
{
"code": null,
"e": 4161,
"s": 3988,
"text": "dir() is a powerful inbuilt function in Python3, which returns a list of the attributes and methods of any object i.e. functions, modules, strings, lists, dictionaries etc."
},
{
"code": null,
"e": 4278,
"s": 4161,
"text": "This can be very useful when having little to no information about the module and helps to learn new modules faster."
},
{
"code": null,
"e": 4478,
"s": 4278,
"text": "The dir() is often used for debugging purposes. The ability of dir() to list out all the attributes of the parameter passed, is really useful when handling a lot of classes and functions, separately."
},
{
"code": null,
"e": 4649,
"s": 4478,
"text": "Sometimes called the Splat or Scatter operator * works when the arguments in a list/tuple need to be unpacked for a function call requiring separate positional arguments."
},
{
"code": null,
"e": 4840,
"s": 4649,
"text": "For instance, the built-in range() function expects separate start and stop arguments. You can use the * operator to unpack the arguments out of a list or tuple when writing a function call:"
},
{
"code": null,
"e": 4883,
"s": 4840,
"text": "Let’s define a simple list x = [1,2,3,4,5]"
},
{
"code": null,
"e": 4944,
"s": 4883,
"text": "A common example of unpacking operator would be using print:"
},
{
"code": null,
"e": 4975,
"s": 4944,
"text": "print(*x) // Result: 1 2 3 4 5"
},
{
"code": null,
"e": 5214,
"s": 4975,
"text": "This simply prints out each element of the list beside each other separated by space as the unpack operator takes all the elements in the list and passes them as a parameter, so the translation of the code above would be print(1,2,3,4,5)."
},
{
"code": null,
"e": 5350,
"s": 5214,
"text": "This Python trick is used quite often in functions, to ‘pack’ all the arguments that the method call receives into one single variable."
},
{
"code": null,
"e": 5497,
"s": 5350,
"text": "The function func above can take an unlimited amount of arguments (args[0] and args[1] would give you the first and second argument respectively)."
},
{
"code": null,
"e": 5580,
"s": 5497,
"text": "In a similar way, dictionaries can deliver keyword arguments with the ** operator."
},
{
"code": null,
"e": 5628,
"s": 5580,
"text": "Let’s define a Python dictionary called person:"
},
{
"code": null,
"e": 5687,
"s": 5628,
"text": "person = {\"name\": \"Paul\", \"age\": 23, \"location\": \"London\"}"
},
{
"code": null,
"e": 5754,
"s": 5687,
"text": "You can use the ** operator to pass in a dictionary to a function."
},
{
"code": null,
"e": 5914,
"s": 5754,
"text": "The passed-in dictionary will decompose the keys as the function keyword arguments and then take the value as the actual value that’s passed for that argument."
},
{
"code": null,
"e": 5978,
"s": 5914,
"text": "Thank you for reading and I hope you found this article useful!"
},
{
"code": null,
"e": 6076,
"s": 5978,
"text": "If there are tips you think I should have included or other suggestions then please do comment. 💬"
}
] |
Python program to display all second lowest grade student name from nested list
|
Suppose we have the names and grades for each student in a nested list we have to display the names of any students having the second lowest grade. If there are more than one students with the second lowest grade, reorder these in an alphabetical order and print each name on a new line.
So, if the input is like students = [['Amal',37],['Bimal',37],['Tarun',36],['Akash',41],['Himadri',39]],
then the output will be Amal, Bimal both have second least score 37, they are placed in alphabetic order.
To solve this, we will follow these steps −
min_mark := minimum of scores for all x in students
students := a list of students x for all x in students if score of > min_mark
min2_mark := minimum of scores for all x in students
students := sort the list [with names of x for all x in students if score of x is same as
min2_mark]
for each x in students, dodisplay x
display x
Let us see the following implementation to get better understanding
def solve(students):
min_mark = min(x[1] for x in students)
students = [x for x in students if x[1] > min_mark]
min2_mark = min(x[1] for x in students)
students = sorted([x[0] for x in students if x[1] == min2_mark])
for x in students:
print(x)
students = [['Amal',37],['Bimal',37],['Tarun',36],['Akash',41],['Himadri',39]]
solve(students)
[['Amal',37],['Bimal',37],['Tarun',36],['Akash',41],['Himadri',39]]
Amal
Bimal
|
[
{
"code": null,
"e": 1350,
"s": 1062,
"text": "Suppose we have the names and grades for each student in a nested list we have to display the names of any students having the second lowest grade. If there are more than one students with the second lowest grade, reorder these in an alphabetical order and print each name on a new line."
},
{
"code": null,
"e": 1561,
"s": 1350,
"text": "So, if the input is like students = [['Amal',37],['Bimal',37],['Tarun',36],['Akash',41],['Himadri',39]],\nthen the output will be Amal, Bimal both have second least score 37, they are placed in alphabetic order."
},
{
"code": null,
"e": 1605,
"s": 1561,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1657,
"s": 1605,
"text": "min_mark := minimum of scores for all x in students"
},
{
"code": null,
"e": 1735,
"s": 1657,
"text": "students := a list of students x for all x in students if score of > min_mark"
},
{
"code": null,
"e": 1788,
"s": 1735,
"text": "min2_mark := minimum of scores for all x in students"
},
{
"code": null,
"e": 1878,
"s": 1788,
"text": "students := sort the list [with names of x for all x in students if score of x is same as"
},
{
"code": null,
"e": 1889,
"s": 1878,
"text": "min2_mark]"
},
{
"code": null,
"e": 1925,
"s": 1889,
"text": "for each x in students, dodisplay x"
},
{
"code": null,
"e": 1935,
"s": 1925,
"text": "display x"
},
{
"code": null,
"e": 2003,
"s": 1935,
"text": "Let us see the following implementation to get better understanding"
},
{
"code": null,
"e": 2365,
"s": 2003,
"text": "def solve(students):\n min_mark = min(x[1] for x in students)\n students = [x for x in students if x[1] > min_mark]\n min2_mark = min(x[1] for x in students)\n students = sorted([x[0] for x in students if x[1] == min2_mark])\n for x in students:\n print(x)\n\nstudents = [['Amal',37],['Bimal',37],['Tarun',36],['Akash',41],['Himadri',39]]\nsolve(students)"
},
{
"code": null,
"e": 2433,
"s": 2365,
"text": "[['Amal',37],['Bimal',37],['Tarun',36],['Akash',41],['Himadri',39]]"
},
{
"code": null,
"e": 2444,
"s": 2433,
"text": "Amal\nBimal"
}
] |
How can we convert a JSON string to a JSON object in Java?
|
The JSON stands for JavaScript Object Notation and it can be used to transfer and storage of data. The JSONObject can parse text from a String to produce a map-like object. The object provides methods for manipulating its contents, and for producing a JSON compliant object serialization. The JSONArray can parse text from a String to produce a vector-like object. The object provides methods for manipulating its contents, and for producing a JSON compliant array serialization.
In the below two examples, We can convert a JSON string to a JSON object.
import org.json.JSONObject;
import org.json.JSONArray;
public class StringToJSONTest {
public static void main(String args[]) {
String str = "[{\"No\":\"1\",\"Name\":\"Adithya\"},{\"No\":\"2\",\"Name\":\"Jai\"}, {\"No\":\"3\",\"Name\":\"Raja\"}]";
JSONArray array = new JSONArray(str);
for(int i=0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
System.out.println(object.getString("No"));
System.out.println(object.getString("Name"));
}
}
}
1
Adithya
2
Jai
3
Raja
import org.json.*;
public class StringToJsonObjectTest {
public static void main(String[] args) {
String str = "{\"name\": \"Raja\", \"technology\": \"Java\"}";
JSONObject json = new JSONObject(str);
System.out.println(json.toString());
String tech = json.getString("technology");
System.out.println(tech);
}
}
{"name":"Raja","technology":"Java"}
Java
|
[
{
"code": null,
"e": 1543,
"s": 1062,
"text": "The JSON stands for JavaScript Object Notation and it can be used to transfer and storage of data. The JSONObject can parse text from a String to produce a map-like object. The object provides methods for manipulating its contents, and for producing a JSON compliant object serialization. The JSONArray can parse text from a String to produce a vector-like object. The object provides methods for manipulating its contents, and for producing a JSON compliant array serialization."
},
{
"code": null,
"e": 1617,
"s": 1543,
"text": "In the below two examples, We can convert a JSON string to a JSON object."
},
{
"code": null,
"e": 2140,
"s": 1617,
"text": "import org.json.JSONObject;\nimport org.json.JSONArray;\npublic class StringToJSONTest {\n public static void main(String args[]) {\n String str = \"[{\\\"No\\\":\\\"1\\\",\\\"Name\\\":\\\"Adithya\\\"},{\\\"No\\\":\\\"2\\\",\\\"Name\\\":\\\"Jai\\\"}, {\\\"No\\\":\\\"3\\\",\\\"Name\\\":\\\"Raja\\\"}]\";\n JSONArray array = new JSONArray(str);\n for(int i=0; i < array.length(); i++) {\n JSONObject object = array.getJSONObject(i);\n System.out.println(object.getString(\"No\"));\n System.out.println(object.getString(\"Name\"));\n }\n }\n}"
},
{
"code": null,
"e": 2163,
"s": 2140,
"text": "1\nAdithya\n2\nJai\n3\nRaja"
},
{
"code": null,
"e": 2510,
"s": 2163,
"text": "import org.json.*;\npublic class StringToJsonObjectTest {\n public static void main(String[] args) {\n String str = \"{\\\"name\\\": \\\"Raja\\\", \\\"technology\\\": \\\"Java\\\"}\";\n JSONObject json = new JSONObject(str);\n System.out.println(json.toString());\n String tech = json.getString(\"technology\");\n System.out.println(tech);\n }\n}"
},
{
"code": null,
"e": 2551,
"s": 2510,
"text": "{\"name\":\"Raja\",\"technology\":\"Java\"}\nJava"
}
] |
Community detection in social networks using brute-force method - GeeksforGeeks
|
05 Sep, 2020
Prerequisite- Python Basics, NetworkX Basics
We are going to divide the nodes of the graph into two or more communities using the brute force method. The brute force method means we will try every division of nodes into communities and check whether the communities are correctly divided or not. We will use a brute force method for this task.
Algorithm:
Create a graph of N nodes and its edges or take an inbuilt graph like a barbell graph.Now take two lists as FirstCommunity and SecondCommunity.Now start putting nodes into communities like put 1st node in FirstCommunity and rest N-1 nodes to SecondCommunity and check its inter and intra edges.Now we will make combinations using itertools.Repeat steps 3 and 4 for every combination.Now check which division is best by taking the ratio of intra/number of inter-community edges.Now find the value of FirstCommunity and SecondCommunity with maximum ratio and print that value.
Create a graph of N nodes and its edges or take an inbuilt graph like a barbell graph.
Now take two lists as FirstCommunity and SecondCommunity.
Now start putting nodes into communities like put 1st node in FirstCommunity and rest N-1 nodes to SecondCommunity and check its inter and intra edges.
Now we will make combinations using itertools.
Repeat steps 3 and 4 for every combination.
Now check which division is best by taking the ratio of intra/number of inter-community edges.
Now find the value of FirstCommunity and SecondCommunity with maximum ratio and print that value.
Below is the implementation.
Python3
import networkx as nximport itertools def communities_using_brute(gfg): nodes = gfg.nodes() n = gfg.number_of_nodes() first_community = [] for i in range(1, n//2 + 1): c = [list(a) for a in itertools.combinations(nodes, i)] first_community.extend(c) second_community = [] for i in range(len(first_community)): b = list(set(nodes)-set(first_community[i])) second_community.append(b) # Which division is best... intra_edges1 = [] intra_edges2 = [] inter_edges = [] # ratio of number of intra/number of inter # community edges ratio = [] for i in range(len(first_community)): intra_edges1.append(gfg.subgraph(first_community[i]).number_of_edges()) for i in range(len(second_community)): intra_edges2.append(gfg.subgraph(second_community[i]).number_of_edges()) e = gfg.number_of_edges() for i in range(len(first_community)): inter_edges.append(e-intra_edges1[i]-intra_edges2[i]) # Calculate the Ratio for i in range(len(first_community)): ratio.append((float(intra_edges1[i]+intra_edges2[i]))/inter_edges[i]) maxV=max(ratio) mindex=ratio.index(maxV) print('[ ', first_community[mindex], ' ] , [ ', second_community[mindex], ' ]') # Example graphgfg=nx.barbell_graph(5, 0)communities_using_brute(gfg)
Output:
[ [0,1,2,3,4] ] , [ [8,9,5,6,7] ]
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
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n05 Sep, 2020"
},
{
"code": null,
"e": 24338,
"s": 24292,
"text": "Prerequisite- Python Basics, NetworkX Basics "
},
{
"code": null,
"e": 24637,
"s": 24338,
"text": "We are going to divide the nodes of the graph into two or more communities using the brute force method. The brute force method means we will try every division of nodes into communities and check whether the communities are correctly divided or not. We will use a brute force method for this task."
},
{
"code": null,
"e": 24648,
"s": 24637,
"text": "Algorithm:"
},
{
"code": null,
"e": 25223,
"s": 24648,
"text": "Create a graph of N nodes and its edges or take an inbuilt graph like a barbell graph.Now take two lists as FirstCommunity and SecondCommunity.Now start putting nodes into communities like put 1st node in FirstCommunity and rest N-1 nodes to SecondCommunity and check its inter and intra edges.Now we will make combinations using itertools.Repeat steps 3 and 4 for every combination.Now check which division is best by taking the ratio of intra/number of inter-community edges.Now find the value of FirstCommunity and SecondCommunity with maximum ratio and print that value."
},
{
"code": null,
"e": 25310,
"s": 25223,
"text": "Create a graph of N nodes and its edges or take an inbuilt graph like a barbell graph."
},
{
"code": null,
"e": 25368,
"s": 25310,
"text": "Now take two lists as FirstCommunity and SecondCommunity."
},
{
"code": null,
"e": 25520,
"s": 25368,
"text": "Now start putting nodes into communities like put 1st node in FirstCommunity and rest N-1 nodes to SecondCommunity and check its inter and intra edges."
},
{
"code": null,
"e": 25567,
"s": 25520,
"text": "Now we will make combinations using itertools."
},
{
"code": null,
"e": 25611,
"s": 25567,
"text": "Repeat steps 3 and 4 for every combination."
},
{
"code": null,
"e": 25706,
"s": 25611,
"text": "Now check which division is best by taking the ratio of intra/number of inter-community edges."
},
{
"code": null,
"e": 25804,
"s": 25706,
"text": "Now find the value of FirstCommunity and SecondCommunity with maximum ratio and print that value."
},
{
"code": null,
"e": 25833,
"s": 25804,
"text": "Below is the implementation."
},
{
"code": null,
"e": 25841,
"s": 25833,
"text": "Python3"
},
{
"code": "import networkx as nximport itertools def communities_using_brute(gfg): nodes = gfg.nodes() n = gfg.number_of_nodes() first_community = [] for i in range(1, n//2 + 1): c = [list(a) for a in itertools.combinations(nodes, i)] first_community.extend(c) second_community = [] for i in range(len(first_community)): b = list(set(nodes)-set(first_community[i])) second_community.append(b) # Which division is best... intra_edges1 = [] intra_edges2 = [] inter_edges = [] # ratio of number of intra/number of inter # community edges ratio = [] for i in range(len(first_community)): intra_edges1.append(gfg.subgraph(first_community[i]).number_of_edges()) for i in range(len(second_community)): intra_edges2.append(gfg.subgraph(second_community[i]).number_of_edges()) e = gfg.number_of_edges() for i in range(len(first_community)): inter_edges.append(e-intra_edges1[i]-intra_edges2[i]) # Calculate the Ratio for i in range(len(first_community)): ratio.append((float(intra_edges1[i]+intra_edges2[i]))/inter_edges[i]) maxV=max(ratio) mindex=ratio.index(maxV) print('[ ', first_community[mindex], ' ] , [ ', second_community[mindex], ' ]') # Example graphgfg=nx.barbell_graph(5, 0)communities_using_brute(gfg)",
"e": 27121,
"s": 25841,
"text": null
},
{
"code": null,
"e": 27129,
"s": 27121,
"text": "Output:"
},
{
"code": null,
"e": 27164,
"s": 27129,
"text": "[ [0,1,2,3,4] ] , [ [8,9,5,6,7] ]\n"
},
{
"code": null,
"e": 27179,
"s": 27164,
"text": "python-utility"
},
{
"code": null,
"e": 27186,
"s": 27179,
"text": "Python"
},
{
"code": null,
"e": 27284,
"s": 27186,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27293,
"s": 27284,
"text": "Comments"
},
{
"code": null,
"e": 27306,
"s": 27293,
"text": "Old Comments"
},
{
"code": null,
"e": 27338,
"s": 27306,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27394,
"s": 27338,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27449,
"s": 27394,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 27491,
"s": 27449,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27533,
"s": 27491,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27564,
"s": 27533,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27603,
"s": 27564,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27625,
"s": 27603,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27654,
"s": 27625,
"text": "Create a directory in Python"
}
] |
10 Examples That Will Make You Use Pandas Query Function More Often | by Soner Yıldırım | Towards Data Science
|
Pandas is a widely-used data analysis and manipulation library. It provides numerous functions and methods to perform typical operations simply and efficiently.
A typical task in data analysis is filtering data points (or observations). In case of working with tabular data, a data point is represented by a row. We sometimes need to filter a row based on some feature (or column) values.
There are several Pandas methods for filtering data points. In this article, we will focus on one of these methods. It is the query function.
Let’s first import libraries and create a sample data frame.
import numpy as npimport pandas as pddf = pd.DataFrame(np.random.randint(10, size=(5,6)), columns=list("ABCDEF"))df
We can now start using the query function to filter this data frame.
The query function allows for applying filtering conditions as a string. It provides more flexibility than many other techniques.
df.query("A > 4")
We have selected rows in which the value in column A is greater than 4.
We can easily combine multiple conditions.
df.query("A > 4 and E == 5")
It is possible to use the “or” logic to combine multiple conditions as well.
df.query("A > 2 or F > 4")
The “not” operator can also be implemented as part of the filter in the query function.
df.query("not (A > 2 or F > 4)")
We can also use simple math operations inside the query function.
df.query("A*2 < 5")
The query function allows for using some built-in functions which provide us with more flexibility.
For instance, we can use the abs function which returns the absolute value of a number. Let’s first convert the values in column F to negative integers and then write a query that includes the abs function.
df.F = -1 * df.Fdf.query("abs(F) > 6")
It is possible to use the sort (square root) function as well.
df.query("sqrt(A) > 2")
The logical operators can also be used for filtering strings. Let’s add a column that contains strings. We can then filter the data frame based on the new column.
df["G"] = ["John", "Jane", "Ashley", "Luke", "Michael"]df.query("G > 'Jo'")
The query function comes in handy when working with dates and times as well. We can implement some functions under the dt accessor. In order to demonstrate this functionality, we need a column with dates or times.
df["Date"] = pd.date_range(start="2021-04-05", periods=5, freq="M")df
Consider we need to select the rows in which the month value is more than 6. Here is how we can accomplish this task.
df.query("Date.dt.month > 6")
We can also create a condition that compares two or more columns.
df.query("A + B < C")
Filtering values is an important part of both data analysis and manipulation. We might be interested in values that fit a certain condition. Similarly, we might want to explore values based on a set of filters.
Pandas offers a rich selection of techniques for filtering data frames. The query function is one of them and it comes in handy for many cases.
Thank you for reading. Please let me know if you have any feedback.
|
[
{
"code": null,
"e": 333,
"s": 172,
"text": "Pandas is a widely-used data analysis and manipulation library. It provides numerous functions and methods to perform typical operations simply and efficiently."
},
{
"code": null,
"e": 561,
"s": 333,
"text": "A typical task in data analysis is filtering data points (or observations). In case of working with tabular data, a data point is represented by a row. We sometimes need to filter a row based on some feature (or column) values."
},
{
"code": null,
"e": 703,
"s": 561,
"text": "There are several Pandas methods for filtering data points. In this article, we will focus on one of these methods. It is the query function."
},
{
"code": null,
"e": 764,
"s": 703,
"text": "Let’s first import libraries and create a sample data frame."
},
{
"code": null,
"e": 880,
"s": 764,
"text": "import numpy as npimport pandas as pddf = pd.DataFrame(np.random.randint(10, size=(5,6)), columns=list(\"ABCDEF\"))df"
},
{
"code": null,
"e": 949,
"s": 880,
"text": "We can now start using the query function to filter this data frame."
},
{
"code": null,
"e": 1079,
"s": 949,
"text": "The query function allows for applying filtering conditions as a string. It provides more flexibility than many other techniques."
},
{
"code": null,
"e": 1097,
"s": 1079,
"text": "df.query(\"A > 4\")"
},
{
"code": null,
"e": 1169,
"s": 1097,
"text": "We have selected rows in which the value in column A is greater than 4."
},
{
"code": null,
"e": 1212,
"s": 1169,
"text": "We can easily combine multiple conditions."
},
{
"code": null,
"e": 1241,
"s": 1212,
"text": "df.query(\"A > 4 and E == 5\")"
},
{
"code": null,
"e": 1318,
"s": 1241,
"text": "It is possible to use the “or” logic to combine multiple conditions as well."
},
{
"code": null,
"e": 1345,
"s": 1318,
"text": "df.query(\"A > 2 or F > 4\")"
},
{
"code": null,
"e": 1433,
"s": 1345,
"text": "The “not” operator can also be implemented as part of the filter in the query function."
},
{
"code": null,
"e": 1466,
"s": 1433,
"text": "df.query(\"not (A > 2 or F > 4)\")"
},
{
"code": null,
"e": 1532,
"s": 1466,
"text": "We can also use simple math operations inside the query function."
},
{
"code": null,
"e": 1552,
"s": 1532,
"text": "df.query(\"A*2 < 5\")"
},
{
"code": null,
"e": 1652,
"s": 1552,
"text": "The query function allows for using some built-in functions which provide us with more flexibility."
},
{
"code": null,
"e": 1859,
"s": 1652,
"text": "For instance, we can use the abs function which returns the absolute value of a number. Let’s first convert the values in column F to negative integers and then write a query that includes the abs function."
},
{
"code": null,
"e": 1898,
"s": 1859,
"text": "df.F = -1 * df.Fdf.query(\"abs(F) > 6\")"
},
{
"code": null,
"e": 1961,
"s": 1898,
"text": "It is possible to use the sort (square root) function as well."
},
{
"code": null,
"e": 1985,
"s": 1961,
"text": "df.query(\"sqrt(A) > 2\")"
},
{
"code": null,
"e": 2148,
"s": 1985,
"text": "The logical operators can also be used for filtering strings. Let’s add a column that contains strings. We can then filter the data frame based on the new column."
},
{
"code": null,
"e": 2224,
"s": 2148,
"text": "df[\"G\"] = [\"John\", \"Jane\", \"Ashley\", \"Luke\", \"Michael\"]df.query(\"G > 'Jo'\")"
},
{
"code": null,
"e": 2438,
"s": 2224,
"text": "The query function comes in handy when working with dates and times as well. We can implement some functions under the dt accessor. In order to demonstrate this functionality, we need a column with dates or times."
},
{
"code": null,
"e": 2508,
"s": 2438,
"text": "df[\"Date\"] = pd.date_range(start=\"2021-04-05\", periods=5, freq=\"M\")df"
},
{
"code": null,
"e": 2626,
"s": 2508,
"text": "Consider we need to select the rows in which the month value is more than 6. Here is how we can accomplish this task."
},
{
"code": null,
"e": 2656,
"s": 2626,
"text": "df.query(\"Date.dt.month > 6\")"
},
{
"code": null,
"e": 2722,
"s": 2656,
"text": "We can also create a condition that compares two or more columns."
},
{
"code": null,
"e": 2744,
"s": 2722,
"text": "df.query(\"A + B < C\")"
},
{
"code": null,
"e": 2955,
"s": 2744,
"text": "Filtering values is an important part of both data analysis and manipulation. We might be interested in values that fit a certain condition. Similarly, we might want to explore values based on a set of filters."
},
{
"code": null,
"e": 3099,
"s": 2955,
"text": "Pandas offers a rich selection of techniques for filtering data frames. The query function is one of them and it comes in handy for many cases."
}
] |
How to find contours of an image using scikit-learn in Python?
|
Scikit-learn, commonly known as sklearn is a library in Python that is used for the purpose of implementing machine learning algorithms. It is an open-source library hence it can be used free of cost. This library is built on Numpy, SciPy and Matplotlib libraries.
The method of ‘marching squares’ is used to find the contours in an image. The function ‘find_contours’ present in the ‘measure’ class of ‘skimage’ library is used. In this, the values present in the array are interpolated in a linear manner.
This way, the precision of the contours in the output image would be much better. If the contours in the image intersect, the contours are open, else they are closed.
Let us understand how to find contours in an image using scikit-learn library −
import numpy as np
import matplotlib.pyplot as plt
from skimage import measure
x, y = np.ogrid[-6.7:np.pi:215j, -1.2:np.pi:215j]
r = np.sin(np.exp((np.sin(x)**3 + np.cos(y)**2)))
contours = measure.find_contours(r, 0.8)
fig, ax = plt.subplots()
ax.imshow(r, cmap=plt.cm.gray)
for contour in contours:
ax.plot(contour[:, 1], contour[:, 0], linewidth=2)
ax.axis('Image')
ax.set_xticks([])
ax.set_yticks([])
plt.show()
The required packages are imported into the environment.
The required packages are imported into the environment.
Data is generated with the help of NumPy package.
Data is generated with the help of NumPy package.
The function ‘find_contours’ is used to determine the contours of the image.
The function ‘find_contours’ is used to determine the contours of the image.
The ‘subplot’ function is used to show the original image and the image with contours on the console.
The ‘subplot’ function is used to show the original image and the image with contours on the console.
|
[
{
"code": null,
"e": 1327,
"s": 1062,
"text": "Scikit-learn, commonly known as sklearn is a library in Python that is used for the purpose of implementing machine learning algorithms. It is an open-source library hence it can be used free of cost. This library is built on Numpy, SciPy and Matplotlib libraries."
},
{
"code": null,
"e": 1570,
"s": 1327,
"text": "The method of ‘marching squares’ is used to find the contours in an image. The function ‘find_contours’ present in the ‘measure’ class of ‘skimage’ library is used. In this, the values present in the array are interpolated in a linear manner."
},
{
"code": null,
"e": 1737,
"s": 1570,
"text": "This way, the precision of the contours in the output image would be much better. If the contours in the image intersect, the contours are open, else they are closed."
},
{
"code": null,
"e": 1817,
"s": 1737,
"text": "Let us understand how to find contours in an image using scikit-learn library −"
},
{
"code": null,
"e": 2233,
"s": 1817,
"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom skimage import measure\nx, y = np.ogrid[-6.7:np.pi:215j, -1.2:np.pi:215j]\nr = np.sin(np.exp((np.sin(x)**3 + np.cos(y)**2)))\ncontours = measure.find_contours(r, 0.8)\nfig, ax = plt.subplots()\nax.imshow(r, cmap=plt.cm.gray)\nfor contour in contours:\nax.plot(contour[:, 1], contour[:, 0], linewidth=2)\nax.axis('Image')\nax.set_xticks([])\nax.set_yticks([])\nplt.show()"
},
{
"code": null,
"e": 2290,
"s": 2233,
"text": "The required packages are imported into the environment."
},
{
"code": null,
"e": 2347,
"s": 2290,
"text": "The required packages are imported into the environment."
},
{
"code": null,
"e": 2397,
"s": 2347,
"text": "Data is generated with the help of NumPy package."
},
{
"code": null,
"e": 2447,
"s": 2397,
"text": "Data is generated with the help of NumPy package."
},
{
"code": null,
"e": 2524,
"s": 2447,
"text": "The function ‘find_contours’ is used to determine the contours of the image."
},
{
"code": null,
"e": 2601,
"s": 2524,
"text": "The function ‘find_contours’ is used to determine the contours of the image."
},
{
"code": null,
"e": 2703,
"s": 2601,
"text": "The ‘subplot’ function is used to show the original image and the image with contours on the console."
},
{
"code": null,
"e": 2805,
"s": 2703,
"text": "The ‘subplot’ function is used to show the original image and the image with contours on the console."
}
] |
Rust - String
|
The String data type in Rust can be classified into the following −
String Literal(&str)
String Literal(&str)
String Object(String)
String Object(String)
String literals (&str) are used when the value of a string is known at compile time. String literals are a set of characters, which are hardcoded into a variable. For example, let company="Tutorials Point". String literals are found in module std::str. String literals are also known as string slices.
The following example declares two string literals − company and location.
fn main() {
let company:&str="TutorialsPoint";
let location:&str = "Hyderabad";
println!("company is : {} location :{}",company,location);
}
String literals are static by default. This means that string literals are guaranteed to be valid for the duration of the entire program. We can also explicitly specify the variable as static as shown below −
fn main() {
let company:&'static str = "TutorialsPoint";
let location:&'static str = "Hyderabad";
println!("company is : {} location :{}",company,location);
}
The above program will generate the following output −
company is : TutorialsPoint location :Hyderabad
The String object type is provided in Standard Library. Unlike string literal, the string object type is not a part of the core language. It is defined as public structure in standard library pub struct String. String is a growable collection. It is mutable and UTF-8 encoded type. The String object type can be used to represent string values that are provided at runtime. String object is allocated in the heap.
To create a String object, we can use any of the following syntax −
String::new()
The above syntax creates an empty string
String::from()
This creates a string with some default value passed as parameter to the from() method.
The following example illustrates the use of a String object.
fn main(){
let empty_string = String::new();
println!("length is {}",empty_string.len());
let content_string = String::from("TutorialsPoint");
println!("length is {}",content_string.len());
}
The above example creates two strings − an empty string object using the new method and a string object from string literal using the from method.
The output is as shown below −
length is 0
length is 14
An empty string object is created using the new() method and its value is set to hello.
fn main(){
let mut z = String::new();
z.push_str("hello");
println!("{}",z);
}
The above program generates the following output −
hello
To access all methods of String object, convert a string literal to object type using the to_string() function.
fn main(){
let name1 = "Hello TutorialsPoint ,
Hello!".to_string();
println!("{}",name1);
}
The above program generates the following output −
Hello TutorialsPoint , Hello!
The replace() function takes two parameters − the first parameter is a string pattern to search for and the second parameter is the new value to be replaced. In the above example, Hello appears two times in the name1 string.
The replace function replaces all occurrences of the string Hello with Howdy.
fn main(){
let name1 = "Hello TutorialsPoint ,
Hello!".to_string(); //String object
let name2 = name1.replace("Hello","Howdy"); //find and replace
println!("{}",name2);
}
The above program generates the following output −
Howdy TutorialsPoint , Howdy!
The as_str() function extracts a string slice containing the entire string.
fn main() {
let example_string = String::from("example_string");
print_literal(example_string.as_str());
}
fn print_literal(data:&str ){
println!("displaying string literal {}",data);
}
The above program generates the following output −
displaying string literal example_string
The push() function appends the given char to the end of this String.
fn main(){
let mut company = "Tutorial".to_string();
company.push('s');
println!("{}",company);
}
The above program generates the following output −
Tutorials
The push_str() function appends a given string slice onto the end of a String.
fn main(){
let mut company = "Tutorials".to_string();
company.push_str(" Point");
println!("{}",company);
}
The above program generates the following output −
Tutorials Point
The len() function returns the total number of characters in a string (including spaces).
fn main() {
let fullname = " Tutorials Point";
println!("length is {}",fullname.len());
}
The above program generates the following output −
length is 20
The trim() function removes leading and trailing spaces in a string. NOTE that this function will not remove the inline spaces.
fn main() {
let fullname = " Tutorials Point \r\n";
println!("Before trim ");
println!("length is {}",fullname.len());
println!();
println!("After trim ");
println!("length is {}",fullname.trim().len());
}
The above program generates the following output −
Before trim
length is 24
After trim
length is 15
The split_whitespace() splits the input string into different strings. It returns an iterator so we are iterating through the tokens as shown below −
fn main(){
let msg = "Tutorials Point has good t
utorials".to_string();
let mut i = 1;
for token in msg.split_whitespace(){
println!("token {} {}",i,token);
i+=1;
}
}
token 1 Tutorials
token 2 Point
token 3 has
token 4 good
token 5 tutorials
The split() string method returns an iterator over substrings of a string slice, separated by characters matched by a pattern. The limitation of the split() method is that the result cannot be stored for later use. The collect method can be used to store the result returned by split() as a vector.
fn main() {
let fullname = "Kannan,Sudhakaran,Tutorialspoint";
for token in fullname.split(","){
println!("token is {}",token);
}
//store in a Vector
println!("\n");
let tokens:Vec<&str>= fullname.split(",").collect();
println!("firstName is {}",tokens[0]);
println!("lastname is {}",tokens[1]);
println!("company is {}",tokens[2]);
}
The above example splits the string fullname, whenever it encounters a comma (,).
token is Kannan
token is Sudhakaran
token is Tutorialspoint
firstName is Kannan
lastname is Sudhakaran
company is Tutorialspoint
Individual characters in a string can be accessed using the chars method. Let us consider an example to understand this.
fn main(){
let n1 = "Tutorials".to_string();
for n in n1.chars(){
println!("{}",n);
}
}
T
u
t
o
r
i
a
l
s
A string value can be appended to another string. This is called concatenation or interpolation. The result of string concatenation is a new string object. The + operator internally uses an add method. The syntax of the add function takes two parameters. The first parameter is self – the string object itself and the second parameter is a reference of the second string object. This is shown below −
//add function
add(self,&str)->String {
// returns a String object
}
fn main(){
let n1 = "Tutorials".to_string();
let n2 = "Point".to_string();
let n3 = n1 + &n2; // n2 reference is passed
println!("{}",n3);
}
The Output will be as given below
TutorialsPoint
The following example illustrates converting a number to a string object −
fn main(){
let number = 2020;
let number_as_string = number.to_string();
// convert number to string
println!("{}",number_as_string);
println!("{}",number_as_string=="2020");
}
The Output will be as given below
2020
true
Another way to add to String objects together is using a macro function called format. The use of Format! is as shown below.
fn main(){
let n1 = "Tutorials".to_string();
let n2 = "Point".to_string();
let n3 = format!("{} {}",n1,n2);
println!("{}",n3);
}
The Output will be as given below
Tutorials Point
45 Lectures
4.5 hours
Stone River ELearning
10 Lectures
33 mins
Ken Burke
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2155,
"s": 2087,
"text": "The String data type in Rust can be classified into the following −"
},
{
"code": null,
"e": 2176,
"s": 2155,
"text": "String Literal(&str)"
},
{
"code": null,
"e": 2197,
"s": 2176,
"text": "String Literal(&str)"
},
{
"code": null,
"e": 2219,
"s": 2197,
"text": "String Object(String)"
},
{
"code": null,
"e": 2241,
"s": 2219,
"text": "String Object(String)"
},
{
"code": null,
"e": 2543,
"s": 2241,
"text": "String literals (&str) are used when the value of a string is known at compile time. String literals are a set of characters, which are hardcoded into a variable. For example, let company=\"Tutorials Point\". String literals are found in module std::str. String literals are also known as string slices."
},
{
"code": null,
"e": 2618,
"s": 2543,
"text": "The following example declares two string literals − company and location."
},
{
"code": null,
"e": 2768,
"s": 2618,
"text": "fn main() {\n let company:&str=\"TutorialsPoint\";\n let location:&str = \"Hyderabad\";\n println!(\"company is : {} location :{}\",company,location);\n}"
},
{
"code": null,
"e": 2977,
"s": 2768,
"text": "String literals are static by default. This means that string literals are guaranteed to be valid for the duration of the entire program. We can also explicitly specify the variable as static as shown below −"
},
{
"code": null,
"e": 3145,
"s": 2977,
"text": "fn main() {\n let company:&'static str = \"TutorialsPoint\";\n let location:&'static str = \"Hyderabad\";\n println!(\"company is : {} location :{}\",company,location);\n}"
},
{
"code": null,
"e": 3200,
"s": 3145,
"text": "The above program will generate the following output −"
},
{
"code": null,
"e": 3249,
"s": 3200,
"text": "company is : TutorialsPoint location :Hyderabad\n"
},
{
"code": null,
"e": 3663,
"s": 3249,
"text": "The String object type is provided in Standard Library. Unlike string literal, the string object type is not a part of the core language. It is defined as public structure in standard library pub struct String. String is a growable collection. It is mutable and UTF-8 encoded type. The String object type can be used to represent string values that are provided at runtime. String object is allocated in the heap."
},
{
"code": null,
"e": 3731,
"s": 3663,
"text": "To create a String object, we can use any of the following syntax −"
},
{
"code": null,
"e": 3746,
"s": 3731,
"text": "String::new()\n"
},
{
"code": null,
"e": 3787,
"s": 3746,
"text": "The above syntax creates an empty string"
},
{
"code": null,
"e": 3803,
"s": 3787,
"text": "String::from()\n"
},
{
"code": null,
"e": 3891,
"s": 3803,
"text": "This creates a string with some default value passed as parameter to the from() method."
},
{
"code": null,
"e": 3953,
"s": 3891,
"text": "The following example illustrates the use of a String object."
},
{
"code": null,
"e": 4158,
"s": 3953,
"text": "fn main(){\n let empty_string = String::new();\n println!(\"length is {}\",empty_string.len());\n\n let content_string = String::from(\"TutorialsPoint\");\n println!(\"length is {}\",content_string.len());\n}"
},
{
"code": null,
"e": 4305,
"s": 4158,
"text": "The above example creates two strings − an empty string object using the new method and a string object from string literal using the from method."
},
{
"code": null,
"e": 4336,
"s": 4305,
"text": "The output is as shown below −"
},
{
"code": null,
"e": 4362,
"s": 4336,
"text": "length is 0\nlength is 14\n"
},
{
"code": null,
"e": 4450,
"s": 4362,
"text": "An empty string object is created using the new() method and its value is set to hello."
},
{
"code": null,
"e": 4538,
"s": 4450,
"text": "fn main(){\n let mut z = String::new();\n z.push_str(\"hello\");\n println!(\"{}\",z);\n}"
},
{
"code": null,
"e": 4589,
"s": 4538,
"text": "The above program generates the following output −"
},
{
"code": null,
"e": 4596,
"s": 4589,
"text": "hello\n"
},
{
"code": null,
"e": 4708,
"s": 4596,
"text": "To access all methods of String object, convert a string literal to object type using the to_string() function."
},
{
"code": null,
"e": 4810,
"s": 4708,
"text": "fn main(){\n let name1 = \"Hello TutorialsPoint , \n Hello!\".to_string();\n println!(\"{}\",name1);\n}"
},
{
"code": null,
"e": 4861,
"s": 4810,
"text": "The above program generates the following output −"
},
{
"code": null,
"e": 4892,
"s": 4861,
"text": "Hello TutorialsPoint , Hello!\n"
},
{
"code": null,
"e": 5117,
"s": 4892,
"text": "The replace() function takes two parameters − the first parameter is a string pattern to search for and the second parameter is the new value to be replaced. In the above example, Hello appears two times in the name1 string."
},
{
"code": null,
"e": 5195,
"s": 5117,
"text": "The replace function replaces all occurrences of the string Hello with Howdy."
},
{
"code": null,
"e": 5390,
"s": 5195,
"text": "fn main(){\n let name1 = \"Hello TutorialsPoint , \n Hello!\".to_string(); //String object\n let name2 = name1.replace(\"Hello\",\"Howdy\"); //find and replace\n println!(\"{}\",name2);\n}"
},
{
"code": null,
"e": 5441,
"s": 5390,
"text": "The above program generates the following output −"
},
{
"code": null,
"e": 5472,
"s": 5441,
"text": "Howdy TutorialsPoint , Howdy!\n"
},
{
"code": null,
"e": 5548,
"s": 5472,
"text": "The as_str() function extracts a string slice containing the entire string."
},
{
"code": null,
"e": 5743,
"s": 5548,
"text": "fn main() {\n let example_string = String::from(\"example_string\");\n print_literal(example_string.as_str());\n}\nfn print_literal(data:&str ){\n println!(\"displaying string literal {}\",data);\n}"
},
{
"code": null,
"e": 5794,
"s": 5743,
"text": "The above program generates the following output −"
},
{
"code": null,
"e": 5836,
"s": 5794,
"text": "displaying string literal example_string\n"
},
{
"code": null,
"e": 5906,
"s": 5836,
"text": "The push() function appends the given char to the end of this String."
},
{
"code": null,
"e": 6013,
"s": 5906,
"text": "fn main(){\n let mut company = \"Tutorial\".to_string();\n company.push('s');\n println!(\"{}\",company);\n}"
},
{
"code": null,
"e": 6064,
"s": 6013,
"text": "The above program generates the following output −"
},
{
"code": null,
"e": 6075,
"s": 6064,
"text": "Tutorials\n"
},
{
"code": null,
"e": 6154,
"s": 6075,
"text": "The push_str() function appends a given string slice onto the end of a String."
},
{
"code": null,
"e": 6271,
"s": 6154,
"text": "fn main(){\n let mut company = \"Tutorials\".to_string();\n company.push_str(\" Point\");\n println!(\"{}\",company);\n}"
},
{
"code": null,
"e": 6322,
"s": 6271,
"text": "The above program generates the following output −"
},
{
"code": null,
"e": 6339,
"s": 6322,
"text": "Tutorials Point\n"
},
{
"code": null,
"e": 6429,
"s": 6339,
"text": "The len() function returns the total number of characters in a string (including spaces)."
},
{
"code": null,
"e": 6525,
"s": 6429,
"text": "fn main() {\n let fullname = \" Tutorials Point\";\n println!(\"length is {}\",fullname.len());\n}"
},
{
"code": null,
"e": 6576,
"s": 6525,
"text": "The above program generates the following output −"
},
{
"code": null,
"e": 6590,
"s": 6576,
"text": "length is 20\n"
},
{
"code": null,
"e": 6718,
"s": 6590,
"text": "The trim() function removes leading and trailing spaces in a string. NOTE that this function will not remove the inline spaces."
},
{
"code": null,
"e": 6942,
"s": 6718,
"text": "fn main() {\n let fullname = \" Tutorials Point \\r\\n\";\n println!(\"Before trim \");\n println!(\"length is {}\",fullname.len());\n println!();\n println!(\"After trim \");\n println!(\"length is {}\",fullname.trim().len());\n}"
},
{
"code": null,
"e": 6993,
"s": 6942,
"text": "The above program generates the following output −"
},
{
"code": null,
"e": 7044,
"s": 6993,
"text": "Before trim\nlength is 24\n\nAfter trim\nlength is 15\n"
},
{
"code": null,
"e": 7194,
"s": 7044,
"text": "The split_whitespace() splits the input string into different strings. It returns an iterator so we are iterating through the tokens as shown below −"
},
{
"code": null,
"e": 7392,
"s": 7194,
"text": "fn main(){\n let msg = \"Tutorials Point has good t\n utorials\".to_string();\n let mut i = 1;\n \n for token in msg.split_whitespace(){\n println!(\"token {} {}\",i,token);\n i+=1;\n }\n}"
},
{
"code": null,
"e": 7468,
"s": 7392,
"text": "token 1 Tutorials\ntoken 2 Point\ntoken 3 has\ntoken 4 good\ntoken 5 tutorials\n"
},
{
"code": null,
"e": 7767,
"s": 7468,
"text": "The split() string method returns an iterator over substrings of a string slice, separated by characters matched by a pattern. The limitation of the split() method is that the result cannot be stored for later use. The collect method can be used to store the result returned by split() as a vector."
},
{
"code": null,
"e": 8137,
"s": 7767,
"text": "fn main() {\n let fullname = \"Kannan,Sudhakaran,Tutorialspoint\";\n\n for token in fullname.split(\",\"){\n println!(\"token is {}\",token);\n }\n\n //store in a Vector\n println!(\"\\n\");\n let tokens:Vec<&str>= fullname.split(\",\").collect();\n println!(\"firstName is {}\",tokens[0]);\n println!(\"lastname is {}\",tokens[1]);\n println!(\"company is {}\",tokens[2]);\n}"
},
{
"code": null,
"e": 8219,
"s": 8137,
"text": "The above example splits the string fullname, whenever it encounters a comma (,)."
},
{
"code": null,
"e": 8350,
"s": 8219,
"text": "token is Kannan\ntoken is Sudhakaran\ntoken is Tutorialspoint\n\nfirstName is Kannan\nlastname is Sudhakaran\ncompany is Tutorialspoint\n"
},
{
"code": null,
"e": 8471,
"s": 8350,
"text": "Individual characters in a string can be accessed using the chars method. Let us consider an example to understand this."
},
{
"code": null,
"e": 8575,
"s": 8471,
"text": "fn main(){\n let n1 = \"Tutorials\".to_string();\n\n for n in n1.chars(){\n println!(\"{}\",n);\n }\n}"
},
{
"code": null,
"e": 8594,
"s": 8575,
"text": "T\nu\nt\no\nr\ni\na\nl\ns\n"
},
{
"code": null,
"e": 8995,
"s": 8594,
"text": "A string value can be appended to another string. This is called concatenation or interpolation. The result of string concatenation is a new string object. The + operator internally uses an add method. The syntax of the add function takes two parameters. The first parameter is self – the string object itself and the second parameter is a reference of the second string object. This is shown below −"
},
{
"code": null,
"e": 9069,
"s": 8995,
"text": "//add function\nadd(self,&str)->String { \n // returns a String object\n}\n"
},
{
"code": null,
"e": 9223,
"s": 9069,
"text": "fn main(){\n let n1 = \"Tutorials\".to_string();\n let n2 = \"Point\".to_string();\n\n let n3 = n1 + &n2; // n2 reference is passed\n println!(\"{}\",n3);\n}"
},
{
"code": null,
"e": 9257,
"s": 9223,
"text": "The Output will be as given below"
},
{
"code": null,
"e": 9273,
"s": 9257,
"text": "TutorialsPoint\n"
},
{
"code": null,
"e": 9348,
"s": 9273,
"text": "The following example illustrates converting a number to a string object −"
},
{
"code": null,
"e": 9545,
"s": 9348,
"text": "fn main(){\n let number = 2020;\n let number_as_string = number.to_string(); \n \n // convert number to string\n println!(\"{}\",number_as_string);\n println!(\"{}\",number_as_string==\"2020\");\n}"
},
{
"code": null,
"e": 9579,
"s": 9545,
"text": "The Output will be as given below"
},
{
"code": null,
"e": 9590,
"s": 9579,
"text": "2020\ntrue\n"
},
{
"code": null,
"e": 9715,
"s": 9590,
"text": "Another way to add to String objects together is using a macro function called format. The use of Format! is as shown below."
},
{
"code": null,
"e": 9856,
"s": 9715,
"text": "fn main(){\n let n1 = \"Tutorials\".to_string();\n let n2 = \"Point\".to_string();\n let n3 = format!(\"{} {}\",n1,n2);\n println!(\"{}\",n3);\n}"
},
{
"code": null,
"e": 9890,
"s": 9856,
"text": "The Output will be as given below"
},
{
"code": null,
"e": 9907,
"s": 9890,
"text": "Tutorials Point\n"
},
{
"code": null,
"e": 9942,
"s": 9907,
"text": "\n 45 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 9965,
"s": 9942,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 9997,
"s": 9965,
"text": "\n 10 Lectures \n 33 mins\n"
},
{
"code": null,
"e": 10008,
"s": 9997,
"text": " Ken Burke"
},
{
"code": null,
"e": 10015,
"s": 10008,
"text": " Print"
},
{
"code": null,
"e": 10026,
"s": 10015,
"text": " Add Notes"
}
] |
Lex program for Decimal to Binary Conversion - GeeksforGeeks
|
02 May, 2019
Problem: Write a Lex program for Decimal to Binary conversion.
Explanation:FLEX (Fast Lexical Analyzer Generator) is a tool/computer program for generating lexical analyzers (scanners or lexers) written by Vern Paxson in C around 1987. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. The function yylex() is the main flex function which runs the Rule Section.
Examples:
Input: 12
Output: 1100
Input: 115
Output: 1110011
Input: 25
Output: 11001
Input: 220
Output: 11011100
Implementation:
/* Lex program for decimal to binary conversion */ %{ /* Definition section */ #include<stdio.h> int num, r, b=0, p=1;%} DIGIT [0-9]/* Rule Section */%%{DIGIT}+ { num=atoi(yytext); while (num > 0) { r= num % 2; b+= r*p; p*= 10; num/= 2; } printf("%d", b); }.|\n ECHO; %% // driver code int main(){ yylex(); return 0;}
Output:
Lex program
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Symbol Table in Compiler
Code Optimization in Compiler Design
Intermediate Code Generation in Compiler Design
Types of Parsers in Compiler Design
Introduction of Compiler Design
Directed Acyclic graph in Compiler Design (with examples)
Syntax Directed Translation in Compiler Design
Ambiguous Grammar
Difference between Compiler and Interpreter
Shift Reduce Parser in Compiler
|
[
{
"code": null,
"e": 26259,
"s": 26231,
"text": "\n02 May, 2019"
},
{
"code": null,
"e": 26322,
"s": 26259,
"text": "Problem: Write a Lex program for Decimal to Binary conversion."
},
{
"code": null,
"e": 26707,
"s": 26322,
"text": "Explanation:FLEX (Fast Lexical Analyzer Generator) is a tool/computer program for generating lexical analyzers (scanners or lexers) written by Vern Paxson in C around 1987. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. The function yylex() is the main flex function which runs the Rule Section."
},
{
"code": null,
"e": 26717,
"s": 26707,
"text": "Examples:"
},
{
"code": null,
"e": 26824,
"s": 26717,
"text": "Input: 12 \nOutput: 1100\n\nInput: 115\nOutput: 1110011\n\nInput: 25\nOutput: 11001\n\nInput: 220\nOutput: 11011100 "
},
{
"code": null,
"e": 26840,
"s": 26824,
"text": "Implementation:"
},
{
"code": "/* Lex program for decimal to binary conversion */ %{ /* Definition section */ #include<stdio.h> int num, r, b=0, p=1;%} DIGIT [0-9]/* Rule Section */%%{DIGIT}+ { num=atoi(yytext); while (num > 0) { r= num % 2; b+= r*p; p*= 10; num/= 2; } printf(\"%d\", b); }.|\\n ECHO; %% // driver code int main(){ yylex(); return 0;} ",
"e": 27301,
"s": 26840,
"text": null
},
{
"code": null,
"e": 27309,
"s": 27301,
"text": "Output:"
},
{
"code": null,
"e": 27321,
"s": 27309,
"text": "Lex program"
},
{
"code": null,
"e": 27337,
"s": 27321,
"text": "Compiler Design"
},
{
"code": null,
"e": 27435,
"s": 27337,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27460,
"s": 27435,
"text": "Symbol Table in Compiler"
},
{
"code": null,
"e": 27497,
"s": 27460,
"text": "Code Optimization in Compiler Design"
},
{
"code": null,
"e": 27545,
"s": 27497,
"text": "Intermediate Code Generation in Compiler Design"
},
{
"code": null,
"e": 27581,
"s": 27545,
"text": "Types of Parsers in Compiler Design"
},
{
"code": null,
"e": 27613,
"s": 27581,
"text": "Introduction of Compiler Design"
},
{
"code": null,
"e": 27671,
"s": 27613,
"text": "Directed Acyclic graph in Compiler Design (with examples)"
},
{
"code": null,
"e": 27718,
"s": 27671,
"text": "Syntax Directed Translation in Compiler Design"
},
{
"code": null,
"e": 27736,
"s": 27718,
"text": "Ambiguous Grammar"
},
{
"code": null,
"e": 27780,
"s": 27736,
"text": "Difference between Compiler and Interpreter"
}
] |
How to resize an image in an HTML 5 canvas ? - GeeksforGeeks
|
27 Aug, 2019
The canvas element is part of HTML 5 and it allows the rendering of 2D shapes and bitmap(also called “raster”) images.A canvas actually has two sizes:
the size of the element.
the size of the element’s drawing surface.
The element’s width and height attributes set both the size of the element and the size of the element’s drawing surface. CSS attributes affect only the element’s size and not the drawing surface.
Example:
<!DOCTYPE html><html> <body> <p>Image:</p> <img id="forest" width="220" height="277" src="https://media.geeksforgeeks.org/wp-content/uploads/20190809013546/gfg_350X350.png" alt="Forest"> <p>Canvas:</p> <canvas id="Canvas" width="300" height="200" style="border:15px solid #000066;"> Your browser not support the HTML5 canvas . </canvas> <script> window.onload = function() { var canvas = document.getElementById("Canvas"); var context = canvas.getContext("2d"); var img = document.getElementById("forest"); context.drawImage(img, 12, 8); }; </script></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Misc
Picked
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
How to Insert Form Data into Database using PHP ?
Types of CSS (Cascading Style Sheet)
Form validation using HTML and JavaScript
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26705,
"s": 26677,
"text": "\n27 Aug, 2019"
},
{
"code": null,
"e": 26856,
"s": 26705,
"text": "The canvas element is part of HTML 5 and it allows the rendering of 2D shapes and bitmap(also called “raster”) images.A canvas actually has two sizes:"
},
{
"code": null,
"e": 26881,
"s": 26856,
"text": "the size of the element."
},
{
"code": null,
"e": 26924,
"s": 26881,
"text": "the size of the element’s drawing surface."
},
{
"code": null,
"e": 27121,
"s": 26924,
"text": "The element’s width and height attributes set both the size of the element and the size of the element’s drawing surface. CSS attributes affect only the element’s size and not the drawing surface."
},
{
"code": null,
"e": 27130,
"s": 27121,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <body> <p>Image:</p> <img id=\"forest\" width=\"220\" height=\"277\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190809013546/gfg_350X350.png\" alt=\"Forest\"> <p>Canvas:</p> <canvas id=\"Canvas\" width=\"300\" height=\"200\" style=\"border:15px solid #000066;\"> Your browser not support the HTML5 canvas . </canvas> <script> window.onload = function() { var canvas = document.getElementById(\"Canvas\"); var context = canvas.getContext(\"2d\"); var img = document.getElementById(\"forest\"); context.drawImage(img, 12, 8); }; </script></body> </html> ",
"e": 27824,
"s": 27130,
"text": null
},
{
"code": null,
"e": 27832,
"s": 27824,
"text": "Output:"
},
{
"code": null,
"e": 27969,
"s": 27832,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 27979,
"s": 27969,
"text": "HTML-Misc"
},
{
"code": null,
"e": 27986,
"s": 27979,
"text": "Picked"
},
{
"code": null,
"e": 27991,
"s": 27986,
"text": "HTML"
},
{
"code": null,
"e": 28008,
"s": 27991,
"text": "Web Technologies"
},
{
"code": null,
"e": 28035,
"s": 28008,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 28040,
"s": 28035,
"text": "HTML"
},
{
"code": null,
"e": 28138,
"s": 28040,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28162,
"s": 28138,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 28203,
"s": 28162,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 28253,
"s": 28203,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 28290,
"s": 28253,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 28332,
"s": 28290,
"text": "Form validation using HTML and JavaScript"
},
{
"code": null,
"e": 28372,
"s": 28332,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28405,
"s": 28372,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28450,
"s": 28405,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28493,
"s": 28450,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to perform string matching in MySQL?
|
For string matching, use LIKE operator. Let us first create a table −
mysql> create table DemoTable
-> (
-> MonthName varchar(100)
-> );
Query OK, 0 rows affected (0.63 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('JFMA');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('JMA');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('JDN');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('JFOSA');
Query OK, 1 row affected (0.19 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
+-----------+
| MonthName |
+-----------+
| JFMA |
| JMA |
| JDN |
| JFOSA |
+-----------+
4 rows in set (0.00 sec)
Following is the query to perform string matching in MySQL −
mysql> select *from DemoTable WHERE MonthName LIKE '%J%M%';
+-----------+
| MonthName |
+-----------+
| JFMA |
| JMA |
+-----------+
2 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1132,
"s": 1062,
"text": "For string matching, use LIKE operator. Let us first create a table −"
},
{
"code": null,
"e": 1245,
"s": 1132,
"text": "mysql> create table DemoTable\n -> (\n -> MonthName varchar(100)\n -> );\nQuery OK, 0 rows affected (0.63 sec)"
},
{
"code": null,
"e": 1301,
"s": 1245,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1627,
"s": 1301,
"text": "mysql> insert into DemoTable values('JFMA');\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into DemoTable values('JMA');\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into DemoTable values('JDN');\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into DemoTable values('JFOSA');\nQuery OK, 1 row affected (0.19 sec)"
},
{
"code": null,
"e": 1687,
"s": 1627,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1718,
"s": 1687,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1855,
"s": 1718,
"text": "+-----------+\n| MonthName |\n+-----------+\n| JFMA |\n| JMA |\n| JDN |\n| JFOSA |\n+-----------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1916,
"s": 1855,
"text": "Following is the query to perform string matching in MySQL −"
},
{
"code": null,
"e": 1976,
"s": 1916,
"text": "mysql> select *from DemoTable WHERE MonthName LIKE '%J%M%';"
},
{
"code": null,
"e": 2085,
"s": 1976,
"text": "+-----------+\n| MonthName |\n+-----------+\n| JFMA |\n| JMA |\n+-----------+\n2 rows in set (0.00 sec)"
}
] |
How to remove “disabled” attribute from HTML input element using JavaScript ? - GeeksforGeeks
|
27 Apr, 2020
The task is to remove the disabled attribute from the input element using JavaScript. There are two approaches that are discussed below.
Approach 1: Select the input element and use disabled property and set its value to false.
Example:<!DOCTYPE html><html> <head> <title> How to remove “disabled” attribute from HTML input element using JavaScript ? </title> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <p> Click on the button to remove disabled attribute </p> Type: <input id="input" disabled /> <br> <br> <button onclick="myGFG()"> Click Here </button> <p id="gfg"> </p> <script> var down = document.getElementById("gfg"); function myGFG() { document.getElementById('input').disabled = false; down.innerHTML = "Disabled Attribute removed"; } </script></body> </html>
<!DOCTYPE html><html> <head> <title> How to remove “disabled” attribute from HTML input element using JavaScript ? </title> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <p> Click on the button to remove disabled attribute </p> Type: <input id="input" disabled /> <br> <br> <button onclick="myGFG()"> Click Here </button> <p id="gfg"> </p> <script> var down = document.getElementById("gfg"); function myGFG() { document.getElementById('input').disabled = false; down.innerHTML = "Disabled Attribute removed"; } </script></body> </html>
Output:
Approach 2: Select the input element and use disabled property and set its value to false. This example selects input element by its class.
Example:<!DOCTYPE HTML><html> <head> <title> How to remove “disabled” attribute from HTML input element using JavaScript ? </title> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <p> Click on the button to remove disabled attribute </p> Type: <input id="input" disabled /> <br> <br> <button onclick="myGFG()"> Click Here </button> <p id="gfg"> </p> <script> var down = document.getElementById("gfg"); function myGFG() { var input = document.getElementsByClassName('inputClass'); for (var i = 0; i < input.length; i++) { input[i].disabled = false; } down.innerHTML = "Disabled Attribute removed"; } </script></body> </html>
<!DOCTYPE HTML><html> <head> <title> How to remove “disabled” attribute from HTML input element using JavaScript ? </title> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <p> Click on the button to remove disabled attribute </p> Type: <input id="input" disabled /> <br> <br> <button onclick="myGFG()"> Click Here </button> <p id="gfg"> </p> <script> var down = document.getElementById("gfg"); function myGFG() { var input = document.getElementsByClassName('inputClass'); for (var i = 0; i < input.length; i++) { input[i].disabled = false; } down.innerHTML = "Disabled Attribute removed"; } </script></body> </html>
Output:
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
How to apply style to parent if it has child with CSS?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
How to set space between the flexbox ?
How to update Node.js and NPM to next version ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
|
[
{
"code": null,
"e": 26527,
"s": 26499,
"text": "\n27 Apr, 2020"
},
{
"code": null,
"e": 26664,
"s": 26527,
"text": "The task is to remove the disabled attribute from the input element using JavaScript. There are two approaches that are discussed below."
},
{
"code": null,
"e": 26755,
"s": 26664,
"text": "Approach 1: Select the input element and use disabled property and set its value to false."
},
{
"code": null,
"e": 27583,
"s": 26755,
"text": "Example:<!DOCTYPE html><html> <head> <title> How to remove “disabled” attribute from HTML input element using JavaScript ? </title> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p> Click on the button to remove disabled attribute </p> Type: <input id=\"input\" disabled /> <br> <br> <button onclick=\"myGFG()\"> Click Here </button> <p id=\"gfg\"> </p> <script> var down = document.getElementById(\"gfg\"); function myGFG() { document.getElementById('input').disabled = false; down.innerHTML = \"Disabled Attribute removed\"; } </script></body> </html>"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to remove “disabled” attribute from HTML input element using JavaScript ? </title> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p> Click on the button to remove disabled attribute </p> Type: <input id=\"input\" disabled /> <br> <br> <button onclick=\"myGFG()\"> Click Here </button> <p id=\"gfg\"> </p> <script> var down = document.getElementById(\"gfg\"); function myGFG() { document.getElementById('input').disabled = false; down.innerHTML = \"Disabled Attribute removed\"; } </script></body> </html>",
"e": 28403,
"s": 27583,
"text": null
},
{
"code": null,
"e": 28411,
"s": 28403,
"text": "Output:"
},
{
"code": null,
"e": 28551,
"s": 28411,
"text": "Approach 2: Select the input element and use disabled property and set its value to false. This example selects input element by its class."
},
{
"code": null,
"e": 29494,
"s": 28551,
"text": "Example:<!DOCTYPE HTML><html> <head> <title> How to remove “disabled” attribute from HTML input element using JavaScript ? </title> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p> Click on the button to remove disabled attribute </p> Type: <input id=\"input\" disabled /> <br> <br> <button onclick=\"myGFG()\"> Click Here </button> <p id=\"gfg\"> </p> <script> var down = document.getElementById(\"gfg\"); function myGFG() { var input = document.getElementsByClassName('inputClass'); for (var i = 0; i < input.length; i++) { input[i].disabled = false; } down.innerHTML = \"Disabled Attribute removed\"; } </script></body> </html>"
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> How to remove “disabled” attribute from HTML input element using JavaScript ? </title> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p> Click on the button to remove disabled attribute </p> Type: <input id=\"input\" disabled /> <br> <br> <button onclick=\"myGFG()\"> Click Here </button> <p id=\"gfg\"> </p> <script> var down = document.getElementById(\"gfg\"); function myGFG() { var input = document.getElementsByClassName('inputClass'); for (var i = 0; i < input.length; i++) { input[i].disabled = false; } down.innerHTML = \"Disabled Attribute removed\"; } </script></body> </html>",
"e": 30429,
"s": 29494,
"text": null
},
{
"code": null,
"e": 30437,
"s": 30429,
"text": "Output:"
},
{
"code": null,
"e": 30446,
"s": 30437,
"text": "CSS-Misc"
},
{
"code": null,
"e": 30456,
"s": 30446,
"text": "HTML-Misc"
},
{
"code": null,
"e": 30472,
"s": 30456,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 30476,
"s": 30472,
"text": "CSS"
},
{
"code": null,
"e": 30481,
"s": 30476,
"text": "HTML"
},
{
"code": null,
"e": 30492,
"s": 30481,
"text": "JavaScript"
},
{
"code": null,
"e": 30509,
"s": 30492,
"text": "Web Technologies"
},
{
"code": null,
"e": 30536,
"s": 30509,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 30541,
"s": 30536,
"text": "HTML"
},
{
"code": null,
"e": 30639,
"s": 30541,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30687,
"s": 30639,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 30742,
"s": 30687,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 30779,
"s": 30742,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 30843,
"s": 30779,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 30882,
"s": 30843,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 30930,
"s": 30882,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 30983,
"s": 30930,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 31044,
"s": 30983,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 31068,
"s": 31044,
"text": "REST API (Introduction)"
}
] |
PHP | Decision Making - GeeksforGeeks
|
01 Sep, 2021
PHP allows us to perform actions based on some type of conditions that may be logical or comparative. Based on the result of these conditions i.e., either TRUE or FALSE, an action would be performed as asked by the user. It’s just like a two- way path. If you want something then go this way or else turn that way. To use this feature, PHP provides us with four conditional statements:
if statement
if...else statement
if...elseif...else statement
switch statement
Let us now look at each one of these in details:
if Statement: This statement allows us to set a condition. On being TRUE, the following block of code enclosed within the if clause will be executed.Syntax :if (condition){
// if TRUE then execute this code
}
Example:<?php$x = 12; if ($x > 0) { echo "The number is positive";}?>Output:The number is positive
Flowchart:if...else Statement: We understood that if a condition will hold i.e., TRUE, then the block of code within if will be executed. But what if the condition is not TRUE and we want to perform an action? This is where else comes into play. If a condition is TRUE then if block gets executed, otherwise else block gets executed.Syntax:if (condition) {
// if TRUE then execute this code
}
else{
// if FALSE then execute this code
}
Example:<?php$x = -12; if ($x > 0) { echo "The number is positive";} else{ echo "The number is negative";}?>Output:The number is negative
Flowchart:if...elseif...else Statement: This allows us to use multiple if...else statements. We use this when there are multiple conditions of TRUE cases.Syntax:if (condition) {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
else {
// if FALSE then execute this code
}
Example:<?php$x = "August"; if ($x == "January") { echo "Happy Republic Day";} elseif ($x == "August") { echo "Happy Independence Day!!!";} else{ echo "Nothing to show";}?>Output:Happy Independence Day!!!
Flowchart:switch Statement: The “switch” performs in various cases i.e., it has various cases to which it matches the condition and appropriately executes a particular case block. It first evaluates an expression and then compares with the values of each case. If a case matches then the same case is executed. To use switch, we need to get familiar with two different keywords namely, break and default.The break statement is used to stop the automatic control flow into the next cases and exit from the switch case.The default statement contains the code that would execute if none of the cases match.Syntax:switch(n) {
case statement1:
code to be executed if n==statement1;
break;
case statement2:
code to be executed if n==statement2;
break;
case statement3:
code to be executed if n==statement3;
break;
case statement4:
code to be executed if n==statement4;
break;
......
default:
code to be executed if n != any case;
Example:<?php$n = "February"; switch($n) { case "January": echo "Its January"; break; case "February": echo "Its February"; break; case "March": echo "Its March"; break; case "April": echo "Its April"; break; case "May": echo "Its May"; break; case "June": echo "Its June"; break; case "July": echo "Its July"; break; case "August": echo "Its August"; break; case "September": echo "Its September"; break; case "October": echo "Its October"; break; case "November": echo "Its November"; break; case "December": echo "Its December"; break; default: echo "Doesn't exist";}?>Output:Its February
Flowchart:
if Statement: This statement allows us to set a condition. On being TRUE, the following block of code enclosed within the if clause will be executed.Syntax :if (condition){
// if TRUE then execute this code
}
Example:<?php$x = 12; if ($x > 0) { echo "The number is positive";}?>Output:The number is positive
Flowchart:
Syntax :
if (condition){
// if TRUE then execute this code
}
Example:
<?php$x = 12; if ($x > 0) { echo "The number is positive";}?>
Output:
The number is positive
Flowchart:
if...else Statement: We understood that if a condition will hold i.e., TRUE, then the block of code within if will be executed. But what if the condition is not TRUE and we want to perform an action? This is where else comes into play. If a condition is TRUE then if block gets executed, otherwise else block gets executed.Syntax:if (condition) {
// if TRUE then execute this code
}
else{
// if FALSE then execute this code
}
Example:<?php$x = -12; if ($x > 0) { echo "The number is positive";} else{ echo "The number is negative";}?>Output:The number is negative
Flowchart:
Syntax:
if (condition) {
// if TRUE then execute this code
}
else{
// if FALSE then execute this code
}
Example:
<?php$x = -12; if ($x > 0) { echo "The number is positive";} else{ echo "The number is negative";}?>
Output:
The number is negative
Flowchart:
if...elseif...else Statement: This allows us to use multiple if...else statements. We use this when there are multiple conditions of TRUE cases.Syntax:if (condition) {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
else {
// if FALSE then execute this code
}
Example:<?php$x = "August"; if ($x == "January") { echo "Happy Republic Day";} elseif ($x == "August") { echo "Happy Independence Day!!!";} else{ echo "Nothing to show";}?>Output:Happy Independence Day!!!
Flowchart:
if (condition) {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
else {
// if FALSE then execute this code
}
Example:
<?php$x = "August"; if ($x == "January") { echo "Happy Republic Day";} elseif ($x == "August") { echo "Happy Independence Day!!!";} else{ echo "Nothing to show";}?>
Output:
Happy Independence Day!!!
Flowchart:
switch Statement: The “switch” performs in various cases i.e., it has various cases to which it matches the condition and appropriately executes a particular case block. It first evaluates an expression and then compares with the values of each case. If a case matches then the same case is executed. To use switch, we need to get familiar with two different keywords namely, break and default.The break statement is used to stop the automatic control flow into the next cases and exit from the switch case.The default statement contains the code that would execute if none of the cases match.Syntax:switch(n) {
case statement1:
code to be executed if n==statement1;
break;
case statement2:
code to be executed if n==statement2;
break;
case statement3:
code to be executed if n==statement3;
break;
case statement4:
code to be executed if n==statement4;
break;
......
default:
code to be executed if n != any case;
Example:<?php$n = "February"; switch($n) { case "January": echo "Its January"; break; case "February": echo "Its February"; break; case "March": echo "Its March"; break; case "April": echo "Its April"; break; case "May": echo "Its May"; break; case "June": echo "Its June"; break; case "July": echo "Its July"; break; case "August": echo "Its August"; break; case "September": echo "Its September"; break; case "October": echo "Its October"; break; case "November": echo "Its November"; break; case "December": echo "Its December"; break; default: echo "Doesn't exist";}?>Output:Its February
Flowchart:
The break statement is used to stop the automatic control flow into the next cases and exit from the switch case.The default statement contains the code that would execute if none of the cases match.
The break statement is used to stop the automatic control flow into the next cases and exit from the switch case.
The default statement contains the code that would execute if none of the cases match.
Syntax:
switch(n) {
case statement1:
code to be executed if n==statement1;
break;
case statement2:
code to be executed if n==statement2;
break;
case statement3:
code to be executed if n==statement3;
break;
case statement4:
code to be executed if n==statement4;
break;
......
default:
code to be executed if n != any case;
Example:
<?php$n = "February"; switch($n) { case "January": echo "Its January"; break; case "February": echo "Its February"; break; case "March": echo "Its March"; break; case "April": echo "Its April"; break; case "May": echo "Its May"; break; case "June": echo "Its June"; break; case "July": echo "Its July"; break; case "August": echo "Its August"; break; case "September": echo "Its September"; break; case "October": echo "Its October"; break; case "November": echo "Its November"; break; case "December": echo "Its December"; break; default: echo "Doesn't exist";}?>
Output:
Its February
Flowchart:
Ternary Operators
In addition to all this conditional statements, PHP provides a shorthand way of writing if...else, called Ternary Operators. The statement uses a question mark (?) and a colon (:) and takes three operands: a condition to check, a result for TRUE and a result for FALSE.Syntax:
(condition) ? if TRUE execute this : otherwise execute this;
Example:
<?php$x = -12; if ($x > 0) { echo "The number is positive \n";}else { echo "The number is negative \n";} // This whole lot can be written in a // single line using ternary operatorecho ($x > 0) ? 'The number is positive' : 'The number is negative';?>
Output:
The number is negative
The number is negative
This article is contributed by Chinmoy Lenka. 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.
surindertarika1234
kapoorsagar226
PHP-basics
PHP
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
PHP in_array() Function
How to convert array to string in PHP ?
How to delete an array element based on key in PHP?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
File uploading in React.js
|
[
{
"code": null,
"e": 42163,
"s": 42135,
"text": "\n01 Sep, 2021"
},
{
"code": null,
"e": 42549,
"s": 42163,
"text": "PHP allows us to perform actions based on some type of conditions that may be logical or comparative. Based on the result of these conditions i.e., either TRUE or FALSE, an action would be performed as asked by the user. It’s just like a two- way path. If you want something then go this way or else turn that way. To use this feature, PHP provides us with four conditional statements:"
},
{
"code": null,
"e": 42562,
"s": 42549,
"text": "if statement"
},
{
"code": null,
"e": 42582,
"s": 42562,
"text": "if...else statement"
},
{
"code": null,
"e": 42611,
"s": 42582,
"text": "if...elseif...else statement"
},
{
"code": null,
"e": 42628,
"s": 42611,
"text": "switch statement"
},
{
"code": null,
"e": 42677,
"s": 42628,
"text": "Let us now look at each one of these in details:"
},
{
"code": null,
"e": 46003,
"s": 42677,
"text": "if Statement: This statement allows us to set a condition. On being TRUE, the following block of code enclosed within the if clause will be executed.Syntax :if (condition){\n // if TRUE then execute this code\n}\nExample:<?php$x = 12; if ($x > 0) { echo \"The number is positive\";}?>Output:The number is positive\nFlowchart:if...else Statement: We understood that if a condition will hold i.e., TRUE, then the block of code within if will be executed. But what if the condition is not TRUE and we want to perform an action? This is where else comes into play. If a condition is TRUE then if block gets executed, otherwise else block gets executed.Syntax:if (condition) {\n // if TRUE then execute this code\n}\nelse{\n // if FALSE then execute this code\n}\nExample:<?php$x = -12; if ($x > 0) { echo \"The number is positive\";} else{ echo \"The number is negative\";}?>Output:The number is negative\nFlowchart:if...elseif...else Statement: This allows us to use multiple if...else statements. We use this when there are multiple conditions of TRUE cases.Syntax:if (condition) {\n // if TRUE then execute this code\n}\nelseif {\n // if TRUE then execute this code\n}\nelseif {\n // if TRUE then execute this code\n}\nelse {\n // if FALSE then execute this code\n}\nExample:<?php$x = \"August\"; if ($x == \"January\") { echo \"Happy Republic Day\";} elseif ($x == \"August\") { echo \"Happy Independence Day!!!\";} else{ echo \"Nothing to show\";}?>Output:Happy Independence Day!!!\nFlowchart:switch Statement: The “switch” performs in various cases i.e., it has various cases to which it matches the condition and appropriately executes a particular case block. It first evaluates an expression and then compares with the values of each case. If a case matches then the same case is executed. To use switch, we need to get familiar with two different keywords namely, break and default.The break statement is used to stop the automatic control flow into the next cases and exit from the switch case.The default statement contains the code that would execute if none of the cases match.Syntax:switch(n) {\n case statement1:\n code to be executed if n==statement1;\n break;\n case statement2:\n code to be executed if n==statement2;\n break;\n case statement3:\n code to be executed if n==statement3;\n break;\n case statement4:\n code to be executed if n==statement4;\n break;\n ......\n default:\n code to be executed if n != any case;\n\nExample:<?php$n = \"February\"; switch($n) { case \"January\": echo \"Its January\"; break; case \"February\": echo \"Its February\"; break; case \"March\": echo \"Its March\"; break; case \"April\": echo \"Its April\"; break; case \"May\": echo \"Its May\"; break; case \"June\": echo \"Its June\"; break; case \"July\": echo \"Its July\"; break; case \"August\": echo \"Its August\"; break; case \"September\": echo \"Its September\"; break; case \"October\": echo \"Its October\"; break; case \"November\": echo \"Its November\"; break; case \"December\": echo \"Its December\"; break; default: echo \"Doesn't exist\";}?>Output:Its February\nFlowchart:"
},
{
"code": null,
"e": 46330,
"s": 46003,
"text": "if Statement: This statement allows us to set a condition. On being TRUE, the following block of code enclosed within the if clause will be executed.Syntax :if (condition){\n // if TRUE then execute this code\n}\nExample:<?php$x = 12; if ($x > 0) { echo \"The number is positive\";}?>Output:The number is positive\nFlowchart:"
},
{
"code": null,
"e": 46339,
"s": 46330,
"text": "Syntax :"
},
{
"code": null,
"e": 46396,
"s": 46339,
"text": "if (condition){\n // if TRUE then execute this code\n}\n"
},
{
"code": null,
"e": 46405,
"s": 46396,
"text": "Example:"
},
{
"code": "<?php$x = 12; if ($x > 0) { echo \"The number is positive\";}?>",
"e": 46471,
"s": 46405,
"text": null
},
{
"code": null,
"e": 46479,
"s": 46471,
"text": "Output:"
},
{
"code": null,
"e": 46503,
"s": 46479,
"text": "The number is positive\n"
},
{
"code": null,
"e": 46514,
"s": 46503,
"text": "Flowchart:"
},
{
"code": null,
"e": 47105,
"s": 46514,
"text": "if...else Statement: We understood that if a condition will hold i.e., TRUE, then the block of code within if will be executed. But what if the condition is not TRUE and we want to perform an action? This is where else comes into play. If a condition is TRUE then if block gets executed, otherwise else block gets executed.Syntax:if (condition) {\n // if TRUE then execute this code\n}\nelse{\n // if FALSE then execute this code\n}\nExample:<?php$x = -12; if ($x > 0) { echo \"The number is positive\";} else{ echo \"The number is negative\";}?>Output:The number is negative\nFlowchart:"
},
{
"code": null,
"e": 47113,
"s": 47105,
"text": "Syntax:"
},
{
"code": null,
"e": 47218,
"s": 47113,
"text": "if (condition) {\n // if TRUE then execute this code\n}\nelse{\n // if FALSE then execute this code\n}\n"
},
{
"code": null,
"e": 47227,
"s": 47218,
"text": "Example:"
},
{
"code": "<?php$x = -12; if ($x > 0) { echo \"The number is positive\";} else{ echo \"The number is negative\";}?>",
"e": 47336,
"s": 47227,
"text": null
},
{
"code": null,
"e": 47344,
"s": 47336,
"text": "Output:"
},
{
"code": null,
"e": 47368,
"s": 47344,
"text": "The number is negative\n"
},
{
"code": null,
"e": 47379,
"s": 47368,
"text": "Flowchart:"
},
{
"code": null,
"e": 47961,
"s": 47379,
"text": "if...elseif...else Statement: This allows us to use multiple if...else statements. We use this when there are multiple conditions of TRUE cases.Syntax:if (condition) {\n // if TRUE then execute this code\n}\nelseif {\n // if TRUE then execute this code\n}\nelseif {\n // if TRUE then execute this code\n}\nelse {\n // if FALSE then execute this code\n}\nExample:<?php$x = \"August\"; if ($x == \"January\") { echo \"Happy Republic Day\";} elseif ($x == \"August\") { echo \"Happy Independence Day!!!\";} else{ echo \"Nothing to show\";}?>Output:Happy Independence Day!!!\nFlowchart:"
},
{
"code": null,
"e": 48165,
"s": 47961,
"text": "if (condition) {\n // if TRUE then execute this code\n}\nelseif {\n // if TRUE then execute this code\n}\nelseif {\n // if TRUE then execute this code\n}\nelse {\n // if FALSE then execute this code\n}\n"
},
{
"code": null,
"e": 48174,
"s": 48165,
"text": "Example:"
},
{
"code": "<?php$x = \"August\"; if ($x == \"January\") { echo \"Happy Republic Day\";} elseif ($x == \"August\") { echo \"Happy Independence Day!!!\";} else{ echo \"Nothing to show\";}?>",
"e": 48351,
"s": 48174,
"text": null
},
{
"code": null,
"e": 48359,
"s": 48351,
"text": "Output:"
},
{
"code": null,
"e": 48386,
"s": 48359,
"text": "Happy Independence Day!!!\n"
},
{
"code": null,
"e": 48397,
"s": 48386,
"text": "Flowchart:"
},
{
"code": null,
"e": 50226,
"s": 48397,
"text": "switch Statement: The “switch” performs in various cases i.e., it has various cases to which it matches the condition and appropriately executes a particular case block. It first evaluates an expression and then compares with the values of each case. If a case matches then the same case is executed. To use switch, we need to get familiar with two different keywords namely, break and default.The break statement is used to stop the automatic control flow into the next cases and exit from the switch case.The default statement contains the code that would execute if none of the cases match.Syntax:switch(n) {\n case statement1:\n code to be executed if n==statement1;\n break;\n case statement2:\n code to be executed if n==statement2;\n break;\n case statement3:\n code to be executed if n==statement3;\n break;\n case statement4:\n code to be executed if n==statement4;\n break;\n ......\n default:\n code to be executed if n != any case;\n\nExample:<?php$n = \"February\"; switch($n) { case \"January\": echo \"Its January\"; break; case \"February\": echo \"Its February\"; break; case \"March\": echo \"Its March\"; break; case \"April\": echo \"Its April\"; break; case \"May\": echo \"Its May\"; break; case \"June\": echo \"Its June\"; break; case \"July\": echo \"Its July\"; break; case \"August\": echo \"Its August\"; break; case \"September\": echo \"Its September\"; break; case \"October\": echo \"Its October\"; break; case \"November\": echo \"Its November\"; break; case \"December\": echo \"Its December\"; break; default: echo \"Doesn't exist\";}?>Output:Its February\nFlowchart:"
},
{
"code": null,
"e": 50426,
"s": 50226,
"text": "The break statement is used to stop the automatic control flow into the next cases and exit from the switch case.The default statement contains the code that would execute if none of the cases match."
},
{
"code": null,
"e": 50540,
"s": 50426,
"text": "The break statement is used to stop the automatic control flow into the next cases and exit from the switch case."
},
{
"code": null,
"e": 50627,
"s": 50540,
"text": "The default statement contains the code that would execute if none of the cases match."
},
{
"code": null,
"e": 50635,
"s": 50627,
"text": "Syntax:"
},
{
"code": null,
"e": 51047,
"s": 50635,
"text": "switch(n) {\n case statement1:\n code to be executed if n==statement1;\n break;\n case statement2:\n code to be executed if n==statement2;\n break;\n case statement3:\n code to be executed if n==statement3;\n break;\n case statement4:\n code to be executed if n==statement4;\n break;\n ......\n default:\n code to be executed if n != any case;\n\n"
},
{
"code": null,
"e": 51056,
"s": 51047,
"text": "Example:"
},
{
"code": "<?php$n = \"February\"; switch($n) { case \"January\": echo \"Its January\"; break; case \"February\": echo \"Its February\"; break; case \"March\": echo \"Its March\"; break; case \"April\": echo \"Its April\"; break; case \"May\": echo \"Its May\"; break; case \"June\": echo \"Its June\"; break; case \"July\": echo \"Its July\"; break; case \"August\": echo \"Its August\"; break; case \"September\": echo \"Its September\"; break; case \"October\": echo \"Its October\"; break; case \"November\": echo \"Its November\"; break; case \"December\": echo \"Its December\"; break; default: echo \"Doesn't exist\";}?>",
"e": 51836,
"s": 51056,
"text": null
},
{
"code": null,
"e": 51844,
"s": 51836,
"text": "Output:"
},
{
"code": null,
"e": 51858,
"s": 51844,
"text": "Its February\n"
},
{
"code": null,
"e": 51869,
"s": 51858,
"text": "Flowchart:"
},
{
"code": null,
"e": 51887,
"s": 51869,
"text": "Ternary Operators"
},
{
"code": null,
"e": 52164,
"s": 51887,
"text": "In addition to all this conditional statements, PHP provides a shorthand way of writing if...else, called Ternary Operators. The statement uses a question mark (?) and a colon (:) and takes three operands: a condition to check, a result for TRUE and a result for FALSE.Syntax:"
},
{
"code": null,
"e": 52225,
"s": 52164,
"text": "(condition) ? if TRUE execute this : otherwise execute this;"
},
{
"code": null,
"e": 52234,
"s": 52225,
"text": "Example:"
},
{
"code": "<?php$x = -12; if ($x > 0) { echo \"The number is positive \\n\";}else { echo \"The number is negative \\n\";} // This whole lot can be written in a // single line using ternary operatorecho ($x > 0) ? 'The number is positive' : 'The number is negative';?>",
"e": 52509,
"s": 52234,
"text": null
},
{
"code": null,
"e": 52517,
"s": 52509,
"text": "Output:"
},
{
"code": null,
"e": 52564,
"s": 52517,
"text": "The number is negative\nThe number is negative\n"
},
{
"code": null,
"e": 52861,
"s": 52564,
"text": "This article is contributed by Chinmoy Lenka. 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."
},
{
"code": null,
"e": 52986,
"s": 52861,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 53005,
"s": 52986,
"text": "surindertarika1234"
},
{
"code": null,
"e": 53020,
"s": 53005,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 53031,
"s": 53020,
"text": "PHP-basics"
},
{
"code": null,
"e": 53035,
"s": 53031,
"text": "PHP"
},
{
"code": null,
"e": 53062,
"s": 53035,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 53066,
"s": 53062,
"text": "PHP"
},
{
"code": null,
"e": 53164,
"s": 53066,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 53209,
"s": 53164,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 53259,
"s": 53209,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 53283,
"s": 53259,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 53323,
"s": 53283,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 53375,
"s": 53323,
"text": "How to delete an array element based on key in PHP?"
},
{
"code": null,
"e": 53415,
"s": 53375,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 53448,
"s": 53415,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 53498,
"s": 53448,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 53558,
"s": 53498,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
Bean life cycle in Java Spring - GeeksforGeeks
|
02 Sep, 2021
Pre-requisite: Introduction to Spring Framework
The lifecycle of any object means when & how it is born, how it behaves throughout its life, and when & how it dies. Similarly, the bean life cycle refers to when & how the bean is instantiated, what action it performs until it lives, and when & how it is destroyed. In this article, we will discuss the life cycle of the bean.
Bean life cycle is managed by the spring container. When we run the program then, first of all, the spring container gets started. After that, the container creates the instance of a bean as per the request, and then dependencies are injected. And finally, the bean is destroyed when the spring container is closed. Therefore, if we want to execute some code on the bean instantiation and just after closing the spring container, then we can write that code inside the custom init() method and the destroy() method.
The following image shows the process flow of the bean life cycle.
Bean Life Cycle Process Flow
Note: We can choose custom method name instead of init() and destroy(). Here, we will use init() method to execute all its code as the spring container starts up and the bean is instantiated, and destroy() method to execute all its code on closing the container.
Ways to implement the life cycle of a beanSpring provides three ways to implement the life cycle of a bean. In order to understand these three ways, let’s take an example. In this example, we will write and activate init() and destroy() method for our bean (HelloWorld.java) to print some message on start and close of Spring container. Therefore, the three ways to implement this are:
1. By XML: In this approach, in order to avail custom init() and destroy() method for a bean we have to register these two methods inside Spring XML configuration file while defining a bean. Therefore, the following steps are followed:
Firstly, we need to create a bean HelloWorld.java in this case and write the init() and destroy() methods in the class.
Java
// Java program to create a bean// in the spring frameworkpackage beans; public class HelloWorld { // This method executes // automatically as the bean // is instantiated public void init() throws Exception { System.out.println( "Bean HelloWorld has been " + "instantiated and I'm " + "the init() method"); } // This method executes // when the spring container // is closed public void destroy() throws Exception { System.out.println( "Container has been closed " + "and I'm the destroy() method"); }}
Now, we need to configure the spring XML file spring.xml and need to register the init() and destroy() methods in it.
XML
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd"> <beans> <bean id="hw" class="beans.HelloWorld" init-method="init" destroy-method="destroy"/> </beans>
Finally, we need to create a driver class to run this bean.
Java
// Java program to call the// bean initialized above package test; import org.springframework .context .ConfigurableApplicationContext; import org.springframework .context.support .ClassPathXmlApplicationContext; import beans.HelloWorld; // Driver classpublic class Client { public static void main(String[] args) throws Exception { // Loading the Spring XML configuration // file into the spring container and // it will create the instance of // the bean as it loads into container ConfigurableApplicationContext cap = new ClassPathXmlApplicationContext( "resources/spring.xml"); // It will close the spring container // and as a result invokes the // destroy() method cap.close(); }}
Output:
Bean HelloWorld has been instantiated and I’m the init() method Container has been closed and I’m the destroy() method
2. By Programmatic Approach: To provide the facility to the created bean to invoke custom init() method on the startup of a spring container and to invoke the custom destroy() method on closing the container, we need to implement our bean with two interfaces namely InitializingBean, DisposableBean and will have to override afterPropertiesSet() and destroy() method. afterPropertiesSet() method is invoked as the container starts and the bean is instantiated whereas, the destroy() method is invoked just after the container is closed.
Note: To invoke destroy method we have to call a close() method of ConfigurableApplicationContext.
Therefore, the following steps are followed:
Firstly, we need to create a bean HelloWorld.java in this case by implementing InitializingBean, DisposableBean, and overriding afterPropertiesSet() and destroy() method.
Java
// Java program to create a bean// in the spring frameworkpackage beans; import org.springframework .beans.factory.DisposableBean; import org.springframework .beans.factory.InitializingBean; // HelloWorld class which implements the// interfacespublic class HelloWorld implements InitializingBean, DisposableBean { @Override // It is the init() method // of our bean and it gets // invoked on bean instantiation public void afterPropertiesSet()throws Exception { System.out.println( "Bean HelloWorld has been " + "instantiated and I'm the " + "init() method"); } @Override // This method is invoked // just after the container // is closed public void destroy() throws Exception { System.out.println( "Container has been closed " + "and I'm the destroy() method"); }}
Now, we need to configure the spring XML file spring.xml and define the bean.
XML
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd"> <beans> <bean id="hw" class="beans.HelloWorld"/> </beans>
Finally, we need to create a driver class to run this bean.
Java
// Java program to call the// bean initialized above package test; import org.springframework .context .ConfigurableApplicationContext; import org.springframework .context.support .ClassPathXmlApplicationContext; import beans.HelloWorld; // Driver classpublic class Client { public static void main(String[] args) throws Exception { // Loading the Spring XML configuration // file into the spring container and // it will create the instance of the bean // as it loads into container ConfigurableApplicationContext cap = new ClassPathXmlApplicationContext( "resources/spring.xml"); // It will close the spring container // and as a result invokes the // destroy() method cap.close(); }}
Output:
Bean HelloWorld has been instantiated and I’m the init() method Container has been closed and I’m the destroy() method
3. Using Annotation: To provide the facility to the created bean to invoke custom init() method on the startup of a spring container and to invoke the custom destroy() method on closing the container, we need annotate init() method by @PostConstruct annotation and destroy() method by @PreDestroy annotation.Note: To invoke the destroy() method we have to call the close() method of ConfigurableApplicationContext.
Therefore, the following steps are followed:
Firstly, we need to create a bean HelloWorld.java in this case and annotate the custom init() method with @PostConstruct and destroy() method with @PreDestroy.
Java
// Java program to create a bean// in the spring frameworkpackage beans; import javax.annotation.PostConstruct;import javax.annotation.PreDestroy; // HelloWorld classpublic class HelloWorld { // Annotate this method to execute it // automatically as the bean is // instantiated @PostConstruct public void init() throws Exception { System.out.println( "Bean HelloWorld has been " + "instantiated and I'm the " + "init() method"); } // Annotate this method to execute it // when Spring container is closed @PreDestroy public void destroy() throws Exception { System.out.println( "Container has been closed " + "and I'm the destroy() method"); }}
Now, we need to configure the spring XML file spring.xml and define the bean.
HTML
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd"> <beans> <!-- activate the @PostConstruct and@PreDestroy annotation --> <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/> <!-- configure the bean --> <bean class="beans.HelloWorld"/> </beans>
Finally, we need to create a driver class to run this bean.
Java
// Java program to call the// bean initialized above package test; import org.springframework .context .ConfigurableApplicationContext; import org.springframework .context.support .ClassPathXmlApplicationContext; import beans.HelloWorld; // Driver classpublic class Client { public static void main(String[] args) throws Exception { // Loading the Spring XML configuration // file into Spring container and // it will create the instance of the // bean as it loads into container ConfigurableApplicationContext cap = new ClassPathXmlApplicationContext( "resources/spring.xml"); // It will close the Spring container // and as a result invokes the // destroy() method cap.close(); }}
Output:
Bean HelloWorld has been instantiated and I’m the init() method Container has been closed and I’m the destroy() method
singghakshay
varshagumber28
java-advanced
Java-Spring
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
|
[
{
"code": null,
"e": 25623,
"s": 25595,
"text": "\n02 Sep, 2021"
},
{
"code": null,
"e": 25671,
"s": 25623,
"text": "Pre-requisite: Introduction to Spring Framework"
},
{
"code": null,
"e": 26000,
"s": 25671,
"text": "The lifecycle of any object means when & how it is born, how it behaves throughout its life, and when & how it dies. Similarly, the bean life cycle refers to when & how the bean is instantiated, what action it performs until it lives, and when & how it is destroyed. In this article, we will discuss the life cycle of the bean. "
},
{
"code": null,
"e": 26516,
"s": 26000,
"text": "Bean life cycle is managed by the spring container. When we run the program then, first of all, the spring container gets started. After that, the container creates the instance of a bean as per the request, and then dependencies are injected. And finally, the bean is destroyed when the spring container is closed. Therefore, if we want to execute some code on the bean instantiation and just after closing the spring container, then we can write that code inside the custom init() method and the destroy() method."
},
{
"code": null,
"e": 26585,
"s": 26516,
"text": "The following image shows the process flow of the bean life cycle. "
},
{
"code": null,
"e": 26614,
"s": 26585,
"text": "Bean Life Cycle Process Flow"
},
{
"code": null,
"e": 26878,
"s": 26614,
"text": "Note: We can choose custom method name instead of init() and destroy(). Here, we will use init() method to execute all its code as the spring container starts up and the bean is instantiated, and destroy() method to execute all its code on closing the container. "
},
{
"code": null,
"e": 27265,
"s": 26878,
"text": "Ways to implement the life cycle of a beanSpring provides three ways to implement the life cycle of a bean. In order to understand these three ways, let’s take an example. In this example, we will write and activate init() and destroy() method for our bean (HelloWorld.java) to print some message on start and close of Spring container. Therefore, the three ways to implement this are: "
},
{
"code": null,
"e": 27502,
"s": 27265,
"text": "1. By XML: In this approach, in order to avail custom init() and destroy() method for a bean we have to register these two methods inside Spring XML configuration file while defining a bean. Therefore, the following steps are followed: "
},
{
"code": null,
"e": 27622,
"s": 27502,
"text": "Firstly, we need to create a bean HelloWorld.java in this case and write the init() and destroy() methods in the class."
},
{
"code": null,
"e": 27627,
"s": 27622,
"text": "Java"
},
{
"code": "// Java program to create a bean// in the spring frameworkpackage beans; public class HelloWorld { // This method executes // automatically as the bean // is instantiated public void init() throws Exception { System.out.println( \"Bean HelloWorld has been \" + \"instantiated and I'm \" + \"the init() method\"); } // This method executes // when the spring container // is closed public void destroy() throws Exception { System.out.println( \"Container has been closed \" + \"and I'm the destroy() method\"); }}",
"e": 28237,
"s": 27627,
"text": null
},
{
"code": null,
"e": 28355,
"s": 28237,
"text": "Now, we need to configure the spring XML file spring.xml and need to register the init() and destroy() methods in it."
},
{
"code": null,
"e": 28359,
"s": 28355,
"text": "XML"
},
{
"code": "<!DOCTYPE beans PUBLIC \"-//SPRING//DTD BEAN 2.0//EN\" \"http://www.springframework.org/dtd/spring-beans-2.0.dtd\"> <beans> <bean id=\"hw\" class=\"beans.HelloWorld\" init-method=\"init\" destroy-method=\"destroy\"/> </beans>",
"e": 28613,
"s": 28359,
"text": null
},
{
"code": null,
"e": 28673,
"s": 28613,
"text": "Finally, we need to create a driver class to run this bean."
},
{
"code": null,
"e": 28678,
"s": 28673,
"text": "Java"
},
{
"code": "// Java program to call the// bean initialized above package test; import org.springframework .context .ConfigurableApplicationContext; import org.springframework .context.support .ClassPathXmlApplicationContext; import beans.HelloWorld; // Driver classpublic class Client { public static void main(String[] args) throws Exception { // Loading the Spring XML configuration // file into the spring container and // it will create the instance of // the bean as it loads into container ConfigurableApplicationContext cap = new ClassPathXmlApplicationContext( \"resources/spring.xml\"); // It will close the spring container // and as a result invokes the // destroy() method cap.close(); }}",
"e": 29486,
"s": 28678,
"text": null
},
{
"code": null,
"e": 29495,
"s": 29486,
"text": "Output: "
},
{
"code": null,
"e": 29616,
"s": 29495,
"text": "Bean HelloWorld has been instantiated and I’m the init() method Container has been closed and I’m the destroy() method "
},
{
"code": null,
"e": 30154,
"s": 29616,
"text": "2. By Programmatic Approach: To provide the facility to the created bean to invoke custom init() method on the startup of a spring container and to invoke the custom destroy() method on closing the container, we need to implement our bean with two interfaces namely InitializingBean, DisposableBean and will have to override afterPropertiesSet() and destroy() method. afterPropertiesSet() method is invoked as the container starts and the bean is instantiated whereas, the destroy() method is invoked just after the container is closed. "
},
{
"code": null,
"e": 30253,
"s": 30154,
"text": "Note: To invoke destroy method we have to call a close() method of ConfigurableApplicationContext."
},
{
"code": null,
"e": 30299,
"s": 30253,
"text": "Therefore, the following steps are followed: "
},
{
"code": null,
"e": 30470,
"s": 30299,
"text": "Firstly, we need to create a bean HelloWorld.java in this case by implementing InitializingBean, DisposableBean, and overriding afterPropertiesSet() and destroy() method."
},
{
"code": null,
"e": 30475,
"s": 30470,
"text": "Java"
},
{
"code": "// Java program to create a bean// in the spring frameworkpackage beans; import org.springframework .beans.factory.DisposableBean; import org.springframework .beans.factory.InitializingBean; // HelloWorld class which implements the// interfacespublic class HelloWorld implements InitializingBean, DisposableBean { @Override // It is the init() method // of our bean and it gets // invoked on bean instantiation public void afterPropertiesSet()throws Exception { System.out.println( \"Bean HelloWorld has been \" + \"instantiated and I'm the \" + \"init() method\"); } @Override // This method is invoked // just after the container // is closed public void destroy() throws Exception { System.out.println( \"Container has been closed \" + \"and I'm the destroy() method\"); }}",
"e": 31364,
"s": 30475,
"text": null
},
{
"code": null,
"e": 31442,
"s": 31364,
"text": "Now, we need to configure the spring XML file spring.xml and define the bean."
},
{
"code": null,
"e": 31446,
"s": 31442,
"text": "XML"
},
{
"code": "<!DOCTYPE beans PUBLIC \"-//SPRING//DTD BEAN 2.0//EN\" \"http://www.springframework.org/dtd/spring-beans-2.0.dtd\"> <beans> <bean id=\"hw\" class=\"beans.HelloWorld\"/> </beans>",
"e": 31646,
"s": 31446,
"text": null
},
{
"code": null,
"e": 31706,
"s": 31646,
"text": "Finally, we need to create a driver class to run this bean."
},
{
"code": null,
"e": 31711,
"s": 31706,
"text": "Java"
},
{
"code": "// Java program to call the// bean initialized above package test; import org.springframework .context .ConfigurableApplicationContext; import org.springframework .context.support .ClassPathXmlApplicationContext; import beans.HelloWorld; // Driver classpublic class Client { public static void main(String[] args) throws Exception { // Loading the Spring XML configuration // file into the spring container and // it will create the instance of the bean // as it loads into container ConfigurableApplicationContext cap = new ClassPathXmlApplicationContext( \"resources/spring.xml\"); // It will close the spring container // and as a result invokes the // destroy() method cap.close(); }}",
"e": 32518,
"s": 31711,
"text": null
},
{
"code": null,
"e": 32527,
"s": 32518,
"text": "Output: "
},
{
"code": null,
"e": 32648,
"s": 32527,
"text": "Bean HelloWorld has been instantiated and I’m the init() method Container has been closed and I’m the destroy() method "
},
{
"code": null,
"e": 33063,
"s": 32648,
"text": "3. Using Annotation: To provide the facility to the created bean to invoke custom init() method on the startup of a spring container and to invoke the custom destroy() method on closing the container, we need annotate init() method by @PostConstruct annotation and destroy() method by @PreDestroy annotation.Note: To invoke the destroy() method we have to call the close() method of ConfigurableApplicationContext."
},
{
"code": null,
"e": 33108,
"s": 33063,
"text": "Therefore, the following steps are followed:"
},
{
"code": null,
"e": 33268,
"s": 33108,
"text": "Firstly, we need to create a bean HelloWorld.java in this case and annotate the custom init() method with @PostConstruct and destroy() method with @PreDestroy."
},
{
"code": null,
"e": 33273,
"s": 33268,
"text": "Java"
},
{
"code": "// Java program to create a bean// in the spring frameworkpackage beans; import javax.annotation.PostConstruct;import javax.annotation.PreDestroy; // HelloWorld classpublic class HelloWorld { // Annotate this method to execute it // automatically as the bean is // instantiated @PostConstruct public void init() throws Exception { System.out.println( \"Bean HelloWorld has been \" + \"instantiated and I'm the \" + \"init() method\"); } // Annotate this method to execute it // when Spring container is closed @PreDestroy public void destroy() throws Exception { System.out.println( \"Container has been closed \" + \"and I'm the destroy() method\"); }}",
"e": 34027,
"s": 33273,
"text": null
},
{
"code": null,
"e": 34105,
"s": 34027,
"text": "Now, we need to configure the spring XML file spring.xml and define the bean."
},
{
"code": null,
"e": 34110,
"s": 34105,
"text": "HTML"
},
{
"code": "<!DOCTYPE beans PUBLIC \"-//SPRING//DTD BEAN 2.0//EN\" \"http://www.springframework.org/dtd/spring-beans-2.0.dtd\"> <beans> <!-- activate the @PostConstruct and@PreDestroy annotation --> <bean class=\"org.springframework.context.annotation.CommonAnnotationBeanPostProcessor\"/> <!-- configure the bean --> <bean class=\"beans.HelloWorld\"/> </beans>",
"e": 34494,
"s": 34110,
"text": null
},
{
"code": null,
"e": 34554,
"s": 34494,
"text": "Finally, we need to create a driver class to run this bean."
},
{
"code": null,
"e": 34559,
"s": 34554,
"text": "Java"
},
{
"code": "// Java program to call the// bean initialized above package test; import org.springframework .context .ConfigurableApplicationContext; import org.springframework .context.support .ClassPathXmlApplicationContext; import beans.HelloWorld; // Driver classpublic class Client { public static void main(String[] args) throws Exception { // Loading the Spring XML configuration // file into Spring container and // it will create the instance of the // bean as it loads into container ConfigurableApplicationContext cap = new ClassPathXmlApplicationContext( \"resources/spring.xml\"); // It will close the Spring container // and as a result invokes the // destroy() method cap.close(); }}",
"e": 35362,
"s": 34559,
"text": null
},
{
"code": null,
"e": 35371,
"s": 35362,
"text": "Output: "
},
{
"code": null,
"e": 35492,
"s": 35371,
"text": "Bean HelloWorld has been instantiated and I’m the init() method Container has been closed and I’m the destroy() method "
},
{
"code": null,
"e": 35507,
"s": 35494,
"text": "singghakshay"
},
{
"code": null,
"e": 35522,
"s": 35507,
"text": "varshagumber28"
},
{
"code": null,
"e": 35536,
"s": 35522,
"text": "java-advanced"
},
{
"code": null,
"e": 35548,
"s": 35536,
"text": "Java-Spring"
},
{
"code": null,
"e": 35553,
"s": 35548,
"text": "Java"
},
{
"code": null,
"e": 35558,
"s": 35553,
"text": "Java"
},
{
"code": null,
"e": 35656,
"s": 35558,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35671,
"s": 35656,
"text": "Stream In Java"
},
{
"code": null,
"e": 35701,
"s": 35671,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 35720,
"s": 35701,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 35751,
"s": 35720,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 35783,
"s": 35751,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 35801,
"s": 35783,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 35821,
"s": 35801,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 35845,
"s": 35821,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 35877,
"s": 35845,
"text": "Multidimensional Arrays in Java"
}
] |
Matplotlib - Axes Class - GeeksforGeeks
|
27 May, 2020
Matplotlib is one of the Python packages which is used for data visualization. You can use the NumPy library to convert data into an array and numerical mathematics extension of Python. Matplotlib library is used for making 2D plots from data in arrays.
Axes is the most basic and flexible unit for creating sub-plots. Axes allow placement of plots at any location in the figure. A given figure can contain many axes, but a given axes object can only be in one figure. The axes contain two axis objects 2D as well as, three-axis objects in the case of 3D. Let’s look at some basic functions of this class.
axes() function creates axes object with argument, where argument is a list of 4 elements [left, bottom, width, height]. Let us now take a brief look to understand the axes() function.
Syntax :
axes([left, bottom, width, height])
Example:
import matplotlib.pyplot as plt fig = plt.figure() #[left, bottom, width, height]ax = plt.axes([0.1, 0.1, 0.8, 0.8])
Output:
Here in axes([0.1, 0.1, 0.8, 0.8]), the first ‘0.1’ refers to the distance between the left side axis and border of the figure window is 10%, of the total width of the figure window. The second ‘0.1’ refers to the distance between the bottom side axis and the border of the figure window is 10%, of the total height of the figure window. The first ‘0.8’ means the axes width from left to right is 80% and the latter ‘0.8’ means the axes height from the bottom to the top is 80%.
Alternatively, you can also add the axes object to the figure by calling the add_axes() method. It returns the axes object and adds axes at position [left, bottom, width, height] where all quantities are in fractions of figure width and height.
Syntax :
add_axes([left, bottom, width, height])
Example :
import matplotlib.pyplot as plt fig = plt.figure() #[left, bottom, width, height]ax = fig.add_axes([0, 0, 1, 1])
Output:
Adding legend to the plot figure can be done by calling the legend() function of the axes class. It consists of three arguments.
Syntax :
ax.legend(handles, labels, loc)
Where labels refers to a sequence of string and handles, a sequence of Line2D or Patch instances, loc can be a string or an integer specifying the location of legend.
Example :
import matplotlib.pyplot as plt fig = plt.figure() #[left, bottom, width, height]ax = plt.axes([0.1, 0.1, 0.8, 0.8]) ax.legend(labels = ('label1', 'label2'), loc = 'upper left')
Output:
plot() function of the axes class plots the values of one array versus another as line or marker.
Syntax : plt.plot(X, Y, ‘CLM’)
Parameters:X is x-axis.Y is y-axis.‘CLM’ stands for Color, Line and Marker.
Note: Line can be of different styles such as dotted line (':'), dashed line ('—'), solid line ('-') and many more.
Marker codes
Example: The following example shows the graph of sine and cosine functions.
import matplotlib.pyplot as pltimport numpy as np X = np.linspace(-np.pi, np.pi, 15)C = np.cos(X)S = np.sin(X) # [left, bottom, width, height]ax = plt.axes([0.1, 0.1, 0.8, 0.8]) # 'bs:' mentions blue color, square # marker with dotted line.ax1 = ax.plot(X, C, 'bs:') #'ro-' mentions red color, circle # marker with solid line.ax2 = ax.plot(X, S, 'ro-') ax.legend(labels = ('Cosine Function', 'Sine Function'), loc = 'upper left') ax.set_title("Trigonometric Functions") plt.show()
Output:
Matplotlib axes-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
|
[
{
"code": null,
"e": 29911,
"s": 29883,
"text": "\n27 May, 2020"
},
{
"code": null,
"e": 30165,
"s": 29911,
"text": "Matplotlib is one of the Python packages which is used for data visualization. You can use the NumPy library to convert data into an array and numerical mathematics extension of Python. Matplotlib library is used for making 2D plots from data in arrays."
},
{
"code": null,
"e": 30517,
"s": 30165,
"text": "Axes is the most basic and flexible unit for creating sub-plots. Axes allow placement of plots at any location in the figure. A given figure can contain many axes, but a given axes object can only be in one figure. The axes contain two axis objects 2D as well as, three-axis objects in the case of 3D. Let’s look at some basic functions of this class."
},
{
"code": null,
"e": 30702,
"s": 30517,
"text": "axes() function creates axes object with argument, where argument is a list of 4 elements [left, bottom, width, height]. Let us now take a brief look to understand the axes() function."
},
{
"code": null,
"e": 30711,
"s": 30702,
"text": "Syntax :"
},
{
"code": null,
"e": 30747,
"s": 30711,
"text": "axes([left, bottom, width, height])"
},
{
"code": null,
"e": 30756,
"s": 30747,
"text": "Example:"
},
{
"code": "import matplotlib.pyplot as plt fig = plt.figure() #[left, bottom, width, height]ax = plt.axes([0.1, 0.1, 0.8, 0.8]) ",
"e": 30878,
"s": 30756,
"text": null
},
{
"code": null,
"e": 30886,
"s": 30878,
"text": "Output:"
},
{
"code": null,
"e": 31365,
"s": 30886,
"text": "Here in axes([0.1, 0.1, 0.8, 0.8]), the first ‘0.1’ refers to the distance between the left side axis and border of the figure window is 10%, of the total width of the figure window. The second ‘0.1’ refers to the distance between the bottom side axis and the border of the figure window is 10%, of the total height of the figure window. The first ‘0.8’ means the axes width from left to right is 80% and the latter ‘0.8’ means the axes height from the bottom to the top is 80%."
},
{
"code": null,
"e": 31610,
"s": 31365,
"text": "Alternatively, you can also add the axes object to the figure by calling the add_axes() method. It returns the axes object and adds axes at position [left, bottom, width, height] where all quantities are in fractions of figure width and height."
},
{
"code": null,
"e": 31619,
"s": 31610,
"text": "Syntax :"
},
{
"code": null,
"e": 31659,
"s": 31619,
"text": "add_axes([left, bottom, width, height])"
},
{
"code": null,
"e": 31669,
"s": 31659,
"text": "Example :"
},
{
"code": "import matplotlib.pyplot as plt fig = plt.figure() #[left, bottom, width, height]ax = fig.add_axes([0, 0, 1, 1])",
"e": 31786,
"s": 31669,
"text": null
},
{
"code": null,
"e": 31794,
"s": 31786,
"text": "Output:"
},
{
"code": null,
"e": 31923,
"s": 31794,
"text": "Adding legend to the plot figure can be done by calling the legend() function of the axes class. It consists of three arguments."
},
{
"code": null,
"e": 31932,
"s": 31923,
"text": "Syntax :"
},
{
"code": null,
"e": 31964,
"s": 31932,
"text": "ax.legend(handles, labels, loc)"
},
{
"code": null,
"e": 32131,
"s": 31964,
"text": "Where labels refers to a sequence of string and handles, a sequence of Line2D or Patch instances, loc can be a string or an integer specifying the location of legend."
},
{
"code": null,
"e": 32141,
"s": 32131,
"text": "Example :"
},
{
"code": "import matplotlib.pyplot as plt fig = plt.figure() #[left, bottom, width, height]ax = plt.axes([0.1, 0.1, 0.8, 0.8]) ax.legend(labels = ('label1', 'label2'), loc = 'upper left')",
"e": 32335,
"s": 32141,
"text": null
},
{
"code": null,
"e": 32343,
"s": 32335,
"text": "Output:"
},
{
"code": null,
"e": 32441,
"s": 32343,
"text": "plot() function of the axes class plots the values of one array versus another as line or marker."
},
{
"code": null,
"e": 32472,
"s": 32441,
"text": "Syntax : plt.plot(X, Y, ‘CLM’)"
},
{
"code": null,
"e": 32548,
"s": 32472,
"text": "Parameters:X is x-axis.Y is y-axis.‘CLM’ stands for Color, Line and Marker."
},
{
"code": null,
"e": 32664,
"s": 32548,
"text": "Note: Line can be of different styles such as dotted line (':'), dashed line ('—'), solid line ('-') and many more."
},
{
"code": null,
"e": 32677,
"s": 32664,
"text": "Marker codes"
},
{
"code": null,
"e": 32754,
"s": 32677,
"text": "Example: The following example shows the graph of sine and cosine functions."
},
{
"code": "import matplotlib.pyplot as pltimport numpy as np X = np.linspace(-np.pi, np.pi, 15)C = np.cos(X)S = np.sin(X) # [left, bottom, width, height]ax = plt.axes([0.1, 0.1, 0.8, 0.8]) # 'bs:' mentions blue color, square # marker with dotted line.ax1 = ax.plot(X, C, 'bs:') #'ro-' mentions red color, circle # marker with solid line.ax2 = ax.plot(X, S, 'ro-') ax.legend(labels = ('Cosine Function', 'Sine Function'), loc = 'upper left') ax.set_title(\"Trigonometric Functions\") plt.show()",
"e": 33277,
"s": 32754,
"text": null
},
{
"code": null,
"e": 33285,
"s": 33277,
"text": "Output:"
},
{
"code": null,
"e": 33307,
"s": 33285,
"text": "Matplotlib axes-class"
},
{
"code": null,
"e": 33325,
"s": 33307,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 33332,
"s": 33325,
"text": "Python"
},
{
"code": null,
"e": 33430,
"s": 33332,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33439,
"s": 33430,
"text": "Comments"
},
{
"code": null,
"e": 33452,
"s": 33439,
"text": "Old Comments"
},
{
"code": null,
"e": 33480,
"s": 33452,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 33530,
"s": 33480,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 33552,
"s": 33530,
"text": "Python map() function"
},
{
"code": null,
"e": 33596,
"s": 33552,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 33614,
"s": 33596,
"text": "Python Dictionary"
},
{
"code": null,
"e": 33637,
"s": 33614,
"text": "Taking input in Python"
},
{
"code": null,
"e": 33672,
"s": 33637,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 33694,
"s": 33672,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 33726,
"s": 33694,
"text": "How to Install PIP on Windows ?"
}
] |
Dynamically add elements in ListView in android?
|
This example demonstrates how do I dynamically add elements in ListView in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_centerHorizontal="true"
android:text="Add Values to listView" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:ems="10"
android:hint="Add elements listView" />
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity {
ListView listview;
Button addButton;
EditText GetValue;
String[] ListElements = new String[] {
"Android",
"PHP",
"Python",
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = findViewById(R.id.listView1);
addButton = findViewById(R.id.button1);
GetValue = findViewById(R.id.editText1);
final List<String> ListElementsArrayList = new ArrayList<>(Arrays.asList(ListElements));
final ArrayAdapter<String> adapter = new ArrayAdapter<>
(MainActivity.this, android.R.layout.simple_list_item_1, ListElementsArrayList);
listview.setAdapter(adapter);
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ListElementsArrayList.add(GetValue.getText().toString());
adapter.notifyDataSetChanged();
}
});
}
}
Step 4 - Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
|
[
{
"code": null,
"e": 1146,
"s": 1062,
"text": "This example demonstrates how do I dynamically add elements in ListView in android."
},
{
"code": null,
"e": 1275,
"s": 1146,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1340,
"s": 1275,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2426,
"s": 1340,
"text": "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\" >\n\n <Button\n android:id=\"@+id/button1\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@+id/editText1\"\n android:layout_centerHorizontal=\"true\"\n android:text=\"Add Values to listView\" />\n\n <EditText\n android:id=\"@+id/editText1\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"26dp\"\n android:ems=\"10\"\n android:hint=\"Add elements listView\" />\n\n <ListView\n android:id=\"@+id/listView1\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@+id/button1\"\n android:layout_centerHorizontal=\"true\" >\n </ListView>\n</RelativeLayout>"
},
{
"code": null,
"e": 2483,
"s": 2426,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3821,
"s": 2483,
"text": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.ListView;\n\npublic class MainActivity extends Activity {\n\n ListView listview;\n Button addButton;\n EditText GetValue;\n String[] ListElements = new String[] {\n \"Android\",\n \"PHP\",\n \"Python\",\n };\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n listview = findViewById(R.id.listView1);\n addButton = findViewById(R.id.button1);\n GetValue = findViewById(R.id.editText1);\n\n final List<String> ListElementsArrayList = new ArrayList<>(Arrays.asList(ListElements));\n final ArrayAdapter<String> adapter = new ArrayAdapter<>\n (MainActivity.this, android.R.layout.simple_list_item_1, ListElementsArrayList);\n listview.setAdapter(adapter);\n\n addButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n ListElementsArrayList.add(GetValue.getText().toString());\n adapter.notifyDataSetChanged();\n }\n });\n }\n}"
},
{
"code": null,
"e": 3876,
"s": 3821,
"text": "Step 4 - Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4550,
"s": 3876,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4897,
"s": 4550,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
}
] |
Excel DAX - Calculated Columns
|
A calculated column is a column that you add to an existing table in the Data Model of your workbook by means of a DAX formula that defines the column values. Instead of importing the values in the column, you create the calculated column.
You can use the calculated column in a PivotTable, PivotChart, Power PivotTable, Power PivotChart or Power View report just like any other table column.
The DAX formula used to create a calculated column is like an Excel formula. However, in DAX formula, you cannot create different formulas for different rows in a table. The DAX formula is automatically applied to the entire column.
For example, you can create one calculated column to extract Year from the existing column – Date, with the DAX formula −
= YEAR ([Date])
YEAR is a DAX function and Date is an existing column in the table. As seen, the table name is enclosed in brackets. You will learn more about this in the chapter – DAX Syntax.
When you add a column to a table with this DAX formula, the column values are computed as soon as you create the formula. A new column with the header CalculatedColumn1 filled with Year values will get created.
Column values are recalculated as necessary, such as when the underlying data is refreshed. You can create calculated columns based on existing columns, calculated fields (measures), and other calculated columns.
Consider the Data Model with the Olympics Results as shown in the following screenshot.
Click the Data View.
Click the Results tab.
You will be viewing the Results table.
As seen in the above screenshot, the rightmost column has the header – Add Column.
Click the Design tab on the Ribbon.
Click Add in the Columns group.
The pointer will appear in the formula bar. That means you are adding a column with a DAX formula.
Type =YEAR ([Date]) in the formula bar.
As can be seen in the above screenshot, the rightmost column with the header – Add Column is highlighted.
Press Enter.
It will take a while (few seconds) for the calculations to be done. Please wait.
The new calculated column will get inserted to the left of the rightmost Add Column.
As shown in the above screenshot, the newly inserted calculated column is highlighted. Values in the entire column appear as per the DAX formula used. The column header is CalculatedColumn1.
To rename the calculated column to a meaningful name, do the following −
Double-click on the column header. The column name will be highlighted.
Select the column name.
Type Year (the new name).
As seen in the above screenshot, the name of the calculated column got changed.
You can also rename a calculated column by right-clicking on the column and then clicking on Rename in the dropdown list.
Just make sure that the new name does not conflict with an existing name in the table.
You can check the data type of the calculated column as follows −
Click the Home tab on the Ribbon.
Click the Data Type.
As you can see in the above screenshot, the dropdown list has the possible data types for the columns. In this example, the default (Auto) data type, i.e. the Whole Number is selected.
Errors can occur in the calculated columns for the following reasons −
Changing or deleting relationships between the tables. This is because the formulas that use columns in those tables will become invalid.
Changing or deleting relationships between the tables. This is because the formulas that use columns in those tables will become invalid.
The formula contains a circular or self-referencing dependency.
The formula contains a circular or self-referencing dependency.
As seen earlier in the example of Olympics results, the Results table has about 35000 rows of data. Hence, when you created a column with a DAX formula, it had calculated all the 35000+ values in the column at once, for which it took a little while. The Data Model and the tables are meant to handle millions of rows of data. Hence, it can affect the performance when the DAX formula has too many references. You can avoid the performance issues doing the following −
If your DAX formula contains many complex dependencies, then create it in steps saving the results in new calculated columns, instead of creating a single big formula at once. This enables you to validate the results and assess the performance.
If your DAX formula contains many complex dependencies, then create it in steps saving the results in new calculated columns, instead of creating a single big formula at once. This enables you to validate the results and assess the performance.
Calculated columns need to be recalculated when data modifications occur. You can set the recalculation mode to manual, thus saving frequent recalculations. However, if any values in the calculated column are incorrect, the column will be grayed out, until you refresh and recalculate the data.
Calculated columns need to be recalculated when data modifications occur. You can set the recalculation mode to manual, thus saving frequent recalculations. However, if any values in the calculated column are incorrect, the column will be grayed out, until you refresh and recalculate the data.
102 Lectures
10 hours
Pavan Lalwani
101 Lectures
6 hours
Pavan Lalwani
56 Lectures
5.5 hours
Pavan Lalwani
63 Lectures
3.5 hours
Yoda Learning
134 Lectures
8.5 hours
Yoda Learning
33 Lectures
3 hours
Abhishek And Pukhraj
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2489,
"s": 2249,
"text": "A calculated column is a column that you add to an existing table in the Data Model of your workbook by means of a DAX formula that defines the column values. Instead of importing the values in the column, you create the calculated column."
},
{
"code": null,
"e": 2642,
"s": 2489,
"text": "You can use the calculated column in a PivotTable, PivotChart, Power PivotTable, Power PivotChart or Power View report just like any other table column."
},
{
"code": null,
"e": 2875,
"s": 2642,
"text": "The DAX formula used to create a calculated column is like an Excel formula. However, in DAX formula, you cannot create different formulas for different rows in a table. The DAX formula is automatically applied to the entire column."
},
{
"code": null,
"e": 2998,
"s": 2875,
"text": "For example, you can create one calculated column to extract Year from the existing column – Date, with the DAX formula −"
},
{
"code": null,
"e": 3016,
"s": 2998,
"text": "= YEAR ([Date]) \n"
},
{
"code": null,
"e": 3193,
"s": 3016,
"text": "YEAR is a DAX function and Date is an existing column in the table. As seen, the table name is enclosed in brackets. You will learn more about this in the chapter – DAX Syntax."
},
{
"code": null,
"e": 3404,
"s": 3193,
"text": "When you add a column to a table with this DAX formula, the column values are computed as soon as you create the formula. A new column with the header CalculatedColumn1 filled with Year values will get created."
},
{
"code": null,
"e": 3617,
"s": 3404,
"text": "Column values are recalculated as necessary, such as when the underlying data is refreshed. You can create calculated columns based on existing columns, calculated fields (measures), and other calculated columns."
},
{
"code": null,
"e": 3705,
"s": 3617,
"text": "Consider the Data Model with the Olympics Results as shown in the following screenshot."
},
{
"code": null,
"e": 3726,
"s": 3705,
"text": "Click the Data View."
},
{
"code": null,
"e": 3749,
"s": 3726,
"text": "Click the Results tab."
},
{
"code": null,
"e": 3788,
"s": 3749,
"text": "You will be viewing the Results table."
},
{
"code": null,
"e": 3871,
"s": 3788,
"text": "As seen in the above screenshot, the rightmost column has the header – Add Column."
},
{
"code": null,
"e": 3907,
"s": 3871,
"text": "Click the Design tab on the Ribbon."
},
{
"code": null,
"e": 3939,
"s": 3907,
"text": "Click Add in the Columns group."
},
{
"code": null,
"e": 4038,
"s": 3939,
"text": "The pointer will appear in the formula bar. That means you are adding a column with a DAX formula."
},
{
"code": null,
"e": 4078,
"s": 4038,
"text": "Type =YEAR ([Date]) in the formula bar."
},
{
"code": null,
"e": 4184,
"s": 4078,
"text": "As can be seen in the above screenshot, the rightmost column with the header – Add Column is highlighted."
},
{
"code": null,
"e": 4197,
"s": 4184,
"text": "Press Enter."
},
{
"code": null,
"e": 4278,
"s": 4197,
"text": "It will take a while (few seconds) for the calculations to be done. Please wait."
},
{
"code": null,
"e": 4363,
"s": 4278,
"text": "The new calculated column will get inserted to the left of the rightmost Add Column."
},
{
"code": null,
"e": 4554,
"s": 4363,
"text": "As shown in the above screenshot, the newly inserted calculated column is highlighted. Values in the entire column appear as per the DAX formula used. The column header is CalculatedColumn1."
},
{
"code": null,
"e": 4627,
"s": 4554,
"text": "To rename the calculated column to a meaningful name, do the following −"
},
{
"code": null,
"e": 4699,
"s": 4627,
"text": "Double-click on the column header. The column name will be highlighted."
},
{
"code": null,
"e": 4723,
"s": 4699,
"text": "Select the column name."
},
{
"code": null,
"e": 4749,
"s": 4723,
"text": "Type Year (the new name)."
},
{
"code": null,
"e": 4829,
"s": 4749,
"text": "As seen in the above screenshot, the name of the calculated column got changed."
},
{
"code": null,
"e": 4951,
"s": 4829,
"text": "You can also rename a calculated column by right-clicking on the column and then clicking on Rename in the dropdown list."
},
{
"code": null,
"e": 5038,
"s": 4951,
"text": "Just make sure that the new name does not conflict with an existing name in the table."
},
{
"code": null,
"e": 5104,
"s": 5038,
"text": "You can check the data type of the calculated column as follows −"
},
{
"code": null,
"e": 5138,
"s": 5104,
"text": "Click the Home tab on the Ribbon."
},
{
"code": null,
"e": 5159,
"s": 5138,
"text": "Click the Data Type."
},
{
"code": null,
"e": 5344,
"s": 5159,
"text": "As you can see in the above screenshot, the dropdown list has the possible data types for the columns. In this example, the default (Auto) data type, i.e. the Whole Number is selected."
},
{
"code": null,
"e": 5415,
"s": 5344,
"text": "Errors can occur in the calculated columns for the following reasons −"
},
{
"code": null,
"e": 5553,
"s": 5415,
"text": "Changing or deleting relationships between the tables. This is because the formulas that use columns in those tables will become invalid."
},
{
"code": null,
"e": 5691,
"s": 5553,
"text": "Changing or deleting relationships between the tables. This is because the formulas that use columns in those tables will become invalid."
},
{
"code": null,
"e": 5755,
"s": 5691,
"text": "The formula contains a circular or self-referencing dependency."
},
{
"code": null,
"e": 5819,
"s": 5755,
"text": "The formula contains a circular or self-referencing dependency."
},
{
"code": null,
"e": 6287,
"s": 5819,
"text": "As seen earlier in the example of Olympics results, the Results table has about 35000 rows of data. Hence, when you created a column with a DAX formula, it had calculated all the 35000+ values in the column at once, for which it took a little while. The Data Model and the tables are meant to handle millions of rows of data. Hence, it can affect the performance when the DAX formula has too many references. You can avoid the performance issues doing the following −"
},
{
"code": null,
"e": 6532,
"s": 6287,
"text": "If your DAX formula contains many complex dependencies, then create it in steps saving the results in new calculated columns, instead of creating a single big formula at once. This enables you to validate the results and assess the performance."
},
{
"code": null,
"e": 6777,
"s": 6532,
"text": "If your DAX formula contains many complex dependencies, then create it in steps saving the results in new calculated columns, instead of creating a single big formula at once. This enables you to validate the results and assess the performance."
},
{
"code": null,
"e": 7072,
"s": 6777,
"text": "Calculated columns need to be recalculated when data modifications occur. You can set the recalculation mode to manual, thus saving frequent recalculations. However, if any values in the calculated column are incorrect, the column will be grayed out, until you refresh and recalculate the data."
},
{
"code": null,
"e": 7367,
"s": 7072,
"text": "Calculated columns need to be recalculated when data modifications occur. You can set the recalculation mode to manual, thus saving frequent recalculations. However, if any values in the calculated column are incorrect, the column will be grayed out, until you refresh and recalculate the data."
},
{
"code": null,
"e": 7402,
"s": 7367,
"text": "\n 102 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 7417,
"s": 7402,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 7451,
"s": 7417,
"text": "\n 101 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 7466,
"s": 7451,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 7501,
"s": 7466,
"text": "\n 56 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7516,
"s": 7501,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 7551,
"s": 7516,
"text": "\n 63 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7566,
"s": 7551,
"text": " Yoda Learning"
},
{
"code": null,
"e": 7602,
"s": 7566,
"text": "\n 134 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 7617,
"s": 7602,
"text": " Yoda Learning"
},
{
"code": null,
"e": 7650,
"s": 7617,
"text": "\n 33 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 7672,
"s": 7650,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 7679,
"s": 7672,
"text": " Print"
},
{
"code": null,
"e": 7690,
"s": 7679,
"text": " Add Notes"
}
] |
What is the equivalent of EXCEPT in MySQL?
|
You cannot use EXCEPT in MySQL, instead use the NOT IN operator. Let us first create a table −
mysql> create table DemoTable
(
Number1 int
);
Query OK, 0 rows affected (0.71 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(100);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(200);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(300);
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable;
This will produce the following output −
+---------+
| Number1 |
+---------+
| 100 |
| 200 |
| 300 |
+---------+
3 rows in set (0.00 sec)
Following is the query to create second table −
mysql> create table DemoTable2
(
Number1 int
);
Query OK, 0 rows affected (0.52 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable2 values(100);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable2 values(400);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable2 values(300);
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable2;
This will produce the following output −
+---------+
| Number1 |
+---------+
| 100 |
| 400 |
| 300 |
+---------+
3 rows in set (0.00 sec)
Following is the query to use NOT IN operator in place of EXCEPT −
mysql> select Number1 from DemoTable
where Number1 not in (SELECT Number1 FROM DemoTable2);
This will produce the following output −
+---------+
| Number1 |
+---------+
| 200 |
+---------+
1 row in set (0.04 sec)
|
[
{
"code": null,
"e": 1157,
"s": 1062,
"text": "You cannot use EXCEPT in MySQL, instead use the NOT IN operator. Let us first create a table −"
},
{
"code": null,
"e": 1250,
"s": 1157,
"text": "mysql> create table DemoTable\n (\n Number1 int\n );\nQuery OK, 0 rows affected (0.71 sec)"
},
{
"code": null,
"e": 1306,
"s": 1250,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1540,
"s": 1306,
"text": "mysql> insert into DemoTable values(100);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values(200);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values(300);\nQuery OK, 1 row affected (0.13 sec)"
},
{
"code": null,
"e": 1600,
"s": 1540,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1632,
"s": 1600,
"text": "mysql> select * from DemoTable;"
},
{
"code": null,
"e": 1673,
"s": 1632,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1782,
"s": 1673,
"text": "+---------+\n| Number1 |\n+---------+\n| 100 |\n| 200 |\n| 300 |\n+---------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1830,
"s": 1782,
"text": "Following is the query to create second table −"
},
{
"code": null,
"e": 1924,
"s": 1830,
"text": "mysql> create table DemoTable2\n (\n Number1 int\n );\nQuery OK, 0 rows affected (0.52 sec)"
},
{
"code": null,
"e": 1980,
"s": 1924,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 2217,
"s": 1980,
"text": "mysql> insert into DemoTable2 values(100);\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable2 values(400);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable2 values(300);\nQuery OK, 1 row affected (0.11 sec)"
},
{
"code": null,
"e": 2277,
"s": 2217,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 2310,
"s": 2277,
"text": "mysql> select * from DemoTable2;"
},
{
"code": null,
"e": 2351,
"s": 2310,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2460,
"s": 2351,
"text": "+---------+\n| Number1 |\n+---------+\n| 100 |\n| 400 |\n| 300 |\n+---------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2527,
"s": 2460,
"text": "Following is the query to use NOT IN operator in place of EXCEPT −"
},
{
"code": null,
"e": 2619,
"s": 2527,
"text": "mysql> select Number1 from DemoTable\nwhere Number1 not in (SELECT Number1 FROM DemoTable2);"
},
{
"code": null,
"e": 2660,
"s": 2619,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2744,
"s": 2660,
"text": "+---------+\n| Number1 |\n+---------+\n| 200 |\n+---------+\n1 row in set (0.04 sec)"
}
] |
C++ Library - <vector>
|
Vectors are sequence container that can change size. Container is a objects that hold data of same type. Sequence containers store elements strictly in linear sequence.
Vector stores elements in contiguous memory locations and enables direct access to any element using subscript operator []. Unlike array, vector can shrink or expand as needed at run time. The storage of the vector is handled automatically.
To support shrink and expand functionality at runtime, vector container may allocate some extra storage to accommodate for possible growth thus container have actual capacity greater than the size. Therefore, compared to array, vector consumes more memory in exchange for the ability to manage storage and grow dynamically in an efficient way.
Zero sized vectors are also valid. In that case vector.begin() and vector.end() points to same location. But behavior of calling front() or back() is undefined.
Below is definition of std::vector from <vector> header file
template < class T, class Alloc = allocator<T> > class vector;
T − Type of the element contained.
T may be substituted by any other data type including user-defined type.
T − Type of the element contained.
T may be substituted by any other data type including user-defined type.
Alloc − Type of allocator object.
By default, the allocator class template is used, which defines the simplest memory allocation model and is value-independent.
Alloc − Type of allocator object.
By default, the allocator class template is used, which defines the simplest memory allocation model and is value-independent.
Following member types can be used as parameters or return type by member functions.
Below is list of all methods from <vector> header.
Constructs an empty container, with zero elements.
Constructs a container with n elements and assignd val to each element.
Constructs a container with as many elements in range of first to last.
Constructs a container with copy of each elements present in existing container x.
Constructs the container with the contents of other using move semantics.
Constructs a container from initializer list.
Destroys container by deallocating container memory.
Assign new values to the vector elements by replacing old ones.
Assign new values to the vector elements by replacing old ones.
Assign new values to the vector elements by replacing old ones.
Returns reference to the element present at location n in the vector.
Returns a reference to the last element of the vector.
Return a random access iterator pointing to the first element of the vector.
Returns the size of allocate storage, expressed in terms of elements.
Returns a constant random access iterator which points to the beginning of the vector.
Returns a constant random access iterator which points to the beginning of the vector.
Destroys the vector by removing all elements from the vector and sets size of vector to zero.
Returns a constant reverse iterator which points to the reverser beginning of the container.
Returns a constant reverse iterator which points to the reverse end of the vector.
Returns a pointer to the first element of the vector container.
Extends container by inserting new element at position.
Inserts new element at the end of vector.
Tests whether vector is empty or not.
Returns an iterator which points to past-the-end element in the vector container.
Removes single element from the the vector.
Removes single element from the the vector.
Returns a reference to the first element of the vector.
Returns an allocator associated with vector.
Extends iterator by inserting new element at position.
Extends vector by inserting new element in the container.
Extends vector by inserting new element in the container.
Extends vector by inserting new element in the container.
Extends vector by inserting new element in the container.
Returns the maximum number of elements can be held by vector.
Assign new contents to the vector by replacing old ones and modifies size if necessary.
Assign new contents to the vector by replacing old ones and modifies size if necessary.
Assign new contents to the vector by replacing old ones and modifies size if necessary.
Returns a reference to the element present at location n.
Removes last element from vector and reduces size of vector by one.
Inserts new element at the end of vector and increases size of vector by one.
Returns a reverse iterator which points to the last element of the vector.
Returns a reverse iterator which points to the reverse end of the vector.
Requests to reserve vector capacity be at least enough to contain n elements.
Changes the size of vector.
Requests the container to reduce it's capacity to fit its size.
Returns the number of elements present in the vector.
Exchanges the content of vector with contents of vector x.
Tests whether two vectors are equal or not.
Tests whether two vectors are equal or not.
Tests whether first vector is less than other or not.
Tests whether first vector is less than or equal to other or not.
Tests whether first vector is greater than other or not.
Tests whether first vector is greater than or equal to other or not.
Exchanges the contents of two vector.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2772,
"s": 2603,
"text": "Vectors are sequence container that can change size. Container is a objects that hold data of same type. Sequence containers store elements strictly in linear sequence."
},
{
"code": null,
"e": 3013,
"s": 2772,
"text": "Vector stores elements in contiguous memory locations and enables direct access to any element using subscript operator []. Unlike array, vector can shrink or expand as needed at run time. The storage of the vector is handled automatically."
},
{
"code": null,
"e": 3357,
"s": 3013,
"text": "To support shrink and expand functionality at runtime, vector container may allocate some extra storage to accommodate for possible growth thus container have actual capacity greater than the size. Therefore, compared to array, vector consumes more memory in exchange for the ability to manage storage and grow dynamically in an efficient way."
},
{
"code": null,
"e": 3518,
"s": 3357,
"text": "Zero sized vectors are also valid. In that case vector.begin() and vector.end() points to same location. But behavior of calling front() or back() is undefined."
},
{
"code": null,
"e": 3579,
"s": 3518,
"text": "Below is definition of std::vector from <vector> header file"
},
{
"code": null,
"e": 3643,
"s": 3579,
"text": "template < class T, class Alloc = allocator<T> > class vector;\n"
},
{
"code": null,
"e": 3751,
"s": 3643,
"text": "T − Type of the element contained.\nT may be substituted by any other data type including user-defined type."
},
{
"code": null,
"e": 3786,
"s": 3751,
"text": "T − Type of the element contained."
},
{
"code": null,
"e": 3859,
"s": 3786,
"text": "T may be substituted by any other data type including user-defined type."
},
{
"code": null,
"e": 4020,
"s": 3859,
"text": "Alloc − Type of allocator object.\nBy default, the allocator class template is used, which defines the simplest memory allocation model and is value-independent."
},
{
"code": null,
"e": 4054,
"s": 4020,
"text": "Alloc − Type of allocator object."
},
{
"code": null,
"e": 4181,
"s": 4054,
"text": "By default, the allocator class template is used, which defines the simplest memory allocation model and is value-independent."
},
{
"code": null,
"e": 4266,
"s": 4181,
"text": "Following member types can be used as parameters or return type by member functions."
},
{
"code": null,
"e": 4317,
"s": 4266,
"text": "Below is list of all methods from <vector> header."
},
{
"code": null,
"e": 4368,
"s": 4317,
"text": "Constructs an empty container, with zero elements."
},
{
"code": null,
"e": 4440,
"s": 4368,
"text": "Constructs a container with n elements and assignd val to each element."
},
{
"code": null,
"e": 4512,
"s": 4440,
"text": "Constructs a container with as many elements in range of first to last."
},
{
"code": null,
"e": 4595,
"s": 4512,
"text": "Constructs a container with copy of each elements present in existing container x."
},
{
"code": null,
"e": 4669,
"s": 4595,
"text": "Constructs the container with the contents of other using move semantics."
},
{
"code": null,
"e": 4715,
"s": 4669,
"text": "Constructs a container from initializer list."
},
{
"code": null,
"e": 4768,
"s": 4715,
"text": "Destroys container by deallocating container memory."
},
{
"code": null,
"e": 4832,
"s": 4768,
"text": "Assign new values to the vector elements by replacing old ones."
},
{
"code": null,
"e": 4896,
"s": 4832,
"text": "Assign new values to the vector elements by replacing old ones."
},
{
"code": null,
"e": 4960,
"s": 4896,
"text": "Assign new values to the vector elements by replacing old ones."
},
{
"code": null,
"e": 5030,
"s": 4960,
"text": "Returns reference to the element present at location n in the vector."
},
{
"code": null,
"e": 5085,
"s": 5030,
"text": "Returns a reference to the last element of the vector."
},
{
"code": null,
"e": 5162,
"s": 5085,
"text": "Return a random access iterator pointing to the first element of the vector."
},
{
"code": null,
"e": 5232,
"s": 5162,
"text": "Returns the size of allocate storage, expressed in terms of elements."
},
{
"code": null,
"e": 5319,
"s": 5232,
"text": "Returns a constant random access iterator which points to the beginning of the vector."
},
{
"code": null,
"e": 5406,
"s": 5319,
"text": "Returns a constant random access iterator which points to the beginning of the vector."
},
{
"code": null,
"e": 5500,
"s": 5406,
"text": "Destroys the vector by removing all elements from the vector and sets size of vector to zero."
},
{
"code": null,
"e": 5593,
"s": 5500,
"text": "Returns a constant reverse iterator which points to the reverser beginning of the container."
},
{
"code": null,
"e": 5676,
"s": 5593,
"text": "Returns a constant reverse iterator which points to the reverse end of the vector."
},
{
"code": null,
"e": 5740,
"s": 5676,
"text": "Returns a pointer to the first element of the vector container."
},
{
"code": null,
"e": 5796,
"s": 5740,
"text": "Extends container by inserting new element at position."
},
{
"code": null,
"e": 5838,
"s": 5796,
"text": "Inserts new element at the end of vector."
},
{
"code": null,
"e": 5876,
"s": 5838,
"text": "Tests whether vector is empty or not."
},
{
"code": null,
"e": 5958,
"s": 5876,
"text": "Returns an iterator which points to past-the-end element in the vector container."
},
{
"code": null,
"e": 6002,
"s": 5958,
"text": "Removes single element from the the vector."
},
{
"code": null,
"e": 6046,
"s": 6002,
"text": "Removes single element from the the vector."
},
{
"code": null,
"e": 6102,
"s": 6046,
"text": "Returns a reference to the first element of the vector."
},
{
"code": null,
"e": 6147,
"s": 6102,
"text": "Returns an allocator associated with vector."
},
{
"code": null,
"e": 6202,
"s": 6147,
"text": "Extends iterator by inserting new element at position."
},
{
"code": null,
"e": 6260,
"s": 6202,
"text": "Extends vector by inserting new element in the container."
},
{
"code": null,
"e": 6318,
"s": 6260,
"text": "Extends vector by inserting new element in the container."
},
{
"code": null,
"e": 6376,
"s": 6318,
"text": "Extends vector by inserting new element in the container."
},
{
"code": null,
"e": 6434,
"s": 6376,
"text": "Extends vector by inserting new element in the container."
},
{
"code": null,
"e": 6496,
"s": 6434,
"text": "Returns the maximum number of elements can be held by vector."
},
{
"code": null,
"e": 6584,
"s": 6496,
"text": "Assign new contents to the vector by replacing old ones and modifies size if necessary."
},
{
"code": null,
"e": 6672,
"s": 6584,
"text": "Assign new contents to the vector by replacing old ones and modifies size if necessary."
},
{
"code": null,
"e": 6760,
"s": 6672,
"text": "Assign new contents to the vector by replacing old ones and modifies size if necessary."
},
{
"code": null,
"e": 6818,
"s": 6760,
"text": "Returns a reference to the element present at location n."
},
{
"code": null,
"e": 6886,
"s": 6818,
"text": "Removes last element from vector and reduces size of vector by one."
},
{
"code": null,
"e": 6964,
"s": 6886,
"text": "Inserts new element at the end of vector and increases size of vector by one."
},
{
"code": null,
"e": 7039,
"s": 6964,
"text": "Returns a reverse iterator which points to the last element of the vector."
},
{
"code": null,
"e": 7113,
"s": 7039,
"text": "Returns a reverse iterator which points to the reverse end of the vector."
},
{
"code": null,
"e": 7191,
"s": 7113,
"text": "Requests to reserve vector capacity be at least enough to contain n elements."
},
{
"code": null,
"e": 7219,
"s": 7191,
"text": "Changes the size of vector."
},
{
"code": null,
"e": 7283,
"s": 7219,
"text": "Requests the container to reduce it's capacity to fit its size."
},
{
"code": null,
"e": 7337,
"s": 7283,
"text": "Returns the number of elements present in the vector."
},
{
"code": null,
"e": 7396,
"s": 7337,
"text": "Exchanges the content of vector with contents of vector x."
},
{
"code": null,
"e": 7440,
"s": 7396,
"text": "Tests whether two vectors are equal or not."
},
{
"code": null,
"e": 7484,
"s": 7440,
"text": "Tests whether two vectors are equal or not."
},
{
"code": null,
"e": 7538,
"s": 7484,
"text": "Tests whether first vector is less than other or not."
},
{
"code": null,
"e": 7604,
"s": 7538,
"text": "Tests whether first vector is less than or equal to other or not."
},
{
"code": null,
"e": 7661,
"s": 7604,
"text": "Tests whether first vector is greater than other or not."
},
{
"code": null,
"e": 7730,
"s": 7661,
"text": "Tests whether first vector is greater than or equal to other or not."
},
{
"code": null,
"e": 7768,
"s": 7730,
"text": "Exchanges the contents of two vector."
},
{
"code": null,
"e": 7775,
"s": 7768,
"text": " Print"
},
{
"code": null,
"e": 7786,
"s": 7775,
"text": " Add Notes"
}
] |
How to convert an integer to a hexadecimal string in Python?
|
We can use built in hex() function to convert any integer to its hexadecimal representation.
>>> hex(100)
'0x64'
>>> hex(4095)
'0xfff'
>>> hex(31)
'0x1f'
|
[
{
"code": null,
"e": 1155,
"s": 1062,
"text": "We can use built in hex() function to convert any integer to its hexadecimal representation."
},
{
"code": null,
"e": 1216,
"s": 1155,
"text": ">>> hex(100)\n'0x64'\n>>> hex(4095)\n'0xfff'\n>>> hex(31)\n'0x1f'"
}
] |
Are array members deeply copied? - GeeksforGeeks
|
28 May, 2017
In C/C++, we can assign a struct (or class in C++ only) variable to another variable of same type. When we assign a struct variable to another, all members of the variable are copied to the other struct variable. But what happens when the structure contains pointer to dynamically allocated memory and what if it contains an array?
In the following C++ program, struct variable st1 contains pointer to dynamically allocated memory. When we assign st1 to st2, str pointer of st2 also start pointing to same memory location. This kind of copying is called Shallow Copy.
# include <iostream># include <string.h> using namespace std; struct test{ char *str;}; int main(){ struct test st1, st2; st1.str = new char[20]; strcpy(st1.str, "GeeksforGeeks"); st2 = st1; st1.str[0] = 'X'; st1.str[1] = 'Y'; /* Since copy was shallow, both strings are same */ cout << "st1's str = " << st1.str << endl; cout << "st2's str = " << st2.str << endl; return 0;}
Output:st1’s str = XYeksforGeeksst2’s str = XYeksforGeeks
Now, what about arrays? The point to note is that the array members are not shallow copied, compiler automatically performs Deep Copy for array members.. In the following program, struct test contains array member str[]. When we assign st1 to st2, st2 has a new copy of the array. So st2 is not changed when we change str[] of st1.
# include <iostream># include <string.h> using namespace std; struct test{ char str[20];}; int main(){ struct test st1, st2; strcpy(st1.str, "GeeksforGeeks"); st2 = st1; st1.str[0] = 'X'; st1.str[1] = 'Y'; /* Since copy was Deep, both arrays are different */ cout << "st1's str = " << st1.str << endl; cout << "st2's str = " << st2.str << endl; return 0;}
Output:st1’s str = XYeksforGeeksst2’s str = GeeksforGeeks
Therefore, for C++ classes, we don’t need to write our own copy constructor and assignment operator for array members as the default behavior is Deep copy for arrays.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C Array and String
pointer
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
rand() and srand() in C/C++
Command line arguments in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Different methods to reverse a string in C/C++
Substring in C++
Function Pointer in C
TCP Server-Client implementation in C
Enumeration (or enum) in C
Converting Strings to Numbers in C/C++
|
[
{
"code": null,
"e": 24576,
"s": 24548,
"text": "\n28 May, 2017"
},
{
"code": null,
"e": 24908,
"s": 24576,
"text": "In C/C++, we can assign a struct (or class in C++ only) variable to another variable of same type. When we assign a struct variable to another, all members of the variable are copied to the other struct variable. But what happens when the structure contains pointer to dynamically allocated memory and what if it contains an array?"
},
{
"code": null,
"e": 25144,
"s": 24908,
"text": "In the following C++ program, struct variable st1 contains pointer to dynamically allocated memory. When we assign st1 to st2, str pointer of st2 also start pointing to same memory location. This kind of copying is called Shallow Copy."
},
{
"code": "# include <iostream># include <string.h> using namespace std; struct test{ char *str;}; int main(){ struct test st1, st2; st1.str = new char[20]; strcpy(st1.str, \"GeeksforGeeks\"); st2 = st1; st1.str[0] = 'X'; st1.str[1] = 'Y'; /* Since copy was shallow, both strings are same */ cout << \"st1's str = \" << st1.str << endl; cout << \"st2's str = \" << st2.str << endl; return 0;}",
"e": 25544,
"s": 25144,
"text": null
},
{
"code": null,
"e": 25602,
"s": 25544,
"text": "Output:st1’s str = XYeksforGeeksst2’s str = XYeksforGeeks"
},
{
"code": null,
"e": 25934,
"s": 25602,
"text": "Now, what about arrays? The point to note is that the array members are not shallow copied, compiler automatically performs Deep Copy for array members.. In the following program, struct test contains array member str[]. When we assign st1 to st2, st2 has a new copy of the array. So st2 is not changed when we change str[] of st1."
},
{
"code": "# include <iostream># include <string.h> using namespace std; struct test{ char str[20];}; int main(){ struct test st1, st2; strcpy(st1.str, \"GeeksforGeeks\"); st2 = st1; st1.str[0] = 'X'; st1.str[1] = 'Y'; /* Since copy was Deep, both arrays are different */ cout << \"st1's str = \" << st1.str << endl; cout << \"st2's str = \" << st2.str << endl; return 0;}",
"e": 26313,
"s": 25934,
"text": null
},
{
"code": null,
"e": 26371,
"s": 26313,
"text": "Output:st1’s str = XYeksforGeeksst2’s str = GeeksforGeeks"
},
{
"code": null,
"e": 26538,
"s": 26371,
"text": "Therefore, for C++ classes, we don’t need to write our own copy constructor and assignment operator for array members as the default behavior is Deep copy for arrays."
},
{
"code": null,
"e": 26663,
"s": 26538,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 26682,
"s": 26663,
"text": "C Array and String"
},
{
"code": null,
"e": 26690,
"s": 26682,
"text": "pointer"
},
{
"code": null,
"e": 26701,
"s": 26690,
"text": "C Language"
},
{
"code": null,
"e": 26799,
"s": 26701,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26808,
"s": 26799,
"text": "Comments"
},
{
"code": null,
"e": 26821,
"s": 26808,
"text": "Old Comments"
},
{
"code": null,
"e": 26849,
"s": 26821,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 26881,
"s": 26849,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 26927,
"s": 26881,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 26939,
"s": 26927,
"text": "fork() in C"
},
{
"code": null,
"e": 26986,
"s": 26939,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 27003,
"s": 26986,
"text": "Substring in C++"
},
{
"code": null,
"e": 27025,
"s": 27003,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 27063,
"s": 27025,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 27090,
"s": 27063,
"text": "Enumeration (or enum) in C"
}
] |
Ngrep - Network Packet Analyzer for Linux - GeeksforGeeks
|
23 Aug, 2021
Ngrep a network packet analyzer that is similar to the grep command, but ngrep grep the package on the network layer. This tool grep the traffic going to coming on the network interface.ngrep allow us to specify an extended regular or hexadecimal expression to match against data payloads of packets.ngrep can work on protocols like IPv4/6, TCP, UDP, ICMPv4/6, IGMP as well as Raw on a number of interfaces.
Now let’s see how to install ngrep on Linux. The ngrep is available in most of the Linux package managers. We are going to use these package managers to install ngrep. Use one of the following commands according to your operating system:
For Debian/Ubuntu/Kali Linux:
sudo apt-get install ngrep
For Arch Linux:
sudo pacman -S ngrep
For Fedora:
dnf install ngrep
After successfully installing the ngrep, now let’s see how to use the ngrep. To monitor all traffic running on the default network interface, just use the ngrep command
sudo ngrep
To stop the ngrep use the ctrl+C keys.
To display information about only packet header and packet payload and avoid useless information use the -q option with ngrep command. We are going to use this option in our next commands. Let’s see how we can filter the packages of a particular protocol using the ngrep. Let’s take one example, in this example, we are going to catch all ICMP packages. To use ICMP protocol we are going to send a ping to another host and then catch all ICMP packets using ngrep.
sudo ngrep -q '.' 'icmp'
We can also filter the packet based on the host, for example, let’s catch the packets of host google.com:
sudo ngrep -q '.' 'host google.com'
To catch all packets that are receiving while surfing the internet through a web browser, we can use the following command:
sudo ngrep -q '^GET .* HTTP/1.1
To monitor traffic passing through the port of source host or destination, use the port option and mention the port number with ngrep command:
sudo ngrep port 443
To search for the occurrence of the word “error” in any network-based Syslog traffic, use the following command:
sudo ngrep -d any 'error' port 514
The ngrep tool can also convert the service port names stored in /etc/services to the port number that mean instead of mentioning the port number in ngrep command we can mention the port name in the /etc/services file.
sudo ngrep -d any 'error' port syslog
To catch all traffic running on port number 80 we can use the following command:
sudo ngrep port 80
In the previous output, we can see that the headers are not in formatted form, this makes it difficult to read the header. To get the header in a well-formatted manner, use the following command:
sudo ngrep -W byline port 80
Use the -t option with ngrep command to get a timestamp in YYYY/MM/DD HH:MM:SS.UUUUUU when every time a packet is matched
sudo ngrep -t -W byline port 80
Use the -p option to avoid putting the interface into promiscuous mode
sudo ngrep -p -W byline port 80
When observing raw or unknown protocols to show sub-protocol numbers along with single-character identifier, use the -N option with ngerp command:
sudo ngrep -N -W byline
man ngrep
Linux-Tools
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
scp command in Linux with Examples
nohup Command in Linux with Examples
mv command in Linux with examples
Thread functions in C/C++
Docker - COPY Instruction
chown command in Linux with Examples
nslookup command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples
|
[
{
"code": null,
"e": 24015,
"s": 23987,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 24423,
"s": 24015,
"text": "Ngrep a network packet analyzer that is similar to the grep command, but ngrep grep the package on the network layer. This tool grep the traffic going to coming on the network interface.ngrep allow us to specify an extended regular or hexadecimal expression to match against data payloads of packets.ngrep can work on protocols like IPv4/6, TCP, UDP, ICMPv4/6, IGMP as well as Raw on a number of interfaces."
},
{
"code": null,
"e": 24661,
"s": 24423,
"text": "Now let’s see how to install ngrep on Linux. The ngrep is available in most of the Linux package managers. We are going to use these package managers to install ngrep. Use one of the following commands according to your operating system:"
},
{
"code": null,
"e": 24691,
"s": 24661,
"text": "For Debian/Ubuntu/Kali Linux:"
},
{
"code": null,
"e": 24718,
"s": 24691,
"text": "sudo apt-get install ngrep"
},
{
"code": null,
"e": 24734,
"s": 24718,
"text": "For Arch Linux:"
},
{
"code": null,
"e": 24755,
"s": 24734,
"text": "sudo pacman -S ngrep"
},
{
"code": null,
"e": 24767,
"s": 24755,
"text": "For Fedora:"
},
{
"code": null,
"e": 24785,
"s": 24767,
"text": "dnf install ngrep"
},
{
"code": null,
"e": 24954,
"s": 24785,
"text": "After successfully installing the ngrep, now let’s see how to use the ngrep. To monitor all traffic running on the default network interface, just use the ngrep command"
},
{
"code": null,
"e": 24966,
"s": 24954,
"text": "sudo ngrep "
},
{
"code": null,
"e": 25005,
"s": 24966,
"text": "To stop the ngrep use the ctrl+C keys."
},
{
"code": null,
"e": 25469,
"s": 25005,
"text": "To display information about only packet header and packet payload and avoid useless information use the -q option with ngrep command. We are going to use this option in our next commands. Let’s see how we can filter the packages of a particular protocol using the ngrep. Let’s take one example, in this example, we are going to catch all ICMP packages. To use ICMP protocol we are going to send a ping to another host and then catch all ICMP packets using ngrep."
},
{
"code": null,
"e": 25494,
"s": 25469,
"text": "sudo ngrep -q '.' 'icmp'"
},
{
"code": null,
"e": 25600,
"s": 25494,
"text": "We can also filter the packet based on the host, for example, let’s catch the packets of host google.com:"
},
{
"code": null,
"e": 25636,
"s": 25600,
"text": "sudo ngrep -q '.' 'host google.com'"
},
{
"code": null,
"e": 25761,
"s": 25636,
"text": "To catch all packets that are receiving while surfing the internet through a web browser, we can use the following command:"
},
{
"code": null,
"e": 25793,
"s": 25761,
"text": "sudo ngrep -q '^GET .* HTTP/1.1"
},
{
"code": null,
"e": 25936,
"s": 25793,
"text": "To monitor traffic passing through the port of source host or destination, use the port option and mention the port number with ngrep command:"
},
{
"code": null,
"e": 25956,
"s": 25936,
"text": "sudo ngrep port 443"
},
{
"code": null,
"e": 26069,
"s": 25956,
"text": "To search for the occurrence of the word “error” in any network-based Syslog traffic, use the following command:"
},
{
"code": null,
"e": 26104,
"s": 26069,
"text": "sudo ngrep -d any 'error' port 514"
},
{
"code": null,
"e": 26323,
"s": 26104,
"text": "The ngrep tool can also convert the service port names stored in /etc/services to the port number that mean instead of mentioning the port number in ngrep command we can mention the port name in the /etc/services file."
},
{
"code": null,
"e": 26361,
"s": 26323,
"text": "sudo ngrep -d any 'error' port syslog"
},
{
"code": null,
"e": 26442,
"s": 26361,
"text": "To catch all traffic running on port number 80 we can use the following command:"
},
{
"code": null,
"e": 26461,
"s": 26442,
"text": "sudo ngrep port 80"
},
{
"code": null,
"e": 26657,
"s": 26461,
"text": "In the previous output, we can see that the headers are not in formatted form, this makes it difficult to read the header. To get the header in a well-formatted manner, use the following command:"
},
{
"code": null,
"e": 26686,
"s": 26657,
"text": "sudo ngrep -W byline port 80"
},
{
"code": null,
"e": 26808,
"s": 26686,
"text": "Use the -t option with ngrep command to get a timestamp in YYYY/MM/DD HH:MM:SS.UUUUUU when every time a packet is matched"
},
{
"code": null,
"e": 26840,
"s": 26808,
"text": "sudo ngrep -t -W byline port 80"
},
{
"code": null,
"e": 26911,
"s": 26840,
"text": "Use the -p option to avoid putting the interface into promiscuous mode"
},
{
"code": null,
"e": 26943,
"s": 26911,
"text": "sudo ngrep -p -W byline port 80"
},
{
"code": null,
"e": 27090,
"s": 26943,
"text": "When observing raw or unknown protocols to show sub-protocol numbers along with single-character identifier, use the -N option with ngerp command:"
},
{
"code": null,
"e": 27124,
"s": 27090,
"text": "sudo ngrep -N -W byline\nman ngrep"
},
{
"code": null,
"e": 27136,
"s": 27124,
"text": "Linux-Tools"
},
{
"code": null,
"e": 27143,
"s": 27136,
"text": "Picked"
},
{
"code": null,
"e": 27154,
"s": 27143,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27252,
"s": 27154,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27261,
"s": 27252,
"text": "Comments"
},
{
"code": null,
"e": 27274,
"s": 27261,
"text": "Old Comments"
},
{
"code": null,
"e": 27309,
"s": 27274,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 27346,
"s": 27309,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 27380,
"s": 27346,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 27406,
"s": 27380,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 27432,
"s": 27406,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 27469,
"s": 27432,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 27509,
"s": 27469,
"text": "nslookup command in Linux with Examples"
},
{
"code": null,
"e": 27538,
"s": 27509,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 27580,
"s": 27538,
"text": "Named Pipe or FIFO with example C program"
}
] |
Check if a number can be expressed as product of a prime and a composite number - GeeksforGeeks
|
23 Dec, 2021
Given a number N, the task is to check if N can be represented as the product of a prime and a composite number or not. If it can, then print Yes, otherwise No.
Examples:
Input: N = 52 Output: YesExplanation: 52 can be represented as the multiplication of 4 and 13, where 4 is a composite and 13 is a prime number.
Input: N = 49Output: No
Approach: This problem can be solved with the help of the Sieve of Eratosthenes algorithm. Now, to solve this problem, follow the below steps:
Create a boolean array isPrime, where the ith element is true if it is a prime, otherwise it’s false.Find all prime numbers till N using sieve algorithm.Now run a loop for i=2 to i<N, and on each iteration:Check for these two conditions:If N is divisible by i.If i is a prime number and N/i isn’t or if i isn’t a prime number and N/i is.If both of the above conditions satisfy, return true.Otherwise, return false.Print the answer, according to the above observation.
Create a boolean array isPrime, where the ith element is true if it is a prime, otherwise it’s false.
Find all prime numbers till N using sieve algorithm.
Now run a loop for i=2 to i<N, and on each iteration:Check for these two conditions:If N is divisible by i.If i is a prime number and N/i isn’t or if i isn’t a prime number and N/i is.If both of the above conditions satisfy, return true.Otherwise, return false.
Check for these two conditions:If N is divisible by i.If i is a prime number and N/i isn’t or if i isn’t a prime number and N/i is.
If N is divisible by i.
If i is a prime number and N/i isn’t or if i isn’t a prime number and N/i is.
If both of the above conditions satisfy, return true.
Otherwise, return false.
Print the answer, according to the above observation.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to generate all prime// numbers less than Nvoid SieveOfEratosthenes(int N, bool isPrime[]){ // Initialize all entries of boolean array // as true. A value in isPrime[i] will finally // be false if i is Not a prime, else true // bool isPrime[N+1]; isPrime[0] = isPrime[1] = false; for (int i = 2; i <= N; i++) isPrime[i] = true; for (int p = 2; p * p <= N; p++) { // If isPrime[p] is not changed, // then it is a prime if (isPrime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= N; i += p) isPrime[i] = false; } }} // Function to check if we can// represent N as product of a prime// and a composite number or notbool isRepresentable(int N){ // Generating primes using Sieve bool isPrime[N + 1]; SieveOfEratosthenes(N, isPrime); // Traversing through the array for (int i = 2; i < N; i++) { if (N % i == 0) { if (N % i == 0 and (isPrime[i] and !isPrime[N / i]) or (!isPrime[i] and isPrime[N / i])) { return true; } } } return false;} // Driver Codeint main(){ int N = 52; if (isRepresentable(N)) { cout << "Yes"; } else { cout << "No"; } return 0;}
// Java program to implement the above approachimport java.util.*;public class GFG{ // Function to generate all prime// numbers less than Nstatic void SieveOfEratosthenes(int N, boolean []isPrime){ // Initialize all entries of boolean array // as true. A value in isPrime[i] will finally // be false if i is Not a prime, else true // bool isPrime[N+1]; isPrime[0] = isPrime[1] = false; for (int i = 2; i <= N; i++) isPrime[i] = true; for (int p = 2; p * p <= N; p++) { // If isPrime[p] is not changed, // then it is a prime if (isPrime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= N; i += p) isPrime[i] = false; } }} // Function to check if we can// represent N as product of a prime// and a composite number or notstatic boolean isRepresentable(int N){ // Generating primes using Sieve boolean []isPrime = new boolean[N + 1]; SieveOfEratosthenes(N, isPrime); // Traversing through the array for (int i = 2; i < N; i++) { if (N % i == 0) { if (N % i == 0 && (isPrime[i] && !isPrime[N / i]) || (!isPrime[i] && isPrime[N / i])) { return true; } } } return false;} // Driver Codepublic static void main(String arg[]){ int N = 52; if (isRepresentable(N)) { System.out.println("Yes"); } else { System.out.println("No"); }}} // This code is contributed by Samim Hossain Mondal.
# python program for the above approachimport math # Function to generate all prime# numbers less than Ndef SieveOfEratosthenes(N, isPrime): # Initialize all entries of boolean array # as true. A value in isPrime[i] will finally # be false if i is Not a prime, else true # bool isPrime[N+1]; isPrime[0] = False isPrime[1] = False for i in range(2, N+1): isPrime[i] = True for p in range(2, int(math.sqrt(N)) + 1): # If isPrime[p] is not changed, # then it is a prime if (isPrime[p] == True): # Update all multiples of p for i in range(p+2, N+1, p): isPrime[i] = False # Function to check if we can# represent N as product of a prime# and a composite number or notdef isRepresentable(N): # Generating primes using Sieve isPrime = [0 for _ in range(N + 1)] SieveOfEratosthenes(N, isPrime) # Traversing through the array for i in range(2, N): if (N % i == 0): if (N % i == 0 and (isPrime[i] and not isPrime[N // i]) or (not isPrime[i] and isPrime[N // i])): return True return False # Driver Codeif __name__ == "__main__": N = 52 if (isRepresentable(N)): print("Yes") else: print("No") # This code is contributed by rakeshsahni
// C# program to implement the above approachusing System;class GFG{// Function to generate all prime// numbers less than Nstatic void SieveOfEratosthenes(int N, bool []isPrime){ // Initialize all entries of boolean array // as true. A value in isPrime[i] will finally // be false if i is Not a prime, else true // bool isPrime[N+1]; isPrime[0] = isPrime[1] = false; for (int i = 2; i <= N; i++) isPrime[i] = true; for (int p = 2; p * p <= N; p++) { // If isPrime[p] is not changed, // then it is a prime if (isPrime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= N; i += p) isPrime[i] = false; } }} // Function to check if we can// represent N as product of a prime// and a composite number or notstatic bool isRepresentable(int N){ // Generating primes using Sieve bool []isPrime = new bool[N + 1]; SieveOfEratosthenes(N, isPrime); // Traversing through the array for (int i = 2; i < N; i++) { if (N % i == 0) { if (N % i == 0 && (isPrime[i] && !isPrime[N / i]) || (!isPrime[i] && isPrime[N / i])) { return true; } } } return false;} // Driver Codepublic static void Main(){ int N = 52; if (isRepresentable(N)) { Console.Write("Yes"); } else { Console.Write("No"); }}}// This code is contributed by Samim Hossain Mondal.
<script>// Javascript program for the above approach // Function to generate all prime// numbers less than Nfunction SieveOfEratosthenes(N, isPrime){ // Initialize all entries of boolean array // as true. A value in isPrime[i] will finally // be false if i is Not a prime, else true // bool isPrime[N+1]; isPrime[0] = isPrime[1] = false; for (let i = 2; i <= N; i++) isPrime[i] = true; for (let p = 2; p * p <= N; p++) { // If isPrime[p] is not changed, // then it is a prime if (isPrime[p] == true) { // Update all multiples of p for (let i = p * 2; i <= N; i += p) isPrime[i] = false; } }} // Function to check if we can// represent N as product of a prime// and a composite number or notfunction isRepresentable(N){ // Generating primes using Sieve let isPrime = []; SieveOfEratosthenes(N, isPrime); // Traversing through the array for (let i = 2; i < N; i++) { if (N % i == 0) { if (N % i == 0 && (isPrime[i] && !isPrime[N / i]) || (!isPrime[i] && isPrime[N / i])) { return true; } } } return false;} // Driver Codelet N = 52;if (isRepresentable(N)) { document.write("Yes");} else { document.write("No");} // This code is contributed by Samim Hossain Mondal.</script>
Yes
Time complexity: O(N*log(logN)) Auxiliary Space: O(N)
rakeshsahni
samim2000
surinderdawra388
Prime Number
sieve
Mathematical
Mathematical
Prime Number
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Find all factors of a natural number | Set 1
Check if a number is Palindrome
Program to print prime numbers from 1 to N.
Fizz Buzz Implementation
Program to multiply two matrices
Count ways to reach the n'th stair
Add two numbers without using arithmetic operators
Program to add two binary strings
Program to convert a given number to words
Modular multiplicative inverse
|
[
{
"code": null,
"e": 24301,
"s": 24273,
"text": "\n23 Dec, 2021"
},
{
"code": null,
"e": 24462,
"s": 24301,
"text": "Given a number N, the task is to check if N can be represented as the product of a prime and a composite number or not. If it can, then print Yes, otherwise No."
},
{
"code": null,
"e": 24472,
"s": 24462,
"text": "Examples:"
},
{
"code": null,
"e": 24616,
"s": 24472,
"text": "Input: N = 52 Output: YesExplanation: 52 can be represented as the multiplication of 4 and 13, where 4 is a composite and 13 is a prime number."
},
{
"code": null,
"e": 24640,
"s": 24616,
"text": "Input: N = 49Output: No"
},
{
"code": null,
"e": 24784,
"s": 24640,
"text": "Approach: This problem can be solved with the help of the Sieve of Eratosthenes algorithm. Now, to solve this problem, follow the below steps:"
},
{
"code": null,
"e": 25252,
"s": 24784,
"text": "Create a boolean array isPrime, where the ith element is true if it is a prime, otherwise it’s false.Find all prime numbers till N using sieve algorithm.Now run a loop for i=2 to i<N, and on each iteration:Check for these two conditions:If N is divisible by i.If i is a prime number and N/i isn’t or if i isn’t a prime number and N/i is.If both of the above conditions satisfy, return true.Otherwise, return false.Print the answer, according to the above observation."
},
{
"code": null,
"e": 25354,
"s": 25252,
"text": "Create a boolean array isPrime, where the ith element is true if it is a prime, otherwise it’s false."
},
{
"code": null,
"e": 25407,
"s": 25354,
"text": "Find all prime numbers till N using sieve algorithm."
},
{
"code": null,
"e": 25669,
"s": 25407,
"text": "Now run a loop for i=2 to i<N, and on each iteration:Check for these two conditions:If N is divisible by i.If i is a prime number and N/i isn’t or if i isn’t a prime number and N/i is.If both of the above conditions satisfy, return true.Otherwise, return false."
},
{
"code": null,
"e": 25801,
"s": 25669,
"text": "Check for these two conditions:If N is divisible by i.If i is a prime number and N/i isn’t or if i isn’t a prime number and N/i is."
},
{
"code": null,
"e": 25825,
"s": 25801,
"text": "If N is divisible by i."
},
{
"code": null,
"e": 25903,
"s": 25825,
"text": "If i is a prime number and N/i isn’t or if i isn’t a prime number and N/i is."
},
{
"code": null,
"e": 25957,
"s": 25903,
"text": "If both of the above conditions satisfy, return true."
},
{
"code": null,
"e": 25982,
"s": 25957,
"text": "Otherwise, return false."
},
{
"code": null,
"e": 26036,
"s": 25982,
"text": "Print the answer, according to the above observation."
},
{
"code": null,
"e": 26087,
"s": 26036,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 26091,
"s": 26087,
"text": "C++"
},
{
"code": null,
"e": 26096,
"s": 26091,
"text": "Java"
},
{
"code": null,
"e": 26104,
"s": 26096,
"text": "Python3"
},
{
"code": null,
"e": 26107,
"s": 26104,
"text": "C#"
},
{
"code": null,
"e": 26118,
"s": 26107,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to generate all prime// numbers less than Nvoid SieveOfEratosthenes(int N, bool isPrime[]){ // Initialize all entries of boolean array // as true. A value in isPrime[i] will finally // be false if i is Not a prime, else true // bool isPrime[N+1]; isPrime[0] = isPrime[1] = false; for (int i = 2; i <= N; i++) isPrime[i] = true; for (int p = 2; p * p <= N; p++) { // If isPrime[p] is not changed, // then it is a prime if (isPrime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= N; i += p) isPrime[i] = false; } }} // Function to check if we can// represent N as product of a prime// and a composite number or notbool isRepresentable(int N){ // Generating primes using Sieve bool isPrime[N + 1]; SieveOfEratosthenes(N, isPrime); // Traversing through the array for (int i = 2; i < N; i++) { if (N % i == 0) { if (N % i == 0 and (isPrime[i] and !isPrime[N / i]) or (!isPrime[i] and isPrime[N / i])) { return true; } } } return false;} // Driver Codeint main(){ int N = 52; if (isRepresentable(N)) { cout << \"Yes\"; } else { cout << \"No\"; } return 0;}",
"e": 27522,
"s": 26118,
"text": null
},
{
"code": "// Java program to implement the above approachimport java.util.*;public class GFG{ // Function to generate all prime// numbers less than Nstatic void SieveOfEratosthenes(int N, boolean []isPrime){ // Initialize all entries of boolean array // as true. A value in isPrime[i] will finally // be false if i is Not a prime, else true // bool isPrime[N+1]; isPrime[0] = isPrime[1] = false; for (int i = 2; i <= N; i++) isPrime[i] = true; for (int p = 2; p * p <= N; p++) { // If isPrime[p] is not changed, // then it is a prime if (isPrime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= N; i += p) isPrime[i] = false; } }} // Function to check if we can// represent N as product of a prime// and a composite number or notstatic boolean isRepresentable(int N){ // Generating primes using Sieve boolean []isPrime = new boolean[N + 1]; SieveOfEratosthenes(N, isPrime); // Traversing through the array for (int i = 2; i < N; i++) { if (N % i == 0) { if (N % i == 0 && (isPrime[i] && !isPrime[N / i]) || (!isPrime[i] && isPrime[N / i])) { return true; } } } return false;} // Driver Codepublic static void main(String arg[]){ int N = 52; if (isRepresentable(N)) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); }}} // This code is contributed by Samim Hossain Mondal.",
"e": 29061,
"s": 27522,
"text": null
},
{
"code": "# python program for the above approachimport math # Function to generate all prime# numbers less than Ndef SieveOfEratosthenes(N, isPrime): # Initialize all entries of boolean array # as true. A value in isPrime[i] will finally # be false if i is Not a prime, else true # bool isPrime[N+1]; isPrime[0] = False isPrime[1] = False for i in range(2, N+1): isPrime[i] = True for p in range(2, int(math.sqrt(N)) + 1): # If isPrime[p] is not changed, # then it is a prime if (isPrime[p] == True): # Update all multiples of p for i in range(p+2, N+1, p): isPrime[i] = False # Function to check if we can# represent N as product of a prime# and a composite number or notdef isRepresentable(N): # Generating primes using Sieve isPrime = [0 for _ in range(N + 1)] SieveOfEratosthenes(N, isPrime) # Traversing through the array for i in range(2, N): if (N % i == 0): if (N % i == 0 and (isPrime[i] and not isPrime[N // i]) or (not isPrime[i] and isPrime[N // i])): return True return False # Driver Codeif __name__ == \"__main__\": N = 52 if (isRepresentable(N)): print(\"Yes\") else: print(\"No\") # This code is contributed by rakeshsahni",
"e": 30364,
"s": 29061,
"text": null
},
{
"code": "// C# program to implement the above approachusing System;class GFG{// Function to generate all prime// numbers less than Nstatic void SieveOfEratosthenes(int N, bool []isPrime){ // Initialize all entries of boolean array // as true. A value in isPrime[i] will finally // be false if i is Not a prime, else true // bool isPrime[N+1]; isPrime[0] = isPrime[1] = false; for (int i = 2; i <= N; i++) isPrime[i] = true; for (int p = 2; p * p <= N; p++) { // If isPrime[p] is not changed, // then it is a prime if (isPrime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= N; i += p) isPrime[i] = false; } }} // Function to check if we can// represent N as product of a prime// and a composite number or notstatic bool isRepresentable(int N){ // Generating primes using Sieve bool []isPrime = new bool[N + 1]; SieveOfEratosthenes(N, isPrime); // Traversing through the array for (int i = 2; i < N; i++) { if (N % i == 0) { if (N % i == 0 && (isPrime[i] && !isPrime[N / i]) || (!isPrime[i] && isPrime[N / i])) { return true; } } } return false;} // Driver Codepublic static void Main(){ int N = 52; if (isRepresentable(N)) { Console.Write(\"Yes\"); } else { Console.Write(\"No\"); }}}// This code is contributed by Samim Hossain Mondal.",
"e": 31847,
"s": 30364,
"text": null
},
{
"code": "<script>// Javascript program for the above approach // Function to generate all prime// numbers less than Nfunction SieveOfEratosthenes(N, isPrime){ // Initialize all entries of boolean array // as true. A value in isPrime[i] will finally // be false if i is Not a prime, else true // bool isPrime[N+1]; isPrime[0] = isPrime[1] = false; for (let i = 2; i <= N; i++) isPrime[i] = true; for (let p = 2; p * p <= N; p++) { // If isPrime[p] is not changed, // then it is a prime if (isPrime[p] == true) { // Update all multiples of p for (let i = p * 2; i <= N; i += p) isPrime[i] = false; } }} // Function to check if we can// represent N as product of a prime// and a composite number or notfunction isRepresentable(N){ // Generating primes using Sieve let isPrime = []; SieveOfEratosthenes(N, isPrime); // Traversing through the array for (let i = 2; i < N; i++) { if (N % i == 0) { if (N % i == 0 && (isPrime[i] && !isPrime[N / i]) || (!isPrime[i] && isPrime[N / i])) { return true; } } } return false;} // Driver Codelet N = 52;if (isRepresentable(N)) { document.write(\"Yes\");} else { document.write(\"No\");} // This code is contributed by Samim Hossain Mondal.</script>",
"e": 33231,
"s": 31847,
"text": null
},
{
"code": null,
"e": 33235,
"s": 33231,
"text": "Yes"
},
{
"code": null,
"e": 33289,
"s": 33235,
"text": "Time complexity: O(N*log(logN)) Auxiliary Space: O(N)"
},
{
"code": null,
"e": 33301,
"s": 33289,
"text": "rakeshsahni"
},
{
"code": null,
"e": 33311,
"s": 33301,
"text": "samim2000"
},
{
"code": null,
"e": 33328,
"s": 33311,
"text": "surinderdawra388"
},
{
"code": null,
"e": 33341,
"s": 33328,
"text": "Prime Number"
},
{
"code": null,
"e": 33347,
"s": 33341,
"text": "sieve"
},
{
"code": null,
"e": 33360,
"s": 33347,
"text": "Mathematical"
},
{
"code": null,
"e": 33373,
"s": 33360,
"text": "Mathematical"
},
{
"code": null,
"e": 33386,
"s": 33373,
"text": "Prime Number"
},
{
"code": null,
"e": 33392,
"s": 33386,
"text": "sieve"
},
{
"code": null,
"e": 33490,
"s": 33392,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33499,
"s": 33490,
"text": "Comments"
},
{
"code": null,
"e": 33512,
"s": 33499,
"text": "Old Comments"
},
{
"code": null,
"e": 33557,
"s": 33512,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 33589,
"s": 33557,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 33633,
"s": 33589,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 33658,
"s": 33633,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 33691,
"s": 33658,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 33726,
"s": 33691,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 33777,
"s": 33726,
"text": "Add two numbers without using arithmetic operators"
},
{
"code": null,
"e": 33811,
"s": 33777,
"text": "Program to add two binary strings"
},
{
"code": null,
"e": 33854,
"s": 33811,
"text": "Program to convert a given number to words"
}
] |
Extract numbers from list of strings in Python
|
While using python for data manipulation, we may come across lists whose elements are a mix of letters and numbers with a fixed pattern. In this article we will see how to separate the numbers form letters which can be used for future calculations.
The split functions splits a string by help of a character that is treated as a separator. In the program below the list elements have hyphen as their separator between letters and text. We will use that along with a for loop to capture each
Live Demo
listA = ['Mon-2', 'Wed-8', 'Thu-2', 'Fri-7']
# Given list
print("Given list : " + str(listA))
# Extracting numbers
num_list = [int(i.split('-')[1]) for i in listA]
# print result
print("List only with numbers : ",num_list)
Running the above code gives us the following result −
Given list : ['Mon-2', 'Wed-8', 'Thu-2', 'Fri-7']
List only with numbers : [2, 8, 2, 7]
In this approach we go through each element and check for the numeric part present in each element. The map function is used to apply the same function repeatedly on each of the element.
listA = ['Mon-2', 'Wed-8', 'Thu-2', 'Fri-7']
# Given list
print("Given list : " + str(listA))
# Extracting numbers
num_list = list(map(lambda sub:int(''.join(
[i for i in sub if i.isnumeric()])), listA))
# print result
print("List only with numbers : ",num_list)
Running the above code gives us the following result −
Given list : ['Mon-2', 'Wed-8', 'Thu-2', 'Fri-7']
List only with numbers : [2, 8, 2, 7]
|
[
{
"code": null,
"e": 1311,
"s": 1062,
"text": "While using python for data manipulation, we may come across lists whose elements are a mix of letters and numbers with a fixed pattern. In this article we will see how to separate the numbers form letters which can be used for future calculations."
},
{
"code": null,
"e": 1553,
"s": 1311,
"text": "The split functions splits a string by help of a character that is treated as a separator. In the program below the list elements have hyphen as their separator between letters and text. We will use that along with a for loop to capture each"
},
{
"code": null,
"e": 1564,
"s": 1553,
"text": " Live Demo"
},
{
"code": null,
"e": 1790,
"s": 1564,
"text": "listA = ['Mon-2', 'Wed-8', 'Thu-2', 'Fri-7']\n\n# Given list\nprint(\"Given list : \" + str(listA))\n\n# Extracting numbers\nnum_list = [int(i.split('-')[1]) for i in listA]\n\n# print result\nprint(\"List only with numbers : \",num_list)"
},
{
"code": null,
"e": 1845,
"s": 1790,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1933,
"s": 1845,
"text": "Given list : ['Mon-2', 'Wed-8', 'Thu-2', 'Fri-7']\nList only with numbers : [2, 8, 2, 7]"
},
{
"code": null,
"e": 2120,
"s": 1933,
"text": "In this approach we go through each element and check for the numeric part present in each element. The map function is used to apply the same function repeatedly on each of the element."
},
{
"code": null,
"e": 2386,
"s": 2120,
"text": "listA = ['Mon-2', 'Wed-8', 'Thu-2', 'Fri-7']\n\n# Given list\nprint(\"Given list : \" + str(listA))\n\n# Extracting numbers\nnum_list = list(map(lambda sub:int(''.join(\n[i for i in sub if i.isnumeric()])), listA))\n\n# print result\nprint(\"List only with numbers : \",num_list)"
},
{
"code": null,
"e": 2441,
"s": 2386,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2529,
"s": 2441,
"text": "Given list : ['Mon-2', 'Wed-8', 'Thu-2', 'Fri-7']\nList only with numbers : [2, 8, 2, 7]"
}
] |
How to mute audio using HTML5 ? - GeeksforGeeks
|
14 Jul, 2020
In this article, we mute the audio by using the muted attribute in the <audio> tag of the HTML document. It is used to define that the audio should be muted on the webpage.
Syntax:
<audio controls muted>
Example:
<!DOCTYPE html> <html> <head> <title> How to mute an audio using HTML5? </title></head> <body> <h2> GeeksForGeeks </h2> <h2> How to mute an audio using HTML5? </h2> <p>Audio Sample</p> <audio controls muted> <source src="test.mp3" type="audio/mp3"> <source src="test.ogg" type="audio/ogg"> </audio> </body> </html>
Output:Supported browsers are listed below:
Google Chrome 4.0
Internet Explorer 9.0
Firefox 3.5
Opera 10.5
Safari 4.0
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Misc
HTML5
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
Form validation using jQuery
How to place text on image using HTML and CSS?
How to auto-resize an image to fit a div container using CSS?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 24503,
"s": 24475,
"text": "\n14 Jul, 2020"
},
{
"code": null,
"e": 24676,
"s": 24503,
"text": "In this article, we mute the audio by using the muted attribute in the <audio> tag of the HTML document. It is used to define that the audio should be muted on the webpage."
},
{
"code": null,
"e": 24684,
"s": 24676,
"text": "Syntax:"
},
{
"code": null,
"e": 24707,
"s": 24684,
"text": "<audio controls muted>"
},
{
"code": null,
"e": 24716,
"s": 24707,
"text": "Example:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> How to mute an audio using HTML5? </title></head> <body> <h2> GeeksForGeeks </h2> <h2> How to mute an audio using HTML5? </h2> <p>Audio Sample</p> <audio controls muted> <source src=\"test.mp3\" type=\"audio/mp3\"> <source src=\"test.ogg\" type=\"audio/ogg\"> </audio> </body> </html> ",
"e": 25124,
"s": 24716,
"text": null
},
{
"code": null,
"e": 25168,
"s": 25124,
"text": "Output:Supported browsers are listed below:"
},
{
"code": null,
"e": 25186,
"s": 25168,
"text": "Google Chrome 4.0"
},
{
"code": null,
"e": 25208,
"s": 25186,
"text": "Internet Explorer 9.0"
},
{
"code": null,
"e": 25220,
"s": 25208,
"text": "Firefox 3.5"
},
{
"code": null,
"e": 25231,
"s": 25220,
"text": "Opera 10.5"
},
{
"code": null,
"e": 25242,
"s": 25231,
"text": "Safari 4.0"
},
{
"code": null,
"e": 25379,
"s": 25242,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 25389,
"s": 25379,
"text": "HTML-Misc"
},
{
"code": null,
"e": 25395,
"s": 25389,
"text": "HTML5"
},
{
"code": null,
"e": 25400,
"s": 25395,
"text": "HTML"
},
{
"code": null,
"e": 25417,
"s": 25400,
"text": "Web Technologies"
},
{
"code": null,
"e": 25422,
"s": 25417,
"text": "HTML"
},
{
"code": null,
"e": 25520,
"s": 25422,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25529,
"s": 25520,
"text": "Comments"
},
{
"code": null,
"e": 25542,
"s": 25529,
"text": "Old Comments"
},
{
"code": null,
"e": 25566,
"s": 25542,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 25603,
"s": 25566,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 25632,
"s": 25603,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 25679,
"s": 25632,
"text": "How to place text on image using HTML and CSS?"
},
{
"code": null,
"e": 25741,
"s": 25679,
"text": "How to auto-resize an image to fit a div container using CSS?"
},
{
"code": null,
"e": 25797,
"s": 25741,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 25830,
"s": 25797,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 25873,
"s": 25830,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 25934,
"s": 25873,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
Algorithms From Scratch: Naive Bayes Classifier | by Kurtis Pykes | Towards Data Science
|
The Naive Bayes classifier is an Eager Learning algorithm that belongs to a family of simple probabilistic classifiers based on Bayes’ Theorem.
Although Bayes Theorem — put simply, is a principled way of calculating a conditional probability without the joint probability — assumes each input is dependent upon all other variables, to use it as a classifier we remove this assumption and consider each variable to be independent of each other and refer to this simplification of Bayes Theorem for predictive modelling as the Naive Bayes classifier. In other words, Naive Bayes assumes that the presence of a predictor in a class is not related to the presence of any other predictor. This is a very strong assumption given that it is very unlikely the predictors do not interact in real-world data.
By the way, if you are unfamiliar with Eager Learning, Eager Learning refers to the learning method in which the system aims to construct a general, input-independent target function during the training of the system. On the contrary, Algorithms such as K-Nearest Neighbors , which is a lazy learner, wait until a query is made before any generalization is made beyond the training data.
Essentially, Naive Bayes (or Idiot Bayes) earned its name due to the calculations for each class being simplified to make their calculations tractable, however the classifier proven itself to be effective in many real-world scenarios, whether it is a binary classification or multi-class classification, despite its naive design and oversimplified assumptions.
For the full code used in this notebook...
github.com
As we stated earlier, if we are going to apply Bayes Theorem for a conditional probability classification model (Naive Bayes model) then we need to simplify the calculation.
Before going into how we can simplify the model I am going to give a brief introduction into Marginal Probability, Joint Probability and Conditional Probability:
Marginal Probability — The probability of an event irrespective of other random variables, for instance P(A) where this means the probability of A occurring.
Joint Probability — The probability of two or more simultaneous events, for example P(A and B) or P(A, B).
Conditional Probability — Probability of one or more events given the occurrence of another event, for example P(A|B) which could be stated as the Probability of A given B.
A cool thing about these probabilities is that we could use them to calculate one another. The joint probability can be calculated by using the conditional probability — this is known as the product rule; See Figure 1.
An interesting fact about the product rule is that it is symmetrical meaning that P(A, B) = P(B, A). On the other hand, the conditional probability is not symmetrical meaning that P(A|B) != P(B|A), however what we can do is, we can calculate the conditional probability using the joint probability — see Figure 2.
There is one problem with Figure 2; It’s often quite difficult to calculate the joint probability, so when we want to work out the conditional probability we use an alternate method. The alternate method we use is called Bayes Rule or Bayes Theorem and it’s done by using one conditional probability to workout the other — See Figure 3
Note: We may also decide to use the alternative approach to calculating the conditional probability when the reverse conditional probability is available or easier to calculate.
To name the terms in Bayes Theorem, we must take into consideration the context of where the equation is used — See Figure 4.
Hence, we can restate Bayes Theorem as...
To model this as a classification model we do this...
However, this expression is a cause of complexity in our calculation so to simplify it we remove the assumption of dependence and considering each variable independent we simplify our classifier.
Note: We drop the denominator (the probability of observing the data in this instance) as it is a constant for all calculations.
And there you have it... Well not quite. This calculation is performed for each of the class labels but we only want to know the class that is most probable for a given instance. Hence, we must find the label with the largest probability to be selected as the classification for the given instance; The name of this decision rule is called Maximum A Posteriori (MAP) — Now there you have the Naive Bayes Classifier.
Chunking the Algorithm
Segment the data by the class, and then compute the mean and variance of x in each class.Calculate Probability using Gaussian Probability Density FunctionGet Class ProbabilitiesGet Final Prediction
Segment the data by the class, and then compute the mean and variance of x in each class.
Calculate Probability using Gaussian Probability Density Function
Get Class Probabilities
Get Final Prediction
Implementation
We are going to be using the iris dataset and since the variables used in this Dataset are numeric, we will build a Gaussian Naive Bayes model.
Note: The different naive Bayes classifiers differ mainly by the assumptions they make regarding the distribution of P(Xi | y) (Source: Scikit-Learn Naive Bayes)
import numpy as np import pandas as pdfrom sklearn.datasets import load_irisfrom sklearn.naive_bayes import GaussianNBfrom sklearn.metrics import accuracy_scorefrom sklearn.model_selection import train_test_split# loading the datairis = load_iris()X, y = iris.data, iris.target# spliting data to train and testX_train, X_test, y_train, y_test = train_test_split(X, y, test_size= 0.2, random_state=1810)X_train.shape, y_train.shape, X_test.shape, y_test.shape((120, 4), (120,), (30, 4), (30,))# scikit learn implementation nb = GaussianNB()nb.fit(X_train, y_train)sklearn_preds = nb.predict(X_test)print(f"sklearn accuracy:{accuracy_score(y_test, sklearn_preds)}")print(f"predictions: {sklearn_preds}")sklearn accuracy:1.0predictions: [0 0 2 2 0 1 0 0 1 1 2 1 2 0 1 2 0 0 0 2 1 2 0 0 0 0 1 1 0 2]
Scikit-Learn implementation gives us a perfect accuracy score on inference, Let’s build our own model and see if we can match the Scikit-learn implementation.
I have built a utility function get_params just so that we can get some parameters for our training data.
def get_params(X_train, y_train): """ Function to get the unique classes, number of classes and number of features in training data """ num_examples, num_features = X_train.shape num_classes = len(np.unique(y_train)) return num_examples, num_features, num_classes# testing utility functionnum_examples, num_features, num_classes = get_params(X_train, y_train)print(num_examples, num_features, num_classes)120 4 3
Our utility function is working great so we can proceed to step one of getting the statistics (specifically mean, variance and the priors) by the class.
def get_stats_by_class(X_train, y_train, num_examples=num_examples, num_classes=num_classes): """ Get stats of dataset by the class """ # dictionaries to store stats class_mean = {} class_var = {} class_prior = {} # loop through each class and get mean, variance and prior by class for cls in range(num_classes): X_cls = X_train[y_train == cls] class_mean[str(cls)] = np.mean(X_cls, axis=0) class_var[str(cls)] = np.var(X_cls, axis=0) class_prior[str(cls)] = X_cls.shape[0] / num_examples return class_mean, class_var, class_prior# output of function cm, var, cp = get_stats_by_class(X_train, y_train)cm, var, cp# output of function cm, var, cp = get_stats_by_class(X_train, y_train)print(f"mean: {cm}\n\nvariance: {var}\n\npriors: {cp}")mean: {'0': array([5.06111111, 3.48611111, 1.44722222, 0.25833333]), '1': array([5.90952381, 2.80714286, 4.25238095, 1.33809524]), '2': array([6.61904762, 2.97857143, 5.58571429, 2.02142857])}variance: {'0': array([0.12570988, 0.15564043, 0.0286034 , 0.01243056]), '1': array([0.26324263, 0.08542517, 0.24582766, 0.04045351]), '2': array([0.43678005, 0.10930272, 0.31884354, 0.0802551 ])}priors: {'0': 0.3, '1': 0.35, '2': 0.35}
We passed the num_classes and num_examples that we got from get_params to the function as they are required to separate the data by class and calculate the priors by class. Now that we have the enough information to work out the class probabilities — Well not quite, we are dealing with continuous data and a typical assumption is that the continuous values associated with each class are distributed according to Gaussian distribution (Source: Wikipedia). As a result we built a function to calculate the density function that’s going to help us calculate the probability from a Gaussian Distribution.
def gaussian_density_function(X, mean, std, num_examples=num_examples, num_features=num_features, eps=1e-6): num_exambles, num_features = X_train.shape const = -num_features/2 * np.log(2*np.pi) - 0.5 * np.sum(np.log(std + eps)) probs = 0.5 * np.sum(np.power(X - mean, 2)/(std + eps), 1) return const - probsgaussian_density_function(X_train, cm[str(0)], var[str(0)])array([-4.34046349e+02, -1.59180054e+02, -1.61095055e+02, 9.25593725e-01, -2.40503860e+02, -4.94829021e+02, -8.44007497e+01, -1.24647713e+02, -2.85653665e+00, -5.72257925e+02, -3.88046018e+02, -2.24563508e+02, 2.14664687e+00, -6.59682718e+02, -1.42720100e+02, -4.38322421e+02, -2.27259034e+02, -2.43243607e+02, -2.60192759e+02, -6.69113243e-01, -2.12744190e+02, -1.96296373e+00, 5.27718947e-01, -8.37591818e+01, -3.74910393e+02, -4.12550151e+02, -5.26784003e+02, 2.02972576e+00, -7.15335962e+02, -4.20276820e+02, 1.96012133e+00, -3.00593481e+02, -2.47461333e+02, -1.60575712e+02, -2.89201209e+02, -2.92885637e+02, -3.13408398e+02, -3.58425796e+02, -3.91682377e+00, 1.39469746e+00, -5.96494272e+02, -2.28962605e+02, -3.30798243e+02, -6.31249585e+02, -2.13727911e+02, -3.30118570e+02, -1.67525014e+02, -1.76565131e+02, 9.43246044e-01, 1.79792264e+00, -5.80893842e+02, -4.89795508e+02, -1.52006930e+02, -2.23865257e+02, -3.95841849e+00, -2.96494860e+02, -9.76659579e+01, -3.45123893e+02, -2.61299515e+02, 7.51925529e-01, -1.57383774e+02, -1.13127846e+02, 6.89240784e-02, -4.32253752e+02, -2.25822704e+00, -1.95763452e+02, -2.54997829e-01, -1.66303411e+02, -2.94088881e+02, -1.47028139e+02, -4.89549541e+02, -4.61090964e+02, 1.22387847e+00, -8.22913900e-02, 9.67128415e-01, -2.30042263e+02, -2.90035079e+00, -2.36569499e+02, 1.42223431e+00, 9.35599166e-01, -3.74718213e+02, -2.07417873e+02, -4.19130888e+02, 7.79051525e-01, 1.82103882e+00, -2.77364308e+02, 9.64732218e-01, -7.15058948e+01, -2.82064236e+02, -1.89898997e+02, 9.79605922e-01, -6.24660543e+02, 1.70258877e+00, -3.17104964e-01, -4.23008651e+02, -1.32107552e+00, -3.09809542e+02, -4.01988565e+02, -2.55855351e+02, -2.25652042e+02, 1.00821726e+00, -2.24154135e+02, 2.07961315e+00, -3.08858104e+02, -4.95246865e+02, -4.74107852e+02, -5.24258175e+02, -5.26011925e+02, -3.43520576e+02, -4.59462733e+02, -1.68243666e+02, 1.06990125e+00, 2.04670066e+00, -8.64641201e-01, -3.89431048e+02, -1.00629804e+02, 1.25321722e+00, -5.07813723e+02, -1.27546482e+02, -4.43687565e+02])
Here is a function to calculate the class probabilities...
def class_probabilities(X, class_mean, class_var, class_prior, num_classes=num_classes): """ calculate the probability of each class given the data """ num_examples = X.shape[0] probs = np.zeros((num_examples, num_classes))for cls in range(num_classes): prior = class_prior[str(cls)] probs_cls = gaussian_density_function(X, class_mean[str(cls)], class_var[str(cls)]) probs[:, cls] = probs_cls + np.log(prior) return probs
Now we need to make a prediction using MAP so let’s put all these steps together in a predict function and output the max probability class.
def predict(X_test, X_train, y_train): num_examples, num_features, num_classes = get_params(X_test, y_train) class_mean, class_std, class_prior = get_stats_by_class(X_train, y_train) probs = class_probabilities(X_test, class_mean, class_std, class_prior) return np.argmax(probs, 1)my_preds = predict(X_test, X_train, y_train)print(f"my predictions accuracy:{accuracy_score(y_test, my_preds)}")print(f"predictions: {my_preds}")my predictions accuracy:1.0predictions: [0 0 2 2 0 1 0 0 1 1 2 1 2 0 1 2 0 0 0 2 1 2 0 0 0 0 1 1 0 2]
As a sanity check...
sklearn_preds == my_predsarray([ True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True])
and that’s the way the cookie crumbles!
Require a small amount of training data to estimate the necessary parameters
Extremely fast compared to sophisticated methods
Known to be a bad estimator (In the Scikit-Learn framework, the outputs from predict_proba aren’t taken too seriously.
The assumption of independent predictors doesn’t hold true (most of the time) in the real world
You’ve now learnt about Naive Bayes Classifiers and how to build one from scratch using Python. Yes, the algorithm has very over-simplified assumptions, but it is still very effective in many real world applications and is worth trying if you want very fast predictions.
Let’s continue the conversation on LinkedIn...
|
[
{
"code": null,
"e": 190,
"s": 46,
"text": "The Naive Bayes classifier is an Eager Learning algorithm that belongs to a family of simple probabilistic classifiers based on Bayes’ Theorem."
},
{
"code": null,
"e": 845,
"s": 190,
"text": "Although Bayes Theorem — put simply, is a principled way of calculating a conditional probability without the joint probability — assumes each input is dependent upon all other variables, to use it as a classifier we remove this assumption and consider each variable to be independent of each other and refer to this simplification of Bayes Theorem for predictive modelling as the Naive Bayes classifier. In other words, Naive Bayes assumes that the presence of a predictor in a class is not related to the presence of any other predictor. This is a very strong assumption given that it is very unlikely the predictors do not interact in real-world data."
},
{
"code": null,
"e": 1233,
"s": 845,
"text": "By the way, if you are unfamiliar with Eager Learning, Eager Learning refers to the learning method in which the system aims to construct a general, input-independent target function during the training of the system. On the contrary, Algorithms such as K-Nearest Neighbors , which is a lazy learner, wait until a query is made before any generalization is made beyond the training data."
},
{
"code": null,
"e": 1594,
"s": 1233,
"text": "Essentially, Naive Bayes (or Idiot Bayes) earned its name due to the calculations for each class being simplified to make their calculations tractable, however the classifier proven itself to be effective in many real-world scenarios, whether it is a binary classification or multi-class classification, despite its naive design and oversimplified assumptions."
},
{
"code": null,
"e": 1637,
"s": 1594,
"text": "For the full code used in this notebook..."
},
{
"code": null,
"e": 1648,
"s": 1637,
"text": "github.com"
},
{
"code": null,
"e": 1822,
"s": 1648,
"text": "As we stated earlier, if we are going to apply Bayes Theorem for a conditional probability classification model (Naive Bayes model) then we need to simplify the calculation."
},
{
"code": null,
"e": 1984,
"s": 1822,
"text": "Before going into how we can simplify the model I am going to give a brief introduction into Marginal Probability, Joint Probability and Conditional Probability:"
},
{
"code": null,
"e": 2142,
"s": 1984,
"text": "Marginal Probability — The probability of an event irrespective of other random variables, for instance P(A) where this means the probability of A occurring."
},
{
"code": null,
"e": 2249,
"s": 2142,
"text": "Joint Probability — The probability of two or more simultaneous events, for example P(A and B) or P(A, B)."
},
{
"code": null,
"e": 2422,
"s": 2249,
"text": "Conditional Probability — Probability of one or more events given the occurrence of another event, for example P(A|B) which could be stated as the Probability of A given B."
},
{
"code": null,
"e": 2641,
"s": 2422,
"text": "A cool thing about these probabilities is that we could use them to calculate one another. The joint probability can be calculated by using the conditional probability — this is known as the product rule; See Figure 1."
},
{
"code": null,
"e": 2955,
"s": 2641,
"text": "An interesting fact about the product rule is that it is symmetrical meaning that P(A, B) = P(B, A). On the other hand, the conditional probability is not symmetrical meaning that P(A|B) != P(B|A), however what we can do is, we can calculate the conditional probability using the joint probability — see Figure 2."
},
{
"code": null,
"e": 3291,
"s": 2955,
"text": "There is one problem with Figure 2; It’s often quite difficult to calculate the joint probability, so when we want to work out the conditional probability we use an alternate method. The alternate method we use is called Bayes Rule or Bayes Theorem and it’s done by using one conditional probability to workout the other — See Figure 3"
},
{
"code": null,
"e": 3469,
"s": 3291,
"text": "Note: We may also decide to use the alternative approach to calculating the conditional probability when the reverse conditional probability is available or easier to calculate."
},
{
"code": null,
"e": 3595,
"s": 3469,
"text": "To name the terms in Bayes Theorem, we must take into consideration the context of where the equation is used — See Figure 4."
},
{
"code": null,
"e": 3637,
"s": 3595,
"text": "Hence, we can restate Bayes Theorem as..."
},
{
"code": null,
"e": 3691,
"s": 3637,
"text": "To model this as a classification model we do this..."
},
{
"code": null,
"e": 3887,
"s": 3691,
"text": "However, this expression is a cause of complexity in our calculation so to simplify it we remove the assumption of dependence and considering each variable independent we simplify our classifier."
},
{
"code": null,
"e": 4016,
"s": 3887,
"text": "Note: We drop the denominator (the probability of observing the data in this instance) as it is a constant for all calculations."
},
{
"code": null,
"e": 4432,
"s": 4016,
"text": "And there you have it... Well not quite. This calculation is performed for each of the class labels but we only want to know the class that is most probable for a given instance. Hence, we must find the label with the largest probability to be selected as the classification for the given instance; The name of this decision rule is called Maximum A Posteriori (MAP) — Now there you have the Naive Bayes Classifier."
},
{
"code": null,
"e": 4455,
"s": 4432,
"text": "Chunking the Algorithm"
},
{
"code": null,
"e": 4653,
"s": 4455,
"text": "Segment the data by the class, and then compute the mean and variance of x in each class.Calculate Probability using Gaussian Probability Density FunctionGet Class ProbabilitiesGet Final Prediction"
},
{
"code": null,
"e": 4743,
"s": 4653,
"text": "Segment the data by the class, and then compute the mean and variance of x in each class."
},
{
"code": null,
"e": 4809,
"s": 4743,
"text": "Calculate Probability using Gaussian Probability Density Function"
},
{
"code": null,
"e": 4833,
"s": 4809,
"text": "Get Class Probabilities"
},
{
"code": null,
"e": 4854,
"s": 4833,
"text": "Get Final Prediction"
},
{
"code": null,
"e": 4869,
"s": 4854,
"text": "Implementation"
},
{
"code": null,
"e": 5013,
"s": 4869,
"text": "We are going to be using the iris dataset and since the variables used in this Dataset are numeric, we will build a Gaussian Naive Bayes model."
},
{
"code": null,
"e": 5175,
"s": 5013,
"text": "Note: The different naive Bayes classifiers differ mainly by the assumptions they make regarding the distribution of P(Xi | y) (Source: Scikit-Learn Naive Bayes)"
},
{
"code": null,
"e": 5971,
"s": 5175,
"text": "import numpy as np import pandas as pdfrom sklearn.datasets import load_irisfrom sklearn.naive_bayes import GaussianNBfrom sklearn.metrics import accuracy_scorefrom sklearn.model_selection import train_test_split# loading the datairis = load_iris()X, y = iris.data, iris.target# spliting data to train and testX_train, X_test, y_train, y_test = train_test_split(X, y, test_size= 0.2, random_state=1810)X_train.shape, y_train.shape, X_test.shape, y_test.shape((120, 4), (120,), (30, 4), (30,))# scikit learn implementation nb = GaussianNB()nb.fit(X_train, y_train)sklearn_preds = nb.predict(X_test)print(f\"sklearn accuracy:{accuracy_score(y_test, sklearn_preds)}\")print(f\"predictions: {sklearn_preds}\")sklearn accuracy:1.0predictions: [0 0 2 2 0 1 0 0 1 1 2 1 2 0 1 2 0 0 0 2 1 2 0 0 0 0 1 1 0 2]"
},
{
"code": null,
"e": 6130,
"s": 5971,
"text": "Scikit-Learn implementation gives us a perfect accuracy score on inference, Let’s build our own model and see if we can match the Scikit-learn implementation."
},
{
"code": null,
"e": 6236,
"s": 6130,
"text": "I have built a utility function get_params just so that we can get some parameters for our training data."
},
{
"code": null,
"e": 6668,
"s": 6236,
"text": "def get_params(X_train, y_train): \"\"\" Function to get the unique classes, number of classes and number of features in training data \"\"\" num_examples, num_features = X_train.shape num_classes = len(np.unique(y_train)) return num_examples, num_features, num_classes# testing utility functionnum_examples, num_features, num_classes = get_params(X_train, y_train)print(num_examples, num_features, num_classes)120 4 3"
},
{
"code": null,
"e": 6821,
"s": 6668,
"text": "Our utility function is working great so we can proceed to step one of getting the statistics (specifically mean, variance and the priors) by the class."
},
{
"code": null,
"e": 8054,
"s": 6821,
"text": "def get_stats_by_class(X_train, y_train, num_examples=num_examples, num_classes=num_classes): \"\"\" Get stats of dataset by the class \"\"\" # dictionaries to store stats class_mean = {} class_var = {} class_prior = {} # loop through each class and get mean, variance and prior by class for cls in range(num_classes): X_cls = X_train[y_train == cls] class_mean[str(cls)] = np.mean(X_cls, axis=0) class_var[str(cls)] = np.var(X_cls, axis=0) class_prior[str(cls)] = X_cls.shape[0] / num_examples return class_mean, class_var, class_prior# output of function cm, var, cp = get_stats_by_class(X_train, y_train)cm, var, cp# output of function cm, var, cp = get_stats_by_class(X_train, y_train)print(f\"mean: {cm}\\n\\nvariance: {var}\\n\\npriors: {cp}\")mean: {'0': array([5.06111111, 3.48611111, 1.44722222, 0.25833333]), '1': array([5.90952381, 2.80714286, 4.25238095, 1.33809524]), '2': array([6.61904762, 2.97857143, 5.58571429, 2.02142857])}variance: {'0': array([0.12570988, 0.15564043, 0.0286034 , 0.01243056]), '1': array([0.26324263, 0.08542517, 0.24582766, 0.04045351]), '2': array([0.43678005, 0.10930272, 0.31884354, 0.0802551 ])}priors: {'0': 0.3, '1': 0.35, '2': 0.35}"
},
{
"code": null,
"e": 8657,
"s": 8054,
"text": "We passed the num_classes and num_examples that we got from get_params to the function as they are required to separate the data by class and calculate the priors by class. Now that we have the enough information to work out the class probabilities — Well not quite, we are dealing with continuous data and a typical assumption is that the continuous values associated with each class are distributed according to Gaussian distribution (Source: Wikipedia). As a result we built a function to calculate the density function that’s going to help us calculate the probability from a Gaussian Distribution."
},
{
"code": null,
"e": 11258,
"s": 8657,
"text": "def gaussian_density_function(X, mean, std, num_examples=num_examples, num_features=num_features, eps=1e-6): num_exambles, num_features = X_train.shape const = -num_features/2 * np.log(2*np.pi) - 0.5 * np.sum(np.log(std + eps)) probs = 0.5 * np.sum(np.power(X - mean, 2)/(std + eps), 1) return const - probsgaussian_density_function(X_train, cm[str(0)], var[str(0)])array([-4.34046349e+02, -1.59180054e+02, -1.61095055e+02, 9.25593725e-01, -2.40503860e+02, -4.94829021e+02, -8.44007497e+01, -1.24647713e+02, -2.85653665e+00, -5.72257925e+02, -3.88046018e+02, -2.24563508e+02, 2.14664687e+00, -6.59682718e+02, -1.42720100e+02, -4.38322421e+02, -2.27259034e+02, -2.43243607e+02, -2.60192759e+02, -6.69113243e-01, -2.12744190e+02, -1.96296373e+00, 5.27718947e-01, -8.37591818e+01, -3.74910393e+02, -4.12550151e+02, -5.26784003e+02, 2.02972576e+00, -7.15335962e+02, -4.20276820e+02, 1.96012133e+00, -3.00593481e+02, -2.47461333e+02, -1.60575712e+02, -2.89201209e+02, -2.92885637e+02, -3.13408398e+02, -3.58425796e+02, -3.91682377e+00, 1.39469746e+00, -5.96494272e+02, -2.28962605e+02, -3.30798243e+02, -6.31249585e+02, -2.13727911e+02, -3.30118570e+02, -1.67525014e+02, -1.76565131e+02, 9.43246044e-01, 1.79792264e+00, -5.80893842e+02, -4.89795508e+02, -1.52006930e+02, -2.23865257e+02, -3.95841849e+00, -2.96494860e+02, -9.76659579e+01, -3.45123893e+02, -2.61299515e+02, 7.51925529e-01, -1.57383774e+02, -1.13127846e+02, 6.89240784e-02, -4.32253752e+02, -2.25822704e+00, -1.95763452e+02, -2.54997829e-01, -1.66303411e+02, -2.94088881e+02, -1.47028139e+02, -4.89549541e+02, -4.61090964e+02, 1.22387847e+00, -8.22913900e-02, 9.67128415e-01, -2.30042263e+02, -2.90035079e+00, -2.36569499e+02, 1.42223431e+00, 9.35599166e-01, -3.74718213e+02, -2.07417873e+02, -4.19130888e+02, 7.79051525e-01, 1.82103882e+00, -2.77364308e+02, 9.64732218e-01, -7.15058948e+01, -2.82064236e+02, -1.89898997e+02, 9.79605922e-01, -6.24660543e+02, 1.70258877e+00, -3.17104964e-01, -4.23008651e+02, -1.32107552e+00, -3.09809542e+02, -4.01988565e+02, -2.55855351e+02, -2.25652042e+02, 1.00821726e+00, -2.24154135e+02, 2.07961315e+00, -3.08858104e+02, -4.95246865e+02, -4.74107852e+02, -5.24258175e+02, -5.26011925e+02, -3.43520576e+02, -4.59462733e+02, -1.68243666e+02, 1.06990125e+00, 2.04670066e+00, -8.64641201e-01, -3.89431048e+02, -1.00629804e+02, 1.25321722e+00, -5.07813723e+02, -1.27546482e+02, -4.43687565e+02])"
},
{
"code": null,
"e": 11317,
"s": 11258,
"text": "Here is a function to calculate the class probabilities..."
},
{
"code": null,
"e": 11780,
"s": 11317,
"text": "def class_probabilities(X, class_mean, class_var, class_prior, num_classes=num_classes): \"\"\" calculate the probability of each class given the data \"\"\" num_examples = X.shape[0] probs = np.zeros((num_examples, num_classes))for cls in range(num_classes): prior = class_prior[str(cls)] probs_cls = gaussian_density_function(X, class_mean[str(cls)], class_var[str(cls)]) probs[:, cls] = probs_cls + np.log(prior) return probs"
},
{
"code": null,
"e": 11921,
"s": 11780,
"text": "Now we need to make a prediction using MAP so let’s put all these steps together in a predict function and output the max probability class."
},
{
"code": null,
"e": 12462,
"s": 11921,
"text": "def predict(X_test, X_train, y_train): num_examples, num_features, num_classes = get_params(X_test, y_train) class_mean, class_std, class_prior = get_stats_by_class(X_train, y_train) probs = class_probabilities(X_test, class_mean, class_std, class_prior) return np.argmax(probs, 1)my_preds = predict(X_test, X_train, y_train)print(f\"my predictions accuracy:{accuracy_score(y_test, my_preds)}\")print(f\"predictions: {my_preds}\")my predictions accuracy:1.0predictions: [0 0 2 2 0 1 0 0 1 1 2 1 2 0 1 2 0 0 0 2 1 2 0 0 0 0 1 1 0 2]"
},
{
"code": null,
"e": 12483,
"s": 12462,
"text": "As a sanity check..."
},
{
"code": null,
"e": 12744,
"s": 12483,
"text": "sklearn_preds == my_predsarray([ True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True])"
},
{
"code": null,
"e": 12784,
"s": 12744,
"text": "and that’s the way the cookie crumbles!"
},
{
"code": null,
"e": 12861,
"s": 12784,
"text": "Require a small amount of training data to estimate the necessary parameters"
},
{
"code": null,
"e": 12910,
"s": 12861,
"text": "Extremely fast compared to sophisticated methods"
},
{
"code": null,
"e": 13029,
"s": 12910,
"text": "Known to be a bad estimator (In the Scikit-Learn framework, the outputs from predict_proba aren’t taken too seriously."
},
{
"code": null,
"e": 13125,
"s": 13029,
"text": "The assumption of independent predictors doesn’t hold true (most of the time) in the real world"
},
{
"code": null,
"e": 13396,
"s": 13125,
"text": "You’ve now learnt about Naive Bayes Classifiers and how to build one from scratch using Python. Yes, the algorithm has very over-simplified assumptions, but it is still very effective in many real world applications and is worth trying if you want very fast predictions."
}
] |
Exclude certain columns from SHOW COLUMNS in MySQL?
|
Let us first create a demo table
mysql> create table excludeCertainColumnsDemo
-> (
-> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> StudentName varchar(100),
-> StudentAge int,
-> StudentMarks int,
-> StudentAddress varchar(200)
-> );
Query OK, 0 rows affected (0.50 sec)
Now you can check the description of table with the help of desc command. The query is as follows −
mysql> desc excludeCertainColumnsDemo;
The following is the output
+----------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------+--------------+------+-----+---------+----------------+
| StudentId | int(11) | NO | PRI | NULL | auto_increment |
| StudentName | varchar(100) | YES | | NULL | |
| StudentAge | int(11) | YES | | NULL | |
| StudentMarks | int(11) | YES | | NULL | |
| StudentAddress | varchar(200) | YES | | NULL | |
+----------------+--------------+------+-----+---------+----------------+
5 rows in set (0.01 sec)
Here is the query to exclude certain columns from SHOW COLUMNS. You need to exclude the column 'StudentAge' and 'StudentMarks'. The query is as follows −
mysql> SHOW COLUMNS FROM excludeCertainColumnsDemo WHERE Field NOT IN ('StudentAge', 'StudentMarks');
The following is the output
+----------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------+--------------+------+-----+---------+----------------+
| StudentId | int(11) | NO | PRI | NULL | auto_increment |
| StudentName | varchar(100) | YES | | NULL | |
| StudentAddress | varchar(200) | YES | | NULL | |
+----------------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1095,
"s": 1062,
"text": "Let us first create a demo table"
},
{
"code": null,
"e": 1364,
"s": 1095,
"text": "mysql> create table excludeCertainColumnsDemo\n -> (\n -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> StudentName varchar(100),\n -> StudentAge int,\n -> StudentMarks int,\n -> StudentAddress varchar(200)\n -> );\nQuery OK, 0 rows affected (0.50 sec)"
},
{
"code": null,
"e": 1464,
"s": 1364,
"text": "Now you can check the description of table with the help of desc command. The query is as follows −"
},
{
"code": null,
"e": 1503,
"s": 1464,
"text": "mysql> desc excludeCertainColumnsDemo;"
},
{
"code": null,
"e": 1531,
"s": 1503,
"text": "The following is the output"
},
{
"code": null,
"e": 2222,
"s": 1531,
"text": "+----------------+--------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+----------------+--------------+------+-----+---------+----------------+\n| StudentId | int(11) | NO | PRI | NULL | auto_increment |\n| StudentName | varchar(100) | YES | | NULL | |\n| StudentAge | int(11) | YES | | NULL | |\n| StudentMarks | int(11) | YES | | NULL | |\n| StudentAddress | varchar(200) | YES | | NULL | |\n+----------------+--------------+------+-----+---------+----------------+\n5 rows in set (0.01 sec)"
},
{
"code": null,
"e": 2376,
"s": 2222,
"text": "Here is the query to exclude certain columns from SHOW COLUMNS. You need to exclude the column 'StudentAge' and 'StudentMarks'. The query is as follows −"
},
{
"code": null,
"e": 2478,
"s": 2376,
"text": "mysql> SHOW COLUMNS FROM excludeCertainColumnsDemo WHERE Field NOT IN ('StudentAge', 'StudentMarks');"
},
{
"code": null,
"e": 2506,
"s": 2478,
"text": "The following is the output"
},
{
"code": null,
"e": 3049,
"s": 2506,
"text": "+----------------+--------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+----------------+--------------+------+-----+---------+----------------+\n| StudentId | int(11) | NO | PRI | NULL | auto_increment |\n| StudentName | varchar(100) | YES | | NULL | |\n| StudentAddress | varchar(200) | YES | | NULL | |\n+----------------+--------------+------+-----+---------+----------------+\n3 rows in set (0.00 sec)"
}
] |
Flutter - Introduction to State Management Using Riverpod - GeeksforGeeks
|
07 Sep, 2021
Riverpod is a Reactive State-Management and Dependency Injection framework, it uses different providers to let us access and listen to state changes across our app, it is built by Remi Rousselet. If you don’t know what is state then I’ll recommend you to read this article first as it will be a little hard for you to understand Riverpod without understanding the “state” itself.
Riverpod is a state management helper. It basically makes our state (in clear words, our variables’ values) accessible in all parts of the app, it puts our state at the top of the widget tree and lets us listen to those state changes and update our User Interface accordingly.
There are many types of providers which Riverpod offers, We’ll go over them one by one.
Providers are the most important part of a Riverpod application, “A provider is an object that encapsulates a piece of state and allows listening to that state.”
Types of Providers:
StateProvider
FutureProvider
StreamProvider
Provider
Let’s start building!
Dart
dependencies: flutter_riverpod: ^0.14.0+3
For providers to work, we must add ProviderScope at the root of our Flutter applications:
Dart
import 'package:flutter_riverpod/flutter_riverpod.dart';void main() { runApp(ProviderScope(child: MyApp()));}
We’ll define all our global providers in this file so that it is easier to maintain the project. Let’s define a StateProvider.
Dart
import 'package:flutter_riverpod/flutter_riverpod.dart'; // Instead of String you can use other data types as well,// we can also use custom data types.final userNameProvider=StateProvider<String>((ref) { // we can also return an empty String here, for the sake of simplicity, // let's return a sample name return "SomeName";});
Now that we’ve declared a StateProvider, Let’s learn how can we read providers. To read any provider, we have multiple widgets, in this article, we’ll go over ConsumerWidget() and Consumer().
Using a ConsumerWidget():
A consumer widget is a widget that we can use in place of our Stateful/Stateless widget. It gives us the ability to read/change the states of providers & also listen to them.
Dart
import 'Providers/providers.dart' as providers.dart; //for easy accessimport 'package:flutter_riverpod/flutter_riverpod.dart'; class Home extends ConsumerWidget { @override Widget build(BuildContext context, ScopedReader watch) { // Listens to the value exposed by userNameProvider // ".state" method lets us get the state easily & directly String name = watch(providers.userNameProvider).state; return MaterialApp( home: Scaffold( appBar: AppBar(title: Center(child: const Text('GFG '))), body: Center( // displaying the value child: Text('$name'), ), ), ); }}
Output:
Well and good. So now, whenever the value of userNameProvider changes, the Text() will be updated accordingly. But how are we gonna update the value of userNameProvider?
To change the value of StateProvider, we need a StateController. So let’s create it.
First, let’s remove the variable “name”. ̶
S̶t̶r̶i̶n̶g̶ ̶n̶a̶m̶e̶ ̶=̶ ̶w̶a̶t̶c̶h̶(̶p̶r̶o̶v̶i̶d̶e̶r̶s̶.̶u̶s̶e̶r̶N̶a̶m̶e̶P̶r̶o̶v̶i̶d̶e̶r̶)̶.̶s̶t̶a̶t̶e̶;̶
//removed as with it we can only listen/get the state not change/mutate the state.
//let's use this StateController instead.
StateController<String> nameController = watch(providers.userNameProvider);
// now we can get / set the state using name.state.
For the sake of simplicity, let’s use a FloatingActionButton, and using it let’s try to mutate(change) the state of userNameProvider.
Dart
// for easy accessimport 'Providers/providers.dart' as providers.dart; class Home extends ConsumerWidget { int n = 0; @override Widget build(BuildContext context, ScopedReader watch) { // Listens to the value exposed by userNameProvider StateController<String> nameController = watch(providers.userNameProvider); // ".state" method lets us get the state easily & directly return MaterialApp( home: Scaffold( floatingActionButton: FloatingActionButton( onPressed: () { n++; nameController.state = // now we can set the state using the state setter. "New Name $n"; }, ), appBar: AppBar(title: Center(child: const Text('GFG '))), body: Center( child: Text( // displaying the value '${nameController.state}', ), ), ), ); }}
Output:
Now, when we press on the FloatingActionButton(), we’ll see that the name changes every time with a different number. So that’s it. Using this information we can easily use StateProviders, mutate their values and listen to it.
Now, Let’s go over asynchronous providers.
When we work with asynchronous code we often use some Future based APIs, let’s look into how you can handle Future events using Riverpod. To demonstrate, we will create a method which returns a Future.
Dart
class FutureClass { // in production, the below method could be any network call Future<int> getData(String para) async { await Future.delayed(Duration(seconds: 5)); return 25; }}
Creating a provider for FutureClass:
final futureClass = Provider((ref) => FutureClass());
Now, let’s create our FutureProvider,
Dart
final response = FutureProvider<int>((ref) async { final client = ref.read(futureClass); return client.getData('some text as a parameter');});
Now, we can use ConsumerWidget to listen to the state changes and update our UI accordingly.
Apart from the ConsumerWidget(), we also have a Consumer() widget. The difference is that while ConsumerWidget rebuilds the entire screen when state changes, Consumer() rebuilds only it’s child, making sure we don’t run into performance issues.
Let’s use Consumer() widget to watch(listen) for state changes.
Dart
class HomeScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("FutureProvider Demo"),), body: Center( child: Column( children: [ Consumer( builder: (context, watch, child) { final futureData = watch(response); }, ), ], ), ), ); }}
As a Future can have 3 states, i.e, completed, in progress & error, we have the ability to handle those states separately using the .map function.
Dart
Consumer( builder: (context, watch, child) { final futureData = watch(response); return futureData.map( ,// have data data: (data) => Text('${data.value}',) ,// in progress loading: (_) => CircularProgressIndicator() // has an error error: (message) => Text(message.error), ); },),
If we want to pass a variable/object to the provider as an argument, then we can do that like-
Dart
final response= FutureProvider.autoDispose.family<int, String>((ref, i_am_a_param) async { final client = ref.read(futureClass); return client.getData(i_am_a_param);}); // the family modifier is used to pass a String value,// which is used to call the get() method.// The modifier "autoDispose" destroys the state of a provider // when it is no longer used, even when the widget state is not yet dispose
Complete Code:
Dart
class HomeScreen extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text("FutureProvider Demo"),), body: SafeArea( child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Consumer( builder: (context, watch, child) { final futureData = watch(providers.response); return futureData.map( data: (data) => Text( '${data.value}', ), // have data loading: (_) => Column( children: [ CircularProgressIndicator(), Text( 'Fetching data', ), ], ), // in progress error: (message) => Text(message.error.toString()), // has an error ); }, ), ], ), ), ), ), ); }}
Output:
We often use streams in a flutter application, be it fetching data from Firestore or reading data from a file. Let’s learn how we can handle those streams with Riverpod.
Let’s declare a stream first,
final streamProvider = StreamProvider<int>((ref) {
return Stream.fromIterable([105, 50]);
//in production this could be a stream of documents from Firestore
});
This time, let’s use ConsumerWidget() to consume StreamProvider’s data, it is fairly similar to that of FutureProvider.
Dart
class HomeScreen extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text("StreamProvider Demo"), ), body: SafeArea( child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Consumer( builder: (context, watch, child) { final streamValue = watch(providers.streamProvider); return streamValue.when( data: (data) => Text( '${data}', ), // have data loading: () => Column( children: [ CircularProgressIndicator(), Text( 'Fetching data', ), ], ), // in progress error: (message, e) => Text(message.toString()), // has an error ); }, ), ], ), ), ), ), ); }}
Now, every time the stream has new data, our UI will update accordingly.
Notice how we didn’t have to manage different states by ourselves, without Riverpod, the above code would look something like this:
Dart
final stream = Stream.fromIterable([105, 50]); StreamBuilder<int>( stream: stream, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.active) { if (snapshot.hasData) { // data return SomeWidget(snapshot.data); } else if (snapshot.hasError) { // error state return SomeErrorWidget(snapshot.error); } else { // no data return Text('No data'); } } else { // loading state return CircularProgressIndicator(); } })
That’s it. This should cover almost everything we need to learn to get started with Riverpod .
The complete code for the article above can be found here.
Flutter
Android
Dart
Flutter
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Retrofit with Kotlin Coroutine in Android
Android Listview in Java with Example
How to Change the Background Color After Clicking the Button in Android?
Listview.builder in Flutter
Flutter - DropDownButton Widget
Flutter - Asset Image
Flutter - Custom Bottom Navigation Bar
Splash Screen in Flutter
|
[
{
"code": null,
"e": 25116,
"s": 25088,
"text": "\n07 Sep, 2021"
},
{
"code": null,
"e": 25496,
"s": 25116,
"text": "Riverpod is a Reactive State-Management and Dependency Injection framework, it uses different providers to let us access and listen to state changes across our app, it is built by Remi Rousselet. If you don’t know what is state then I’ll recommend you to read this article first as it will be a little hard for you to understand Riverpod without understanding the “state” itself."
},
{
"code": null,
"e": 25774,
"s": 25496,
"text": "Riverpod is a state management helper. It basically makes our state (in clear words, our variables’ values) accessible in all parts of the app, it puts our state at the top of the widget tree and lets us listen to those state changes and update our User Interface accordingly. "
},
{
"code": null,
"e": 25862,
"s": 25774,
"text": "There are many types of providers which Riverpod offers, We’ll go over them one by one."
},
{
"code": null,
"e": 26024,
"s": 25862,
"text": "Providers are the most important part of a Riverpod application, “A provider is an object that encapsulates a piece of state and allows listening to that state.”"
},
{
"code": null,
"e": 26044,
"s": 26024,
"text": "Types of Providers:"
},
{
"code": null,
"e": 26058,
"s": 26044,
"text": "StateProvider"
},
{
"code": null,
"e": 26073,
"s": 26058,
"text": "FutureProvider"
},
{
"code": null,
"e": 26088,
"s": 26073,
"text": "StreamProvider"
},
{
"code": null,
"e": 26097,
"s": 26088,
"text": "Provider"
},
{
"code": null,
"e": 26119,
"s": 26097,
"text": "Let’s start building!"
},
{
"code": null,
"e": 26124,
"s": 26119,
"text": "Dart"
},
{
"code": "dependencies: flutter_riverpod: ^0.14.0+3",
"e": 26167,
"s": 26124,
"text": null
},
{
"code": null,
"e": 26257,
"s": 26167,
"text": "For providers to work, we must add ProviderScope at the root of our Flutter applications:"
},
{
"code": null,
"e": 26262,
"s": 26257,
"text": "Dart"
},
{
"code": "import 'package:flutter_riverpod/flutter_riverpod.dart';void main() { runApp(ProviderScope(child: MyApp()));}",
"e": 26373,
"s": 26262,
"text": null
},
{
"code": null,
"e": 26500,
"s": 26373,
"text": "We’ll define all our global providers in this file so that it is easier to maintain the project. Let’s define a StateProvider."
},
{
"code": null,
"e": 26505,
"s": 26500,
"text": "Dart"
},
{
"code": "import 'package:flutter_riverpod/flutter_riverpod.dart'; // Instead of String you can use other data types as well,// we can also use custom data types.final userNameProvider=StateProvider<String>((ref) { // we can also return an empty String here, for the sake of simplicity, // let's return a sample name return \"SomeName\";});",
"e": 26844,
"s": 26505,
"text": null
},
{
"code": null,
"e": 27036,
"s": 26844,
"text": "Now that we’ve declared a StateProvider, Let’s learn how can we read providers. To read any provider, we have multiple widgets, in this article, we’ll go over ConsumerWidget() and Consumer()."
},
{
"code": null,
"e": 27062,
"s": 27036,
"text": "Using a ConsumerWidget():"
},
{
"code": null,
"e": 27237,
"s": 27062,
"text": "A consumer widget is a widget that we can use in place of our Stateful/Stateless widget. It gives us the ability to read/change the states of providers & also listen to them."
},
{
"code": null,
"e": 27242,
"s": 27237,
"text": "Dart"
},
{
"code": "import 'Providers/providers.dart' as providers.dart; //for easy accessimport 'package:flutter_riverpod/flutter_riverpod.dart'; class Home extends ConsumerWidget { @override Widget build(BuildContext context, ScopedReader watch) { // Listens to the value exposed by userNameProvider // \".state\" method lets us get the state easily & directly String name = watch(providers.userNameProvider).state; return MaterialApp( home: Scaffold( appBar: AppBar(title: Center(child: const Text('GFG '))), body: Center( // displaying the value child: Text('$name'), ), ), ); }}",
"e": 27901,
"s": 27242,
"text": null
},
{
"code": null,
"e": 27909,
"s": 27901,
"text": "Output:"
},
{
"code": null,
"e": 28079,
"s": 27909,
"text": "Well and good. So now, whenever the value of userNameProvider changes, the Text() will be updated accordingly. But how are we gonna update the value of userNameProvider?"
},
{
"code": null,
"e": 28164,
"s": 28079,
"text": "To change the value of StateProvider, we need a StateController. So let’s create it."
},
{
"code": null,
"e": 28207,
"s": 28164,
"text": "First, let’s remove the variable “name”. ̶"
},
{
"code": null,
"e": 28573,
"s": 28207,
"text": "S̶t̶r̶i̶n̶g̶ ̶n̶a̶m̶e̶ ̶=̶ ̶w̶a̶t̶c̶h̶(̶p̶r̶o̶v̶i̶d̶e̶r̶s̶.̶u̶s̶e̶r̶N̶a̶m̶e̶P̶r̶o̶v̶i̶d̶e̶r̶)̶.̶s̶t̶a̶t̶e̶;̶\n\n//removed as with it we can only listen/get the state not change/mutate the state.\n\n//let's use this StateController instead.\n\nStateController<String> nameController = watch(providers.userNameProvider);\n\n// now we can get / set the state using name.state."
},
{
"code": null,
"e": 28707,
"s": 28573,
"text": "For the sake of simplicity, let’s use a FloatingActionButton, and using it let’s try to mutate(change) the state of userNameProvider."
},
{
"code": null,
"e": 28712,
"s": 28707,
"text": "Dart"
},
{
"code": "// for easy accessimport 'Providers/providers.dart' as providers.dart; class Home extends ConsumerWidget { int n = 0; @override Widget build(BuildContext context, ScopedReader watch) { // Listens to the value exposed by userNameProvider StateController<String> nameController = watch(providers.userNameProvider); // \".state\" method lets us get the state easily & directly return MaterialApp( home: Scaffold( floatingActionButton: FloatingActionButton( onPressed: () { n++; nameController.state = // now we can set the state using the state setter. \"New Name $n\"; }, ), appBar: AppBar(title: Center(child: const Text('GFG '))), body: Center( child: Text( // displaying the value '${nameController.state}', ), ), ), ); }}",
"e": 29648,
"s": 28712,
"text": null
},
{
"code": null,
"e": 29656,
"s": 29648,
"text": "Output:"
},
{
"code": null,
"e": 29883,
"s": 29656,
"text": "Now, when we press on the FloatingActionButton(), we’ll see that the name changes every time with a different number. So that’s it. Using this information we can easily use StateProviders, mutate their values and listen to it."
},
{
"code": null,
"e": 29926,
"s": 29883,
"text": "Now, Let’s go over asynchronous providers."
},
{
"code": null,
"e": 30128,
"s": 29926,
"text": "When we work with asynchronous code we often use some Future based APIs, let’s look into how you can handle Future events using Riverpod. To demonstrate, we will create a method which returns a Future."
},
{
"code": null,
"e": 30133,
"s": 30128,
"text": "Dart"
},
{
"code": "class FutureClass { // in production, the below method could be any network call Future<int> getData(String para) async { await Future.delayed(Duration(seconds: 5)); return 25; }}",
"e": 30326,
"s": 30133,
"text": null
},
{
"code": null,
"e": 30363,
"s": 30326,
"text": "Creating a provider for FutureClass:"
},
{
"code": null,
"e": 30417,
"s": 30363,
"text": "final futureClass = Provider((ref) => FutureClass());"
},
{
"code": null,
"e": 30455,
"s": 30417,
"text": "Now, let’s create our FutureProvider,"
},
{
"code": null,
"e": 30460,
"s": 30455,
"text": "Dart"
},
{
"code": "final response = FutureProvider<int>((ref) async { final client = ref.read(futureClass); return client.getData('some text as a parameter');});",
"e": 30605,
"s": 30460,
"text": null
},
{
"code": null,
"e": 30698,
"s": 30605,
"text": "Now, we can use ConsumerWidget to listen to the state changes and update our UI accordingly."
},
{
"code": null,
"e": 30943,
"s": 30698,
"text": "Apart from the ConsumerWidget(), we also have a Consumer() widget. The difference is that while ConsumerWidget rebuilds the entire screen when state changes, Consumer() rebuilds only it’s child, making sure we don’t run into performance issues."
},
{
"code": null,
"e": 31007,
"s": 30943,
"text": "Let’s use Consumer() widget to watch(listen) for state changes."
},
{
"code": null,
"e": 31012,
"s": 31007,
"text": "Dart"
},
{
"code": "class HomeScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text(\"FutureProvider Demo\"),), body: Center( child: Column( children: [ Consumer( builder: (context, watch, child) { final futureData = watch(response); }, ), ], ), ), ); }}",
"e": 31446,
"s": 31012,
"text": null
},
{
"code": null,
"e": 31593,
"s": 31446,
"text": "As a Future can have 3 states, i.e, completed, in progress & error, we have the ability to handle those states separately using the .map function."
},
{
"code": null,
"e": 31598,
"s": 31593,
"text": "Dart"
},
{
"code": "Consumer( builder: (context, watch, child) { final futureData = watch(response); return futureData.map( ,// have data data: (data) => Text('${data.value}',) ,// in progress loading: (_) => CircularProgressIndicator() // has an error error: (message) => Text(message.error), ); },),",
"e": 31948,
"s": 31598,
"text": null
},
{
"code": null,
"e": 32043,
"s": 31948,
"text": "If we want to pass a variable/object to the provider as an argument, then we can do that like-"
},
{
"code": null,
"e": 32048,
"s": 32043,
"text": "Dart"
},
{
"code": "final response= FutureProvider.autoDispose.family<int, String>((ref, i_am_a_param) async { final client = ref.read(futureClass); return client.getData(i_am_a_param);}); // the family modifier is used to pass a String value,// which is used to call the get() method.// The modifier \"autoDispose\" destroys the state of a provider // when it is no longer used, even when the widget state is not yet dispose",
"e": 32458,
"s": 32048,
"text": null
},
{
"code": null,
"e": 32473,
"s": 32458,
"text": "Complete Code:"
},
{
"code": null,
"e": 32478,
"s": 32473,
"text": "Dart"
},
{
"code": "class HomeScreen extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text(\"FutureProvider Demo\"),), body: SafeArea( child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Consumer( builder: (context, watch, child) { final futureData = watch(providers.response); return futureData.map( data: (data) => Text( '${data.value}', ), // have data loading: (_) => Column( children: [ CircularProgressIndicator(), Text( 'Fetching data', ), ], ), // in progress error: (message) => Text(message.error.toString()), // has an error ); }, ), ], ), ), ), ), ); }}",
"e": 33703,
"s": 32478,
"text": null
},
{
"code": null,
"e": 33711,
"s": 33703,
"text": "Output:"
},
{
"code": null,
"e": 33881,
"s": 33711,
"text": "We often use streams in a flutter application, be it fetching data from Firestore or reading data from a file. Let’s learn how we can handle those streams with Riverpod."
},
{
"code": null,
"e": 33911,
"s": 33881,
"text": "Let’s declare a stream first,"
},
{
"code": null,
"e": 34076,
"s": 33911,
"text": "final streamProvider = StreamProvider<int>((ref) {\n return Stream.fromIterable([105, 50]);\n //in production this could be a stream of documents from Firestore\n});"
},
{
"code": null,
"e": 34196,
"s": 34076,
"text": "This time, let’s use ConsumerWidget() to consume StreamProvider’s data, it is fairly similar to that of FutureProvider."
},
{
"code": null,
"e": 34201,
"s": 34196,
"text": "Dart"
},
{
"code": "class HomeScreen extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text(\"StreamProvider Demo\"), ), body: SafeArea( child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Consumer( builder: (context, watch, child) { final streamValue = watch(providers.streamProvider); return streamValue.when( data: (data) => Text( '${data}', ), // have data loading: () => Column( children: [ CircularProgressIndicator(), Text( 'Fetching data', ), ], ), // in progress error: (message, e) => Text(message.toString()), // has an error ); }, ), ], ), ), ), ), ); }}",
"e": 35443,
"s": 34201,
"text": null
},
{
"code": null,
"e": 35516,
"s": 35443,
"text": "Now, every time the stream has new data, our UI will update accordingly."
},
{
"code": null,
"e": 35648,
"s": 35516,
"text": "Notice how we didn’t have to manage different states by ourselves, without Riverpod, the above code would look something like this:"
},
{
"code": null,
"e": 35653,
"s": 35648,
"text": "Dart"
},
{
"code": "final stream = Stream.fromIterable([105, 50]); StreamBuilder<int>( stream: stream, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.active) { if (snapshot.hasData) { // data return SomeWidget(snapshot.data); } else if (snapshot.hasError) { // error state return SomeErrorWidget(snapshot.error); } else { // no data return Text('No data'); } } else { // loading state return CircularProgressIndicator(); } })",
"e": 36218,
"s": 35653,
"text": null
},
{
"code": null,
"e": 36313,
"s": 36218,
"text": "That’s it. This should cover almost everything we need to learn to get started with Riverpod ."
},
{
"code": null,
"e": 36372,
"s": 36313,
"text": "The complete code for the article above can be found here."
},
{
"code": null,
"e": 36380,
"s": 36372,
"text": "Flutter"
},
{
"code": null,
"e": 36388,
"s": 36380,
"text": "Android"
},
{
"code": null,
"e": 36393,
"s": 36388,
"text": "Dart"
},
{
"code": null,
"e": 36401,
"s": 36393,
"text": "Flutter"
},
{
"code": null,
"e": 36409,
"s": 36401,
"text": "Android"
},
{
"code": null,
"e": 36507,
"s": 36409,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36546,
"s": 36507,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 36596,
"s": 36546,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 36638,
"s": 36596,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 36676,
"s": 36638,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 36749,
"s": 36676,
"text": "How to Change the Background Color After Clicking the Button in Android?"
},
{
"code": null,
"e": 36777,
"s": 36749,
"text": "Listview.builder in Flutter"
},
{
"code": null,
"e": 36809,
"s": 36777,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 36831,
"s": 36809,
"text": "Flutter - Asset Image"
},
{
"code": null,
"e": 36870,
"s": 36831,
"text": "Flutter - Custom Bottom Navigation Bar"
}
] |
Cryptocurrency Prediction with LSTM | by Soner Yıldırım | Towards Data Science
|
Although the first redistributed cryptocurrency (bitcoin) was created in 2009, the idea of digital money arised in 1980s. In the recent years, cryptocurrencies have gained tremendeous popularity. As traditional currencies, the value of cryptocurrencies are changing over time. Using the historical data, I will implement a recurrent neural netwok using LSTM (Long short-term memory) layers to predict the trend of cryptocurrency values in the future.
There is a huge dataset about cryptocurrency market prices on Kaggle. I will only use a part of it which is historical price data of litecoin.
As always, we start with importing the libraries:
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snssns.set(style="darkgrid", font_scale=1.5)%matplotlib inline
After importing the libraries, we can now get the data we need:
df = pd.read_csv("crypto-markets.csv", parse_dates=["date"], index_col="date")df.shape(942297, 12)df.head()
The dataset includes almost 1 million rows. I just need the “open” prince of “litecoin”.
df = df[df.slug == "litecoin"][["open"]]df.shape(2042, 1)
We now have the historical data of litecoin from April,2013 to November,2018. Let’s take a look at how it changed through time.
plt.figure(figsize=(12,6))sns.lineplot(x=df.index, y="open", data=df).set_title("Price of Litecoin")
It was in a long time silence following a small peak through the end 2013. Then reached its highest values at the end of 2017. We can make the graph look smoother by applying down-sampling.
df.resample('10D').mean().plot(figsize=(12,6))plt.figtext(.5,0.9,"Down-sampled to 10-day periods", fontsize=20, ha='center')
Long short-term memory (LSTM) is a type of recurrent neural network (RNN) and powerful to model sequence data because it maintains an internal state to keep track of the data it has already seen. Common applications of LSTMs include time series analysis and natural language processing.
LSTM requires the input to be a 3D tensor with shape (batch_size, timesteps, input_dim).
I will build a model that predicts the value of litecoin at time t using the past 90 values (from t-90 to t-1). Therefore the the number of timesteps is 90. I only use “open” price to make the prediction so the input_dim is 1. The target variable is “open” price of litecoin which can be effected by many other factors. For example, the value of another cryptocurrency may have an effect on litecoin. If we also use a second variable to make the prediction, than the input_dim will be 2.
I will re-organize the data in a way that a sequence of the values in previous 90 days is used to predict the value at time t. It is also better to normalize the values due to excessive computations done in a neural network.
data = df.iloc[:, 0]hist = []target = []length = 90for i in range(len(data)-length): x = data[i:i+length] y = data[i+length] hist.append(x) target.append(y)
The last timestep of the first element is same as the 90th timestep of the original data which is what we planned to do.
The second element of hist should be just one timestep shifted version of first element. Therefore, the last timestep in the second element should be equal to the first item of the target variable which is the 91st timestep in the original data.
Let’s double check to confirm:
print(hist[1][89])print(data[90])print(target[0])2.92.92.9
Hist and target are lists. We need to convert them to numpy arrays and reshape the target variable.
hist = np.array(hist)target = np.array(target)target = target.reshape(-1,1)
Let’s check the shapes of hist and target arrays:
hist.shape(1952, 90)target.shape(1952, 1)
Hist array include 1952 observations each of which includes 90 timesteps (90 days).
We can now normalize the data which is squeezing all data points in the range 0 to 1 in a way that the maximum value and minimum values will 1 and 0, respectively. Normalizing can be done by applying a simple math equation or just using a function like MinMaxScaler.
from sklearn.preprocessing import MinMaxScalersc = MinMaxScaler()hist_scaled = sc.fit_transform(hist)target_scaled = sc.fit_transform(target)
The final step of preprocessing is reshaping the input array to be compatible with LSTM layer.
hist_scaled = hist_scaled.reshape((len(hist_scaled), length, 1))print(hist_scaled.shape)(1952, 90, 1)
Our dataset includes 1951 samples (days). A sample of input consists of the value of litecoin for 90 consecutive days and target variable is the value of litecoin on the following day after the 90-day period.
I will split the dataset in a way that 1900 samples are used for training and then the model will be used to predict the trend in the following 51 days.
X_train = hist_scaled[:1900,:,:]X_test = hist_scaled[1900:,:,:]y_train = target_scaled[:1900,:]y_test = target_scaled[1900:,:]
import tensorflow as tffrom tensorflow.keras import layers
I will build a model with 3 LSTM layers and 1 dense layer which is the output layer.
model = tf.keras.Sequential()model.add(layers.LSTM(units=32, return_sequences=True, input_shape=(90,1), dropout=0.2))model.add(layers.LSTM(units=32, return_sequences=True, dropout=0.2))model.add(layers.LSTM(units=32, dropout=0.2))model.add(layers.Dense(units=1))model.summary()
We now need to compile the model. When compiling a model, an optimizer which is used to adjust the weights should be selected. Tensorflow offers many optimizers. Commonly used optimizers in regression tasks are “adam” and “rmsprop”. Also, a loss function should be selected. Since this is a regression task, we can select “mean_squared_error”.
model.compile(optimizer='adam', loss='mean_squared_error')
It is time to train the model. We need to specify two hyperparameters here:
batch_size= The number of samples to work through the neural network before updating the internal parameters of the model. If batch_size is 1, then the parameters are updated after each sample (or observation) is fed to the neural network.
epochs: The number of times the entire training set is passed through the neural network forward and backward.
history = model.fit(X_train, y_train, epochs=30, batch_size=32)
It seems like the model is converged in 30 epochs so there is no need to do additional epochs. The loss is less than 0.002 which I think is pretty good.
Let’s visualize how loss changes as number of epochs increases.
loss = history.history['loss']epoch_count = range(1, len(loss) + 1)plt.figure(figsize=(12,8))plt.plot(epoch_count, loss, 'r--')plt.legend(['Training Loss'])plt.xlabel('Epoch')plt.ylabel('Loss')plt.show();
It seems like the model has converged after 15 epochs. After that, the loss is bouncing up and down around 0.0018.
Now it is time to make predictions.
pred = model.predict(X_test)plt.figure(figsize=(12,8))plt.plot(y_test, color='blue', label='Real')plt.plot(pred, color='red', label='Prediction')plt.title('Litecoin Price Prediction')plt.legend()plt.show()
Our model achieved to determine the trend pretty well. As you may have noticed, the values are much less than the original values because we normalized the values before training the model. We can inverse transform to reflect the real prices but trend will be the same.
pred_transformed = sc.inverse_transform(pred)y_test_transformed = sc.inverse_transform(y_test)
There is always space for improvement. The fuel of a neural network is data so we can build a more robust and accurate model by collecting more data. We can also try to adjust number of nodes in a layer or add additional LSTM layers. We can also try to increase the number of timesteps which was 90 in our model. Another way to improve is to adjust parameters using GridSearchCV.
Please keep in mind that it is not always good to increase the model accuracy because we may end up having an overfit model.
You can get the entire jupyter notebook here.
Thanks for reading. Please let me know if you have any feedback.
|
[
{
"code": null,
"e": 498,
"s": 47,
"text": "Although the first redistributed cryptocurrency (bitcoin) was created in 2009, the idea of digital money arised in 1980s. In the recent years, cryptocurrencies have gained tremendeous popularity. As traditional currencies, the value of cryptocurrencies are changing over time. Using the historical data, I will implement a recurrent neural netwok using LSTM (Long short-term memory) layers to predict the trend of cryptocurrency values in the future."
},
{
"code": null,
"e": 641,
"s": 498,
"text": "There is a huge dataset about cryptocurrency market prices on Kaggle. I will only use a part of it which is historical price data of litecoin."
},
{
"code": null,
"e": 691,
"s": 641,
"text": "As always, we start with importing the libraries:"
},
{
"code": null,
"e": 840,
"s": 691,
"text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snssns.set(style=\"darkgrid\", font_scale=1.5)%matplotlib inline"
},
{
"code": null,
"e": 904,
"s": 840,
"text": "After importing the libraries, we can now get the data we need:"
},
{
"code": null,
"e": 1012,
"s": 904,
"text": "df = pd.read_csv(\"crypto-markets.csv\", parse_dates=[\"date\"], index_col=\"date\")df.shape(942297, 12)df.head()"
},
{
"code": null,
"e": 1101,
"s": 1012,
"text": "The dataset includes almost 1 million rows. I just need the “open” prince of “litecoin”."
},
{
"code": null,
"e": 1159,
"s": 1101,
"text": "df = df[df.slug == \"litecoin\"][[\"open\"]]df.shape(2042, 1)"
},
{
"code": null,
"e": 1287,
"s": 1159,
"text": "We now have the historical data of litecoin from April,2013 to November,2018. Let’s take a look at how it changed through time."
},
{
"code": null,
"e": 1388,
"s": 1287,
"text": "plt.figure(figsize=(12,6))sns.lineplot(x=df.index, y=\"open\", data=df).set_title(\"Price of Litecoin\")"
},
{
"code": null,
"e": 1578,
"s": 1388,
"text": "It was in a long time silence following a small peak through the end 2013. Then reached its highest values at the end of 2017. We can make the graph look smoother by applying down-sampling."
},
{
"code": null,
"e": 1703,
"s": 1578,
"text": "df.resample('10D').mean().plot(figsize=(12,6))plt.figtext(.5,0.9,\"Down-sampled to 10-day periods\", fontsize=20, ha='center')"
},
{
"code": null,
"e": 1990,
"s": 1703,
"text": "Long short-term memory (LSTM) is a type of recurrent neural network (RNN) and powerful to model sequence data because it maintains an internal state to keep track of the data it has already seen. Common applications of LSTMs include time series analysis and natural language processing."
},
{
"code": null,
"e": 2079,
"s": 1990,
"text": "LSTM requires the input to be a 3D tensor with shape (batch_size, timesteps, input_dim)."
},
{
"code": null,
"e": 2567,
"s": 2079,
"text": "I will build a model that predicts the value of litecoin at time t using the past 90 values (from t-90 to t-1). Therefore the the number of timesteps is 90. I only use “open” price to make the prediction so the input_dim is 1. The target variable is “open” price of litecoin which can be effected by many other factors. For example, the value of another cryptocurrency may have an effect on litecoin. If we also use a second variable to make the prediction, than the input_dim will be 2."
},
{
"code": null,
"e": 2792,
"s": 2567,
"text": "I will re-organize the data in a way that a sequence of the values in previous 90 days is used to predict the value at time t. It is also better to normalize the values due to excessive computations done in a neural network."
},
{
"code": null,
"e": 2961,
"s": 2792,
"text": "data = df.iloc[:, 0]hist = []target = []length = 90for i in range(len(data)-length): x = data[i:i+length] y = data[i+length] hist.append(x) target.append(y)"
},
{
"code": null,
"e": 3082,
"s": 2961,
"text": "The last timestep of the first element is same as the 90th timestep of the original data which is what we planned to do."
},
{
"code": null,
"e": 3328,
"s": 3082,
"text": "The second element of hist should be just one timestep shifted version of first element. Therefore, the last timestep in the second element should be equal to the first item of the target variable which is the 91st timestep in the original data."
},
{
"code": null,
"e": 3359,
"s": 3328,
"text": "Let’s double check to confirm:"
},
{
"code": null,
"e": 3418,
"s": 3359,
"text": "print(hist[1][89])print(data[90])print(target[0])2.92.92.9"
},
{
"code": null,
"e": 3518,
"s": 3418,
"text": "Hist and target are lists. We need to convert them to numpy arrays and reshape the target variable."
},
{
"code": null,
"e": 3594,
"s": 3518,
"text": "hist = np.array(hist)target = np.array(target)target = target.reshape(-1,1)"
},
{
"code": null,
"e": 3644,
"s": 3594,
"text": "Let’s check the shapes of hist and target arrays:"
},
{
"code": null,
"e": 3686,
"s": 3644,
"text": "hist.shape(1952, 90)target.shape(1952, 1)"
},
{
"code": null,
"e": 3770,
"s": 3686,
"text": "Hist array include 1952 observations each of which includes 90 timesteps (90 days)."
},
{
"code": null,
"e": 4037,
"s": 3770,
"text": "We can now normalize the data which is squeezing all data points in the range 0 to 1 in a way that the maximum value and minimum values will 1 and 0, respectively. Normalizing can be done by applying a simple math equation or just using a function like MinMaxScaler."
},
{
"code": null,
"e": 4179,
"s": 4037,
"text": "from sklearn.preprocessing import MinMaxScalersc = MinMaxScaler()hist_scaled = sc.fit_transform(hist)target_scaled = sc.fit_transform(target)"
},
{
"code": null,
"e": 4274,
"s": 4179,
"text": "The final step of preprocessing is reshaping the input array to be compatible with LSTM layer."
},
{
"code": null,
"e": 4376,
"s": 4274,
"text": "hist_scaled = hist_scaled.reshape((len(hist_scaled), length, 1))print(hist_scaled.shape)(1952, 90, 1)"
},
{
"code": null,
"e": 4585,
"s": 4376,
"text": "Our dataset includes 1951 samples (days). A sample of input consists of the value of litecoin for 90 consecutive days and target variable is the value of litecoin on the following day after the 90-day period."
},
{
"code": null,
"e": 4738,
"s": 4585,
"text": "I will split the dataset in a way that 1900 samples are used for training and then the model will be used to predict the trend in the following 51 days."
},
{
"code": null,
"e": 4865,
"s": 4738,
"text": "X_train = hist_scaled[:1900,:,:]X_test = hist_scaled[1900:,:,:]y_train = target_scaled[:1900,:]y_test = target_scaled[1900:,:]"
},
{
"code": null,
"e": 4924,
"s": 4865,
"text": "import tensorflow as tffrom tensorflow.keras import layers"
},
{
"code": null,
"e": 5009,
"s": 4924,
"text": "I will build a model with 3 LSTM layers and 1 dense layer which is the output layer."
},
{
"code": null,
"e": 5321,
"s": 5009,
"text": "model = tf.keras.Sequential()model.add(layers.LSTM(units=32, return_sequences=True, input_shape=(90,1), dropout=0.2))model.add(layers.LSTM(units=32, return_sequences=True, dropout=0.2))model.add(layers.LSTM(units=32, dropout=0.2))model.add(layers.Dense(units=1))model.summary()"
},
{
"code": null,
"e": 5665,
"s": 5321,
"text": "We now need to compile the model. When compiling a model, an optimizer which is used to adjust the weights should be selected. Tensorflow offers many optimizers. Commonly used optimizers in regression tasks are “adam” and “rmsprop”. Also, a loss function should be selected. Since this is a regression task, we can select “mean_squared_error”."
},
{
"code": null,
"e": 5724,
"s": 5665,
"text": "model.compile(optimizer='adam', loss='mean_squared_error')"
},
{
"code": null,
"e": 5800,
"s": 5724,
"text": "It is time to train the model. We need to specify two hyperparameters here:"
},
{
"code": null,
"e": 6040,
"s": 5800,
"text": "batch_size= The number of samples to work through the neural network before updating the internal parameters of the model. If batch_size is 1, then the parameters are updated after each sample (or observation) is fed to the neural network."
},
{
"code": null,
"e": 6151,
"s": 6040,
"text": "epochs: The number of times the entire training set is passed through the neural network forward and backward."
},
{
"code": null,
"e": 6215,
"s": 6151,
"text": "history = model.fit(X_train, y_train, epochs=30, batch_size=32)"
},
{
"code": null,
"e": 6368,
"s": 6215,
"text": "It seems like the model is converged in 30 epochs so there is no need to do additional epochs. The loss is less than 0.002 which I think is pretty good."
},
{
"code": null,
"e": 6432,
"s": 6368,
"text": "Let’s visualize how loss changes as number of epochs increases."
},
{
"code": null,
"e": 6637,
"s": 6432,
"text": "loss = history.history['loss']epoch_count = range(1, len(loss) + 1)plt.figure(figsize=(12,8))plt.plot(epoch_count, loss, 'r--')plt.legend(['Training Loss'])plt.xlabel('Epoch')plt.ylabel('Loss')plt.show();"
},
{
"code": null,
"e": 6752,
"s": 6637,
"text": "It seems like the model has converged after 15 epochs. After that, the loss is bouncing up and down around 0.0018."
},
{
"code": null,
"e": 6788,
"s": 6752,
"text": "Now it is time to make predictions."
},
{
"code": null,
"e": 6994,
"s": 6788,
"text": "pred = model.predict(X_test)plt.figure(figsize=(12,8))plt.plot(y_test, color='blue', label='Real')plt.plot(pred, color='red', label='Prediction')plt.title('Litecoin Price Prediction')plt.legend()plt.show()"
},
{
"code": null,
"e": 7264,
"s": 6994,
"text": "Our model achieved to determine the trend pretty well. As you may have noticed, the values are much less than the original values because we normalized the values before training the model. We can inverse transform to reflect the real prices but trend will be the same."
},
{
"code": null,
"e": 7359,
"s": 7264,
"text": "pred_transformed = sc.inverse_transform(pred)y_test_transformed = sc.inverse_transform(y_test)"
},
{
"code": null,
"e": 7739,
"s": 7359,
"text": "There is always space for improvement. The fuel of a neural network is data so we can build a more robust and accurate model by collecting more data. We can also try to adjust number of nodes in a layer or add additional LSTM layers. We can also try to increase the number of timesteps which was 90 in our model. Another way to improve is to adjust parameters using GridSearchCV."
},
{
"code": null,
"e": 7864,
"s": 7739,
"text": "Please keep in mind that it is not always good to increase the model accuracy because we may end up having an overfit model."
},
{
"code": null,
"e": 7910,
"s": 7864,
"text": "You can get the entire jupyter notebook here."
}
] |
LISP - Macros
|
Macros allow you to extend the syntax of standard LISP.
Technically, a macro is a function that takes an s-expression as arguments and returns a LISP form, which is then evaluated.
In LISP, a named macro is defined using another macro named defmacro. Syntax for defining a macro is −
(defmacro macro-name (parameter-list))
"Optional documentation string."
body-form
The macro definition consists of the name of the macro, a parameter list, an optional documentation string, and a body of Lisp expressions that defines the job to be performed by the macro.
Let us write a simple macro named setTo10, which will take a number and set its value to 10.
Create new source code file named main.lisp and type the following code in it.
(defmacro setTo10(num)
(setq num 10)(print num))
(setq x 25)
(print x)
(setTo10 x)
When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −
25
10
79 Lectures
7 hours
Arnold Higuit
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2116,
"s": 2060,
"text": "Macros allow you to extend the syntax of standard LISP."
},
{
"code": null,
"e": 2241,
"s": 2116,
"text": "Technically, a macro is a function that takes an s-expression as arguments and returns a LISP form, which is then evaluated."
},
{
"code": null,
"e": 2344,
"s": 2241,
"text": "In LISP, a named macro is defined using another macro named defmacro. Syntax for defining a macro is −"
},
{
"code": null,
"e": 2426,
"s": 2344,
"text": "(defmacro macro-name (parameter-list))\n\"Optional documentation string.\"\nbody-form"
},
{
"code": null,
"e": 2616,
"s": 2426,
"text": "The macro definition consists of the name of the macro, a parameter list, an optional documentation string, and a body of Lisp expressions that defines the job to be performed by the macro."
},
{
"code": null,
"e": 2709,
"s": 2616,
"text": "Let us write a simple macro named setTo10, which will take a number and set its value to 10."
},
{
"code": null,
"e": 2788,
"s": 2709,
"text": "Create new source code file named main.lisp and type the following code in it."
},
{
"code": null,
"e": 2871,
"s": 2788,
"text": "(defmacro setTo10(num)\n(setq num 10)(print num))\n(setq x 25)\n(print x)\n(setTo10 x)"
},
{
"code": null,
"e": 2980,
"s": 2871,
"text": "When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −"
},
{
"code": null,
"e": 2987,
"s": 2980,
"text": "25\n10\n"
},
{
"code": null,
"e": 3020,
"s": 2987,
"text": "\n 79 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3035,
"s": 3020,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 3042,
"s": 3035,
"text": " Print"
},
{
"code": null,
"e": 3053,
"s": 3042,
"text": " Add Notes"
}
] |
C Program for Maximum circular subarray sum - GeeksforGeeks
|
21 Dec, 2021
Given n numbers (both +ve and -ve), arranged in a circle, find the maximum sum of consecutive numbers.
Examples:
Input: a[] = {8, -8, 9, -9, 10, -11, 12}
Output: 22 (12 + 8 - 8 + 9 - 9 + 10)
Input: a[] = {10, -3, -4, 7, 6, 5, -4, -1}
Output: 23 (7 + 6 + 5 - 4 -1 + 10)
Input: a[] = {-1, 40, -14, 7, 6, 5, -4, -1}
Output: 52 (7 + 6 + 5 - 4 - 1 - 1 + 40)
Approach: There can be two cases for the maximum sum:
Case 1: The elements that contribute to the maximum sum are arranged such that no wrapping is there. Examples: {-10, 2, -1, 5}, {-2, 4, -1, 4, -1}. In this case, Kadane’s algorithm will produce the result.
Case 2: The elements which contribute to the maximum sum are arranged such that wrapping is there. Examples: {10, -12, 11}, {12, -5, 4, -8, 11}. In this case, we change wrapping to non-wrapping. Let us see how. Wrapping of contributing elements implies non-wrapping of non-contributing elements, so find out the sum of non-contributing elements and subtract this sum from the total sum. To find out the sum of non-contributions, invert the sign of each element and then run Kadane’s algorithm. Our array is like a ring and we have to eliminate the maximum continuous negative that implies maximum continuous positive in the inverted arrays. Finally, we compare the sum obtained in both cases and return the maximum of the two sums.
Thanks to ashishdey0 for suggesting this solution.
The following are implementations of the above method.
C
// C program for maximum contiguous circular sum problem#include <stdio.h> // Standard Kadane's algorithm to find maximum subarray// sumint kadane(int a[], int n); // The function returns maximum circular contiguous sum// in a[]int maxCircularSum(int a[], int n){ // Case 1: get the maximum sum using standard kadane' // s algorithm int max_kadane = kadane(a, n); // Case 2: Now find the maximum sum that includes // corner elements. int max_wrap = 0, i; for (i = 0; i < n; i++) { max_wrap += a[i]; // Calculate array-sum a[i] = -a[i]; // invert the array (change sign) } // max sum with corner elements will be: // array-sum - (-max subarray sum of inverted array) max_wrap = max_wrap + kadane(a, n); // The maximum circular sum will be maximum of two sums return (max_wrap > max_kadane) ? max_wrap : max_kadane;} // Standard Kadane's algorithm to find maximum subarray sum// See https:// www.geeksforgeeks.org/archives/576 for detailsint kadane(int a[], int n){ int max_so_far = 0, max_ending_here = 0; int i; for (i = 0; i < n; i++) { max_ending_here = max_ending_here + a[i]; if (max_ending_here < 0) max_ending_here = 0; if (max_so_far < max_ending_here) max_so_far = max_ending_here; } return max_so_far;} /* Driver program to test maxCircularSum() */int main(){ int a[] = { 11, 10, -20, 5, -3, -5, 8, -13, 10 }; int n = sizeof(a) / sizeof(a[0]); printf("Maximum circular sum is %dn", maxCircularSum(a, n)); return 0;}
Output:
Maximum circular sum is 31
Complexity Analysis:
Time Complexity: O(n), where n is the number of elements in the input array. As only linear traversal of the array is needed.
Auxiliary Space: O(1). As no extra space is required.
Note that the above algorithm doesn’t work if all numbers are negative, e.g., {-1, -2, -3}. It returns 0 in this case. This case can be handled by adding a pre-check to see if all the numbers are negative before running the above algorithm.
Please refer complete article on Maximum circular subarray sum for more details!
circular-array
subarray
subarray-sum
Arrays
C Language
C Programs
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to find sum of elements in a given array
Building Heap from Array
Window Sliding Technique
Reversal algorithm for array rotation
1's and 2's complement of a Binary Number
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
std::sort() in C++ STL
Bitwise Operators in C/C++
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
|
[
{
"code": null,
"e": 24405,
"s": 24377,
"text": "\n21 Dec, 2021"
},
{
"code": null,
"e": 24509,
"s": 24405,
"text": "Given n numbers (both +ve and -ve), arranged in a circle, find the maximum sum of consecutive numbers. "
},
{
"code": null,
"e": 24520,
"s": 24509,
"text": "Examples: "
},
{
"code": null,
"e": 24765,
"s": 24520,
"text": "Input: a[] = {8, -8, 9, -9, 10, -11, 12}\nOutput: 22 (12 + 8 - 8 + 9 - 9 + 10)\n\nInput: a[] = {10, -3, -4, 7, 6, 5, -4, -1} \nOutput: 23 (7 + 6 + 5 - 4 -1 + 10) \n\nInput: a[] = {-1, 40, -14, 7, 6, 5, -4, -1}\nOutput: 52 (7 + 6 + 5 - 4 - 1 - 1 + 40)"
},
{
"code": null,
"e": 24821,
"s": 24765,
"text": "Approach: There can be two cases for the maximum sum: "
},
{
"code": null,
"e": 25027,
"s": 24821,
"text": "Case 1: The elements that contribute to the maximum sum are arranged such that no wrapping is there. Examples: {-10, 2, -1, 5}, {-2, 4, -1, 4, -1}. In this case, Kadane’s algorithm will produce the result."
},
{
"code": null,
"e": 25759,
"s": 25027,
"text": "Case 2: The elements which contribute to the maximum sum are arranged such that wrapping is there. Examples: {10, -12, 11}, {12, -5, 4, -8, 11}. In this case, we change wrapping to non-wrapping. Let us see how. Wrapping of contributing elements implies non-wrapping of non-contributing elements, so find out the sum of non-contributing elements and subtract this sum from the total sum. To find out the sum of non-contributions, invert the sign of each element and then run Kadane’s algorithm. Our array is like a ring and we have to eliminate the maximum continuous negative that implies maximum continuous positive in the inverted arrays. Finally, we compare the sum obtained in both cases and return the maximum of the two sums."
},
{
"code": null,
"e": 25811,
"s": 25759,
"text": "Thanks to ashishdey0 for suggesting this solution. "
},
{
"code": null,
"e": 25867,
"s": 25811,
"text": "The following are implementations of the above method. "
},
{
"code": null,
"e": 25869,
"s": 25867,
"text": "C"
},
{
"code": "// C program for maximum contiguous circular sum problem#include <stdio.h> // Standard Kadane's algorithm to find maximum subarray// sumint kadane(int a[], int n); // The function returns maximum circular contiguous sum// in a[]int maxCircularSum(int a[], int n){ // Case 1: get the maximum sum using standard kadane' // s algorithm int max_kadane = kadane(a, n); // Case 2: Now find the maximum sum that includes // corner elements. int max_wrap = 0, i; for (i = 0; i < n; i++) { max_wrap += a[i]; // Calculate array-sum a[i] = -a[i]; // invert the array (change sign) } // max sum with corner elements will be: // array-sum - (-max subarray sum of inverted array) max_wrap = max_wrap + kadane(a, n); // The maximum circular sum will be maximum of two sums return (max_wrap > max_kadane) ? max_wrap : max_kadane;} // Standard Kadane's algorithm to find maximum subarray sum// See https:// www.geeksforgeeks.org/archives/576 for detailsint kadane(int a[], int n){ int max_so_far = 0, max_ending_here = 0; int i; for (i = 0; i < n; i++) { max_ending_here = max_ending_here + a[i]; if (max_ending_here < 0) max_ending_here = 0; if (max_so_far < max_ending_here) max_so_far = max_ending_here; } return max_so_far;} /* Driver program to test maxCircularSum() */int main(){ int a[] = { 11, 10, -20, 5, -3, -5, 8, -13, 10 }; int n = sizeof(a) / sizeof(a[0]); printf(\"Maximum circular sum is %dn\", maxCircularSum(a, n)); return 0;}",
"e": 27437,
"s": 25869,
"text": null
},
{
"code": null,
"e": 27446,
"s": 27437,
"text": "Output: "
},
{
"code": null,
"e": 27473,
"s": 27446,
"text": "Maximum circular sum is 31"
},
{
"code": null,
"e": 27496,
"s": 27473,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 27622,
"s": 27496,
"text": "Time Complexity: O(n), where n is the number of elements in the input array. As only linear traversal of the array is needed."
},
{
"code": null,
"e": 27676,
"s": 27622,
"text": "Auxiliary Space: O(1). As no extra space is required."
},
{
"code": null,
"e": 27917,
"s": 27676,
"text": "Note that the above algorithm doesn’t work if all numbers are negative, e.g., {-1, -2, -3}. It returns 0 in this case. This case can be handled by adding a pre-check to see if all the numbers are negative before running the above algorithm."
},
{
"code": null,
"e": 27998,
"s": 27917,
"text": "Please refer complete article on Maximum circular subarray sum for more details!"
},
{
"code": null,
"e": 28013,
"s": 27998,
"text": "circular-array"
},
{
"code": null,
"e": 28022,
"s": 28013,
"text": "subarray"
},
{
"code": null,
"e": 28035,
"s": 28022,
"text": "subarray-sum"
},
{
"code": null,
"e": 28042,
"s": 28035,
"text": "Arrays"
},
{
"code": null,
"e": 28053,
"s": 28042,
"text": "C Language"
},
{
"code": null,
"e": 28064,
"s": 28053,
"text": "C Programs"
},
{
"code": null,
"e": 28071,
"s": 28064,
"text": "Arrays"
},
{
"code": null,
"e": 28169,
"s": 28071,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28178,
"s": 28169,
"text": "Comments"
},
{
"code": null,
"e": 28191,
"s": 28178,
"text": "Old Comments"
},
{
"code": null,
"e": 28240,
"s": 28191,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 28265,
"s": 28240,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 28290,
"s": 28265,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 28328,
"s": 28290,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 28370,
"s": 28328,
"text": "1's and 2's complement of a Binary Number"
},
{
"code": null,
"e": 28448,
"s": 28370,
"text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()"
},
{
"code": null,
"e": 28471,
"s": 28448,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 28498,
"s": 28471,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 28533,
"s": 28498,
"text": "Multidimensional Arrays in C / C++"
}
] |
Const cast in C++
|
Given the task is to show the working of const_cast in C++.
const_cast is one of the type casting operators. It is used to change the constant value of any object or we can say it is used to remove the constant nature of any object.
const_cast can be used in programs that have any object with some constant value which need to be changed occasionally at some point.
The syntax is as follows −
const_cast<type name>(expression)
Input: x = 50
const int* y = &x
cout<<"old value is"<<*y<<"\n";
int* z=const_cast<int *>(y);
*z=100;
cout<<"new value is"<<*y;
Output: old value is 50
new value is 100
Following example shows the basic use of const_cast. Here we have declared a constant variable ”x” of type int which has been assigned a value of 50 and another constant pointer “y” of type int which points at the variable “x”.
A third pointer has to be created to use const_cast, and here we have created pointer ”z” of the same data type, that is, int.
So when we pass our constant pointer “y”, that points at constant variable “x” into const_cast, and assign a value to the pointer z, we are able to make changes to the value of our constant pointer “y”.
This way we were able to change the constant value from 50 to 100 using const_cast.
If we try to change the value of “x” that the pointer “y” is pointing at without using const_cast , then the following error will be shown-“assignment of read-only location”
Approach used in the below program as follows −
First create a constant variable of type int and give it some suitable size, let’s say “a” and its value be 20.
Then create a constant pointer, let us say “b” of the same data type and allocate it the address of our constant variable “a”.
Then create a third pointer, let us say “c” of data type int to be used for const_cast.
Now pass our constant pointer “b” into const_cast and keep it equal to our pointer “c”.
Finally make changes in the value of our pointer “c”. This will automatically make changes in the value at which our constant pointer “b” is pointing.
Start
Step 1 -> In function main()
Declare a constant int a=20
Declare a constant pointer int* b=&a
Declare a pointer int*c = const_cast<int *>(b)
Assign *c=40
Stop
Live Demo
#include <iostream>
using namespace std;
int main() {
const int a = 20;
const int* b = &a;
cout<<"old value is"<<*b<<"\n";
int* c=const_cast<int *>(b);
*c=40;
cout<<"new value is"<<*b;
return 0;
}
If we run the above code it will generate the following output −
old value is 20
new value is 40
Here, the constant pointer “b” is pointed at the constant variable “a” with value=20 which is unchangeable. But by creating a third non-constant pointer “c” of the same data type and using const_cast we are able to change that constant value.
The change of value of pointer “c” resulted in the change of the constant value 20 at which the constant pointer “b” was pointing. Therefore before using const_cast the output value was 20 and after using it the output value was 40.
In any program, const_cast can be used to pass constant data to another function that does not accept constant data.
#include <iostream>
using namespace std;
int change(int* p2) {
return (*p2 * 10);
}
int main() {
const int num = 100;
const int *p = #
int *p1 = const_cast <int *>(p);
cout << change(p1);
return 0;
}
If we run the above code it will generate the following output −
1000
The following program shows how we are able to pass a constant value of 100 using const_cast into the function change() that does not receive any constant data.
The change() function receives the value and multiplies it by 10 and returns it back to the main() function that generates the final output, that is, 1000.
If we run the same program without const_cast and try to pass the constant value directly into the change() function, it will show errors.
|
[
{
"code": null,
"e": 1122,
"s": 1062,
"text": "Given the task is to show the working of const_cast in C++."
},
{
"code": null,
"e": 1295,
"s": 1122,
"text": "const_cast is one of the type casting operators. It is used to change the constant value of any object or we can say it is used to remove the constant nature of any object."
},
{
"code": null,
"e": 1429,
"s": 1295,
"text": "const_cast can be used in programs that have any object with some constant value which need to be changed occasionally at some point."
},
{
"code": null,
"e": 1456,
"s": 1429,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 1490,
"s": 1456,
"text": "const_cast<type name>(expression)"
},
{
"code": null,
"e": 1658,
"s": 1490,
"text": "Input: x = 50\nconst int* y = &x\ncout<<\"old value is\"<<*y<<\"\\n\";\nint* z=const_cast<int *>(y);\n*z=100;\ncout<<\"new value is\"<<*y;\nOutput: old value is 50\nnew value is 100"
},
{
"code": null,
"e": 1886,
"s": 1658,
"text": "Following example shows the basic use of const_cast. Here we have declared a constant variable ”x” of type int which has been assigned a value of 50 and another constant pointer “y” of type int which points at the variable “x”."
},
{
"code": null,
"e": 2013,
"s": 1886,
"text": "A third pointer has to be created to use const_cast, and here we have created pointer ”z” of the same data type, that is, int."
},
{
"code": null,
"e": 2216,
"s": 2013,
"text": "So when we pass our constant pointer “y”, that points at constant variable “x” into const_cast, and assign a value to the pointer z, we are able to make changes to the value of our constant pointer “y”."
},
{
"code": null,
"e": 2300,
"s": 2216,
"text": "This way we were able to change the constant value from 50 to 100 using const_cast."
},
{
"code": null,
"e": 2474,
"s": 2300,
"text": "If we try to change the value of “x” that the pointer “y” is pointing at without using const_cast , then the following error will be shown-“assignment of read-only location”"
},
{
"code": null,
"e": 2522,
"s": 2474,
"text": "Approach used in the below program as follows −"
},
{
"code": null,
"e": 2634,
"s": 2522,
"text": "First create a constant variable of type int and give it some suitable size, let’s say “a” and its value be 20."
},
{
"code": null,
"e": 2761,
"s": 2634,
"text": "Then create a constant pointer, let us say “b” of the same data type and allocate it the address of our constant variable “a”."
},
{
"code": null,
"e": 2849,
"s": 2761,
"text": "Then create a third pointer, let us say “c” of data type int to be used for const_cast."
},
{
"code": null,
"e": 2937,
"s": 2849,
"text": "Now pass our constant pointer “b” into const_cast and keep it equal to our pointer “c”."
},
{
"code": null,
"e": 3088,
"s": 2937,
"text": "Finally make changes in the value of our pointer “c”. This will automatically make changes in the value at which our constant pointer “b” is pointing."
},
{
"code": null,
"e": 3265,
"s": 3088,
"text": "Start\nStep 1 -> In function main()\n Declare a constant int a=20\n Declare a constant pointer int* b=&a\n Declare a pointer int*c = const_cast<int *>(b)\n Assign *c=40\nStop"
},
{
"code": null,
"e": 3276,
"s": 3265,
"text": " Live Demo"
},
{
"code": null,
"e": 3494,
"s": 3276,
"text": "#include <iostream>\nusing namespace std;\nint main() {\n const int a = 20;\n const int* b = &a;\n cout<<\"old value is\"<<*b<<\"\\n\";\n int* c=const_cast<int *>(b);\n *c=40;\n cout<<\"new value is\"<<*b;\n return 0;\n}"
},
{
"code": null,
"e": 3559,
"s": 3494,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 3591,
"s": 3559,
"text": "old value is 20\nnew value is 40"
},
{
"code": null,
"e": 3834,
"s": 3591,
"text": "Here, the constant pointer “b” is pointed at the constant variable “a” with value=20 which is unchangeable. But by creating a third non-constant pointer “c” of the same data type and using const_cast we are able to change that constant value."
},
{
"code": null,
"e": 4067,
"s": 3834,
"text": "The change of value of pointer “c” resulted in the change of the constant value 20 at which the constant pointer “b” was pointing. Therefore before using const_cast the output value was 20 and after using it the output value was 40."
},
{
"code": null,
"e": 4184,
"s": 4067,
"text": "In any program, const_cast can be used to pass constant data to another function that does not accept constant data."
},
{
"code": null,
"e": 4402,
"s": 4184,
"text": "#include <iostream>\nusing namespace std;\nint change(int* p2) {\n return (*p2 * 10);\n}\nint main() {\n const int num = 100;\n const int *p = #\n int *p1 = const_cast <int *>(p);\n cout << change(p1);\n return 0;\n}"
},
{
"code": null,
"e": 4467,
"s": 4402,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 4472,
"s": 4467,
"text": "1000"
},
{
"code": null,
"e": 4633,
"s": 4472,
"text": "The following program shows how we are able to pass a constant value of 100 using const_cast into the function change() that does not receive any constant data."
},
{
"code": null,
"e": 4789,
"s": 4633,
"text": "The change() function receives the value and multiplies it by 10 and returns it back to the main() function that generates the final output, that is, 1000."
},
{
"code": null,
"e": 4928,
"s": 4789,
"text": "If we run the same program without const_cast and try to pass the constant value directly into the change() function, it will show errors."
}
] |
Easy Runtime Permissions in Android with Dexter - GeeksforGeeks
|
20 Jan, 2021
The runtime permission in Android which introduced in Marshmallow and due to these runtime permissions user can grant permission to the app in runtime, also while writing the code for runtime permissions. Sometimes handling the task of requesting permissions become so difficult and the developer has to write a huge amount of code. So we will see towards the implementation of Runtime permissions in Android using Dexter.
Dexter is the library that will help us to make this task easy for handling runtime permissions in Android. Now we will see the implementation of this in our Android app.
We will be building a simple application in which we will be showing a button to the user. After clicking on that button we will display runtime permissions to the user. So if the users deny the permission then we are showing the option to open the settings screen and grant the permissions. Below is the short video in which we will get to see what we are going to build in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add dependency of Dexter runtime permissions in build.gradle file
Navigate to gradle scripts and then to build.gradle(Module) level. Add below line in build.gradle file in the dependencies section.
implementation ‘com.karumi:dexter:6.2.2’
After adding this dependency now sync your project. Let’s move towards the XML part.
Step 3: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><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" android:orientation="vertical" tools:context=".MainActivity"> <!--Button to request permissions--> <Button android:id="@+id/idBtnRequestPermission" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Request Permission" android:textAllCaps="false" /> </RelativeLayout>
Step 4: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.Manifest;import android.app.AlertDialog;import android.content.DialogInterface;import android.content.Intent;import android.net.Uri;import android.os.Bundle;import android.provider.Settings;import android.view.View;import android.widget.Button;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.karumi.dexter.Dexter;import com.karumi.dexter.MultiplePermissionsReport;import com.karumi.dexter.PermissionToken;import com.karumi.dexter.listener.DexterError;import com.karumi.dexter.listener.PermissionRequest;import com.karumi.dexter.listener.PermissionRequestErrorListener;import com.karumi.dexter.listener.multi.MultiplePermissionsListener; import java.util.List; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our button and adding on click listener to it. Button requestPermissionsBtn = findViewById(R.id.idBtnRequestPermission); requestPermissionsBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // inside on click listener calling // method to request permission requestPermissions(); } }); } private void requestPermissions() { // below line is use to request // permission in the current activity. Dexter.withActivity(this) // below line is use to request the number of // permissions which are required in our app. .withPermissions(Manifest.permission.CAMERA, // below is the list of permissions Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_CONTACTS) // after adding permissions we are // calling an with listener method. .withListener(new MultiplePermissionsListener() { @Override public void onPermissionsChecked(MultiplePermissionsReport multiplePermissionsReport) { // this method is called when all permissions are granted if (multiplePermissionsReport.areAllPermissionsGranted()) { // do you work now Toast.makeText(MainActivity.this, "All the permissions are granted..", Toast.LENGTH_SHORT).show(); } // check for permanent denial of any permission if (multiplePermissionsReport.isAnyPermissionPermanentlyDenied()) { // permission is denied permanently, // we will show user a dialog message. showSettingsDialog(); } } @Override public void onPermissionRationaleShouldBeShown(List<PermissionRequest> list, PermissionToken permissionToken) { // this method is called when user grants some // permission and denies some of them. permissionToken.continuePermissionRequest(); } }).withErrorListener(new PermissionRequestErrorListener() { // this method is use to handle error // in runtime permissions @Override public void onError(DexterError error) { // we are displaying a toast message for error message. Toast.makeText(getApplicationContext(), "Error occurred! ", Toast.LENGTH_SHORT).show(); } }) // below line is use to run the permissions // on same thread and to check the permissions .onSameThread().check(); } // below is the shoe setting dialog // method which is use to display a // dialogue message. private void showSettingsDialog() { // we are displaying an alert dialog for permissions AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); // below line is the title // for our alert dialog. builder.setTitle("Need Permissions"); // below line is our message for our dialog builder.setMessage("This app needs permission to use this feature. You can grant them in app settings."); builder.setPositiveButton("GOTO SETTINGS", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // this method is called on click on positive // button and on clicking shit button we // are redirecting our user from our app to the // settings page of our app. dialog.cancel(); // below is the intent from which we // are redirecting our user. Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", getPackageName(), null); intent.setData(uri); startActivityForResult(intent, 101); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // this method is called when // user click on negative button. dialog.cancel(); } }); // below line is used // to display our dialog builder.show(); }}
Step 5: Adding the required permissions in the Manifest file
Navigate to the app > AndroidManifest.xml file and add the below permissions to it.
XML
<!-- Permissions we are requesting from user --><uses-permission android:name="android.permission.CAMERA"/><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/><uses-permission android:name="android.permission.READ_CONTACTS"/>
After adding these permissions in our AndroidManifest.xml file. Now run our app and see the output of the code.
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
Android Listview in Java with Example
How to Change the Background Color After Clicking the Button in Android?
How to Read Data from SQLite Database in Android?
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
|
[
{
"code": null,
"e": 25142,
"s": 25114,
"text": "\n20 Jan, 2021"
},
{
"code": null,
"e": 25566,
"s": 25142,
"text": "The runtime permission in Android which introduced in Marshmallow and due to these runtime permissions user can grant permission to the app in runtime, also while writing the code for runtime permissions. Sometimes handling the task of requesting permissions become so difficult and the developer has to write a huge amount of code. So we will see towards the implementation of Runtime permissions in Android using Dexter. "
},
{
"code": null,
"e": 25738,
"s": 25566,
"text": "Dexter is the library that will help us to make this task easy for handling runtime permissions in Android. Now we will see the implementation of this in our Android app. "
},
{
"code": null,
"e": 26202,
"s": 25738,
"text": "We will be building a simple application in which we will be showing a button to the user. After clicking on that button we will display runtime permissions to the user. So if the users deny the permission then we are showing the option to open the settings screen and grant the permissions. Below is the short video in which we will get to see what we are going to build in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 26231,
"s": 26202,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 26393,
"s": 26231,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 26467,
"s": 26393,
"text": "Step 2: Add dependency of Dexter runtime permissions in build.gradle file"
},
{
"code": null,
"e": 26599,
"s": 26467,
"text": "Navigate to gradle scripts and then to build.gradle(Module) level. Add below line in build.gradle file in the dependencies section."
},
{
"code": null,
"e": 26640,
"s": 26599,
"text": "implementation ‘com.karumi:dexter:6.2.2’"
},
{
"code": null,
"e": 26726,
"s": 26640,
"text": "After adding this dependency now sync your project. Let’s move towards the XML part. "
},
{
"code": null,
"e": 26774,
"s": 26726,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 26890,
"s": 26774,
"text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file."
},
{
"code": null,
"e": 26894,
"s": 26890,
"text": "XML"
},
{
"code": "<?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\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <!--Button to request permissions--> <Button android:id=\"@+id/idBtnRequestPermission\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:text=\"Request Permission\" android:textAllCaps=\"false\" /> </RelativeLayout>",
"e": 27542,
"s": 26894,
"text": null
},
{
"code": null,
"e": 27590,
"s": 27542,
"text": "Step 4: Working with the MainActivity.java file"
},
{
"code": null,
"e": 27780,
"s": 27590,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 27785,
"s": 27780,
"text": "Java"
},
{
"code": "import android.Manifest;import android.app.AlertDialog;import android.content.DialogInterface;import android.content.Intent;import android.net.Uri;import android.os.Bundle;import android.provider.Settings;import android.view.View;import android.widget.Button;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.karumi.dexter.Dexter;import com.karumi.dexter.MultiplePermissionsReport;import com.karumi.dexter.PermissionToken;import com.karumi.dexter.listener.DexterError;import com.karumi.dexter.listener.PermissionRequest;import com.karumi.dexter.listener.PermissionRequestErrorListener;import com.karumi.dexter.listener.multi.MultiplePermissionsListener; import java.util.List; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our button and adding on click listener to it. Button requestPermissionsBtn = findViewById(R.id.idBtnRequestPermission); requestPermissionsBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // inside on click listener calling // method to request permission requestPermissions(); } }); } private void requestPermissions() { // below line is use to request // permission in the current activity. Dexter.withActivity(this) // below line is use to request the number of // permissions which are required in our app. .withPermissions(Manifest.permission.CAMERA, // below is the list of permissions Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_CONTACTS) // after adding permissions we are // calling an with listener method. .withListener(new MultiplePermissionsListener() { @Override public void onPermissionsChecked(MultiplePermissionsReport multiplePermissionsReport) { // this method is called when all permissions are granted if (multiplePermissionsReport.areAllPermissionsGranted()) { // do you work now Toast.makeText(MainActivity.this, \"All the permissions are granted..\", Toast.LENGTH_SHORT).show(); } // check for permanent denial of any permission if (multiplePermissionsReport.isAnyPermissionPermanentlyDenied()) { // permission is denied permanently, // we will show user a dialog message. showSettingsDialog(); } } @Override public void onPermissionRationaleShouldBeShown(List<PermissionRequest> list, PermissionToken permissionToken) { // this method is called when user grants some // permission and denies some of them. permissionToken.continuePermissionRequest(); } }).withErrorListener(new PermissionRequestErrorListener() { // this method is use to handle error // in runtime permissions @Override public void onError(DexterError error) { // we are displaying a toast message for error message. Toast.makeText(getApplicationContext(), \"Error occurred! \", Toast.LENGTH_SHORT).show(); } }) // below line is use to run the permissions // on same thread and to check the permissions .onSameThread().check(); } // below is the shoe setting dialog // method which is use to display a // dialogue message. private void showSettingsDialog() { // we are displaying an alert dialog for permissions AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); // below line is the title // for our alert dialog. builder.setTitle(\"Need Permissions\"); // below line is our message for our dialog builder.setMessage(\"This app needs permission to use this feature. You can grant them in app settings.\"); builder.setPositiveButton(\"GOTO SETTINGS\", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // this method is called on click on positive // button and on clicking shit button we // are redirecting our user from our app to the // settings page of our app. dialog.cancel(); // below is the intent from which we // are redirecting our user. Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts(\"package\", getPackageName(), null); intent.setData(uri); startActivityForResult(intent, 101); } }); builder.setNegativeButton(\"Cancel\", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // this method is called when // user click on negative button. dialog.cancel(); } }); // below line is used // to display our dialog builder.show(); }}",
"e": 33549,
"s": 27785,
"text": null
},
{
"code": null,
"e": 33611,
"s": 33549,
"text": "Step 5: Adding the required permissions in the Manifest file "
},
{
"code": null,
"e": 33696,
"s": 33611,
"text": "Navigate to the app > AndroidManifest.xml file and add the below permissions to it. "
},
{
"code": null,
"e": 33700,
"s": 33696,
"text": "XML"
},
{
"code": "<!-- Permissions we are requesting from user --><uses-permission android:name=\"android.permission.CAMERA\"/><uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\"/><uses-permission android:name=\"android.permission.READ_CONTACTS\"/>",
"e": 33947,
"s": 33700,
"text": null
},
{
"code": null,
"e": 34060,
"s": 33947,
"text": "After adding these permissions in our AndroidManifest.xml file. Now run our app and see the output of the code. "
},
{
"code": null,
"e": 34068,
"s": 34060,
"text": "android"
},
{
"code": null,
"e": 34092,
"s": 34068,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 34100,
"s": 34092,
"text": "Android"
},
{
"code": null,
"e": 34105,
"s": 34100,
"text": "Java"
},
{
"code": null,
"e": 34124,
"s": 34105,
"text": "Technical Scripter"
},
{
"code": null,
"e": 34129,
"s": 34124,
"text": "Java"
},
{
"code": null,
"e": 34137,
"s": 34129,
"text": "Android"
},
{
"code": null,
"e": 34235,
"s": 34137,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34274,
"s": 34235,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 34316,
"s": 34274,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 34354,
"s": 34316,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 34427,
"s": 34354,
"text": "How to Change the Background Color After Clicking the Button in Android?"
},
{
"code": null,
"e": 34477,
"s": 34427,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 34492,
"s": 34477,
"text": "Arrays in Java"
},
{
"code": null,
"e": 34536,
"s": 34492,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 34558,
"s": 34536,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 34594,
"s": 34558,
"text": "Arrays.sort() in Java with examples"
}
] |
Reshape a pandas DataFrame using stack,unstack and melt method
|
08 Jan, 2019
Pandas use various methods to reshape the dataframe and series. Let’s see about the some of that reshaping method.
Let’s import a dataframe first.
# import pandas moduleimport pandas as pd # making dataframedf = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # it was print the first 5-rowsprint(df.head())
Output:
Using stack() method:
Stack method works with the MultiIndex objects in DataFrame, it returning a DataFrame with an index with a new inner-most level of row labels. It changes the wide table to a long table.
# import pandas moduleimport pandas as pd # making dataframedf = pd.read_csv("nba.csv") # reshape the dataframe using stack() methoddf_stacked = df.stack() print(df_stacked.head(26))
Output: Using unstack() method:unstack is similar to stack method, It also works with multi-index objects in dataframe, producing a reshaped DataFrame with a new inner-most level of column labels.
# import pandas moduleimport pandas as pd # making dataframedf = pd.read_csv("nba.csv") # unstack() methoddf_unstacked = df_stacked.unstack()print(df_unstacked.head(10))
Using melt() method:Melt in pandas reshape dataframe from wide format to long format. It uses the “id_vars[‘col_names’]” for melt the dataframe by column names.
# import pandas moduleimport pandas as pd # making dataframedf = pd.read_csv("nba.csv") # it takes two columns "Name" and "Team"df_melt = df.melt(id_vars =['Name', 'Team']) print(df_melt.head(10))
Output:
pandas-dataframe-program
Picked
Python pandas-dataFrame
Python-pandas
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": 28,
"s": 0,
"text": "\n08 Jan, 2019"
},
{
"code": null,
"e": 143,
"s": 28,
"text": "Pandas use various methods to reshape the dataframe and series. Let’s see about the some of that reshaping method."
},
{
"code": null,
"e": 175,
"s": 143,
"text": "Let’s import a dataframe first."
},
{
"code": "# import pandas moduleimport pandas as pd # making dataframedf = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # it was print the first 5-rowsprint(df.head()) ",
"e": 365,
"s": 175,
"text": null
},
{
"code": null,
"e": 373,
"s": 365,
"text": "Output:"
},
{
"code": null,
"e": 395,
"s": 373,
"text": "Using stack() method:"
},
{
"code": null,
"e": 581,
"s": 395,
"text": "Stack method works with the MultiIndex objects in DataFrame, it returning a DataFrame with an index with a new inner-most level of row labels. It changes the wide table to a long table."
},
{
"code": "# import pandas moduleimport pandas as pd # making dataframedf = pd.read_csv(\"nba.csv\") # reshape the dataframe using stack() methoddf_stacked = df.stack() print(df_stacked.head(26))",
"e": 767,
"s": 581,
"text": null
},
{
"code": null,
"e": 964,
"s": 767,
"text": "Output: Using unstack() method:unstack is similar to stack method, It also works with multi-index objects in dataframe, producing a reshaped DataFrame with a new inner-most level of column labels."
},
{
"code": "# import pandas moduleimport pandas as pd # making dataframedf = pd.read_csv(\"nba.csv\") # unstack() methoddf_unstacked = df_stacked.unstack()print(df_unstacked.head(10))",
"e": 1136,
"s": 964,
"text": null
},
{
"code": null,
"e": 1297,
"s": 1136,
"text": "Using melt() method:Melt in pandas reshape dataframe from wide format to long format. It uses the “id_vars[‘col_names’]” for melt the dataframe by column names."
},
{
"code": "# import pandas moduleimport pandas as pd # making dataframedf = pd.read_csv(\"nba.csv\") # it takes two columns \"Name\" and \"Team\"df_melt = df.melt(id_vars =['Name', 'Team']) print(df_melt.head(10))",
"e": 1496,
"s": 1297,
"text": null
},
{
"code": null,
"e": 1504,
"s": 1496,
"text": "Output:"
},
{
"code": null,
"e": 1529,
"s": 1504,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 1536,
"s": 1529,
"text": "Picked"
},
{
"code": null,
"e": 1560,
"s": 1536,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 1574,
"s": 1560,
"text": "Python-pandas"
},
{
"code": null,
"e": 1581,
"s": 1574,
"text": "Python"
},
{
"code": null,
"e": 1679,
"s": 1581,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1697,
"s": 1679,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1739,
"s": 1697,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1761,
"s": 1739,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1796,
"s": 1761,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1822,
"s": 1796,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1854,
"s": 1822,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1883,
"s": 1854,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1910,
"s": 1883,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1940,
"s": 1910,
"text": "Iterate over a list in Python"
}
] |
Python | Pandas MultiIndex.nlevels
|
24 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas MultiIndex.nlevels attribute returns the integer number of levels in the MultiIndex.
Syntax: MultiIndex.nlevels
Example #1: Use MultiIndex.nlevels attribute to find the number of levels in the MultiIndex.
# importing pandas as pdimport pandas as pd # Creating the arrayarray = [[1, 2, 3], ['Sharon', 'Nick', 'Bailey']] # Print the arrayprint(array)
Output :
Now let’s create the MultiIndex using this array
# Creating the MultiIndexmidx = pd.MultiIndex.from_arrays(array, names =('Number', 'Names')) # Print the MultiIndexprint(midx)
Output :
Now we will find the number of levels in the MultiIndex.
# Print the number of the levels in MultiIndexmidx.nlevels
Output :As we can see in the output, there are 2 levels in the midx MultiIndex. Example #2: Use MultiIndex.nlevels attribute to find the number of levels in the given MultiIndex.
# importing pandas as pdimport pandas as pd # Creating the arrayarray = [[1, 2, 3], ['Sharon', 'Nick', 'Bailey'], ['Doctor', 'Scientist', 'Physicist']] # Print the arrayprint(array)
Output :
Now let’s create the MultiIndex using this array
# Creating the MultiIndexmidx = pd.MultiIndex.from_arrays(array, names =('Ranking', 'Names', 'Profession')) # Print the MultiIndexprint(midx)
Output :
Now we will find the number of levels in the MultiIndex.
# Print the number of level in MultiIndexmidx.nlevels
Output :As we can see in the output, midx MultiIndex has 3 levels.
Python pandas-multiIndex
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Dec, 2018"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 334,
"s": 242,
"text": "Pandas MultiIndex.nlevels attribute returns the integer number of levels in the MultiIndex."
},
{
"code": null,
"e": 361,
"s": 334,
"text": "Syntax: MultiIndex.nlevels"
},
{
"code": null,
"e": 454,
"s": 361,
"text": "Example #1: Use MultiIndex.nlevels attribute to find the number of levels in the MultiIndex."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the arrayarray = [[1, 2, 3], ['Sharon', 'Nick', 'Bailey']] # Print the arrayprint(array)",
"e": 600,
"s": 454,
"text": null
},
{
"code": null,
"e": 609,
"s": 600,
"text": "Output :"
},
{
"code": null,
"e": 658,
"s": 609,
"text": "Now let’s create the MultiIndex using this array"
},
{
"code": "# Creating the MultiIndexmidx = pd.MultiIndex.from_arrays(array, names =('Number', 'Names')) # Print the MultiIndexprint(midx)",
"e": 786,
"s": 658,
"text": null
},
{
"code": null,
"e": 795,
"s": 786,
"text": "Output :"
},
{
"code": null,
"e": 852,
"s": 795,
"text": "Now we will find the number of levels in the MultiIndex."
},
{
"code": "# Print the number of the levels in MultiIndexmidx.nlevels",
"e": 911,
"s": 852,
"text": null
},
{
"code": null,
"e": 1090,
"s": 911,
"text": "Output :As we can see in the output, there are 2 levels in the midx MultiIndex. Example #2: Use MultiIndex.nlevels attribute to find the number of levels in the given MultiIndex."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the arrayarray = [[1, 2, 3], ['Sharon', 'Nick', 'Bailey'], ['Doctor', 'Scientist', 'Physicist']] # Print the arrayprint(array)",
"e": 1285,
"s": 1090,
"text": null
},
{
"code": null,
"e": 1294,
"s": 1285,
"text": "Output :"
},
{
"code": null,
"e": 1343,
"s": 1294,
"text": "Now let’s create the MultiIndex using this array"
},
{
"code": "# Creating the MultiIndexmidx = pd.MultiIndex.from_arrays(array, names =('Ranking', 'Names', 'Profession')) # Print the MultiIndexprint(midx)",
"e": 1496,
"s": 1343,
"text": null
},
{
"code": null,
"e": 1505,
"s": 1496,
"text": "Output :"
},
{
"code": null,
"e": 1562,
"s": 1505,
"text": "Now we will find the number of levels in the MultiIndex."
},
{
"code": "# Print the number of level in MultiIndexmidx.nlevels",
"e": 1616,
"s": 1562,
"text": null
},
{
"code": null,
"e": 1683,
"s": 1616,
"text": "Output :As we can see in the output, midx MultiIndex has 3 levels."
},
{
"code": null,
"e": 1708,
"s": 1683,
"text": "Python pandas-multiIndex"
},
{
"code": null,
"e": 1722,
"s": 1708,
"text": "Python-pandas"
},
{
"code": null,
"e": 1729,
"s": 1722,
"text": "Python"
},
{
"code": null,
"e": 1827,
"s": 1729,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1859,
"s": 1827,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1886,
"s": 1859,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1907,
"s": 1886,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1930,
"s": 1907,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1986,
"s": 1930,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2017,
"s": 1986,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2059,
"s": 2017,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2101,
"s": 2059,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2140,
"s": 2101,
"text": "Python | Get unique values from a list"
}
] |
Generalized Lists in Data Structure
|
In this section we will see the generalized lists. The generalized list can be defined as below −
A generalized list L is a finite sequence of n elements (n ≥ 0). The element ei is either an atom (single element) or another generalized list. The elements ei that are not atoms, they will be sub-list of L. Suppose L is ((A, B, C), ((D, E), F), G). Here L has three elements sub-list (A, B, C), sub-list ((D, E), F), and atom G. Again sub-list ((D, E), F) has two elements one sub-list (D, E) and atom F.
In C++, we can define the Generalized list structure like below −
class GeneralizedListNode{
private:
GeneralizedListNode *next;
bool tag;
union{
char data;
GeneralizedListNode *down;
};
};
So if the tag is true, then element represented by the node is a sub-list. The down points to the first node in the sub-list. If tag is false, the element is atom. The next pointer points to the next element in the list. The list will be look like this.
|
[
{
"code": null,
"e": 1285,
"s": 1187,
"text": "In this section we will see the generalized lists. The generalized list can be defined as below −"
},
{
"code": null,
"e": 1691,
"s": 1285,
"text": "A generalized list L is a finite sequence of n elements (n ≥ 0). The element ei is either an atom (single element) or another generalized list. The elements ei that are not atoms, they will be sub-list of L. Suppose L is ((A, B, C), ((D, E), F), G). Here L has three elements sub-list (A, B, C), sub-list ((D, E), F), and atom G. Again sub-list ((D, E), F) has two elements one sub-list (D, E) and atom F."
},
{
"code": null,
"e": 1757,
"s": 1691,
"text": "In C++, we can define the Generalized list structure like below −"
},
{
"code": null,
"e": 1926,
"s": 1757,
"text": "class GeneralizedListNode{\n private:\n GeneralizedListNode *next;\n bool tag;\n union{\n char data;\n GeneralizedListNode *down;\n };\n};"
},
{
"code": null,
"e": 2180,
"s": 1926,
"text": "So if the tag is true, then element represented by the node is a sub-list. The down points to the first node in the sub-list. If tag is false, the element is atom. The next pointer points to the next element in the list. The list will be look like this."
}
] |
Python Tkinter – Toplevel Widget
|
11 Aug, 2021
Tkinter is a GUI toolkit used in python to make user-friendly GUIs.Tkinter is the most commonly used and the most basic GUI framework available in Python. Tkinter uses an object-oriented approach to make GUIs.
Note: For more information, refer to Python GUI – tkinter
A Toplevel widget is used to create a window on top of all other windows. The Toplevel widget is used to provide some extra information to the user and also when our program deals with more than one application. These windows are directly organized and managed by the Window Manager and do not need to have any parent window associated with them every time.
Syntax:
toplevel = Toplevel(root, bg, fg, bd, height, width, font, ..)
Optional parameters
root = root window(optional)
bg = background colour
fg = foreground colour
bd = border
height = height of the widget.
width = width of the widget.
font = Font type of the text.
cursor = cursor that appears on the widget which can be an arrow, a dot etc.
Common methods
iconify turns the windows into icon.
deiconify turns back the icon into window.
state returns the current state of window.
withdraw removes the window from the screen.
title defines title for window.
frame returns a window identifier which is system specific.
Example 1:
Python3
from tkinter import * root = Tk()root.geometry("200x300")root.title("main") l = Label(root, text = "This is root window") top = Toplevel()top.geometry("180x100")top.title("toplevel")l2 = Label(top, text = "This is toplevel window") l.pack()l2.pack() top.mainloop()
Output
Example 2: Creating Multiple toplevels over one another
Python3
from tkinter import * # Create the root window# with specified size and titleroot = Tk() root.title("Root Window") root.geometry("450x300") # Create label for root windowlabel1 = Label(root, text = "This is the root window") # define a function for 2nd toplevel# window which is not associated with# any parent windowdef open_Toplevel2(): # Create widget top2 = Toplevel() # define title for window top2.title("Toplevel2") # specify size top2.geometry("200x100") # Create label label = Label(top2, text = "This is a Toplevel2 window") # Create exit button. button = Button(top2, text = "Exit", command = top2.destroy) label.pack() button.pack() # Display until closed manually. top2.mainloop() # define a function for 1st toplevel# which is associated with root window.def open_Toplevel1(): # Create widget top1 = Toplevel(root) # Define title for window top1.title("Toplevel1") # specify size top1.geometry("200x200") # Create label label = Label(top1, text = "This is a Toplevel1 window") # Create Exit button button1 = Button(top1, text = "Exit", command = top1.destroy) # create button to open toplevel2 button2 = Button(top1, text = "open toplevel2", command = open_Toplevel2) label.pack() button2.pack() button1.pack() # Display until closed manually top1.mainloop() # Create button to open toplevel1button = Button(root, text = "open toplevel1", command = open_Toplevel1)label1.pack() # position the buttonbutton.place(x = 155, y = 50) # Display until closed manuallyroot.mainloop()
Output
arorakashish0911
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n11 Aug, 2021"
},
{
"code": null,
"e": 263,
"s": 53,
"text": "Tkinter is a GUI toolkit used in python to make user-friendly GUIs.Tkinter is the most commonly used and the most basic GUI framework available in Python. Tkinter uses an object-oriented approach to make GUIs."
},
{
"code": null,
"e": 321,
"s": 263,
"text": "Note: For more information, refer to Python GUI – tkinter"
},
{
"code": null,
"e": 679,
"s": 321,
"text": "A Toplevel widget is used to create a window on top of all other windows. The Toplevel widget is used to provide some extra information to the user and also when our program deals with more than one application. These windows are directly organized and managed by the Window Manager and do not need to have any parent window associated with them every time."
},
{
"code": null,
"e": 689,
"s": 679,
"text": "Syntax: "
},
{
"code": null,
"e": 752,
"s": 689,
"text": "toplevel = Toplevel(root, bg, fg, bd, height, width, font, ..)"
},
{
"code": null,
"e": 774,
"s": 752,
"text": "Optional parameters "
},
{
"code": null,
"e": 804,
"s": 774,
"text": "root = root window(optional) "
},
{
"code": null,
"e": 828,
"s": 804,
"text": "bg = background colour "
},
{
"code": null,
"e": 852,
"s": 828,
"text": "fg = foreground colour "
},
{
"code": null,
"e": 865,
"s": 852,
"text": "bd = border "
},
{
"code": null,
"e": 897,
"s": 865,
"text": "height = height of the widget. "
},
{
"code": null,
"e": 927,
"s": 897,
"text": "width = width of the widget. "
},
{
"code": null,
"e": 958,
"s": 927,
"text": "font = Font type of the text. "
},
{
"code": null,
"e": 1036,
"s": 958,
"text": "cursor = cursor that appears on the widget which can be an arrow, a dot etc. "
},
{
"code": null,
"e": 1053,
"s": 1036,
"text": "Common methods "
},
{
"code": null,
"e": 1091,
"s": 1053,
"text": "iconify turns the windows into icon. "
},
{
"code": null,
"e": 1135,
"s": 1091,
"text": "deiconify turns back the icon into window. "
},
{
"code": null,
"e": 1179,
"s": 1135,
"text": "state returns the current state of window. "
},
{
"code": null,
"e": 1225,
"s": 1179,
"text": "withdraw removes the window from the screen. "
},
{
"code": null,
"e": 1258,
"s": 1225,
"text": "title defines title for window. "
},
{
"code": null,
"e": 1319,
"s": 1258,
"text": "frame returns a window identifier which is system specific. "
},
{
"code": null,
"e": 1332,
"s": 1319,
"text": "Example 1: "
},
{
"code": null,
"e": 1340,
"s": 1332,
"text": "Python3"
},
{
"code": "from tkinter import * root = Tk()root.geometry(\"200x300\")root.title(\"main\") l = Label(root, text = \"This is root window\") top = Toplevel()top.geometry(\"180x100\")top.title(\"toplevel\")l2 = Label(top, text = \"This is toplevel window\") l.pack()l2.pack() top.mainloop()",
"e": 1606,
"s": 1340,
"text": null
},
{
"code": null,
"e": 1613,
"s": 1606,
"text": "Output"
},
{
"code": null,
"e": 1670,
"s": 1613,
"text": "Example 2: Creating Multiple toplevels over one another "
},
{
"code": null,
"e": 1678,
"s": 1670,
"text": "Python3"
},
{
"code": "from tkinter import * # Create the root window# with specified size and titleroot = Tk() root.title(\"Root Window\") root.geometry(\"450x300\") # Create label for root windowlabel1 = Label(root, text = \"This is the root window\") # define a function for 2nd toplevel# window which is not associated with# any parent windowdef open_Toplevel2(): # Create widget top2 = Toplevel() # define title for window top2.title(\"Toplevel2\") # specify size top2.geometry(\"200x100\") # Create label label = Label(top2, text = \"This is a Toplevel2 window\") # Create exit button. button = Button(top2, text = \"Exit\", command = top2.destroy) label.pack() button.pack() # Display until closed manually. top2.mainloop() # define a function for 1st toplevel# which is associated with root window.def open_Toplevel1(): # Create widget top1 = Toplevel(root) # Define title for window top1.title(\"Toplevel1\") # specify size top1.geometry(\"200x200\") # Create label label = Label(top1, text = \"This is a Toplevel1 window\") # Create Exit button button1 = Button(top1, text = \"Exit\", command = top1.destroy) # create button to open toplevel2 button2 = Button(top1, text = \"open toplevel2\", command = open_Toplevel2) label.pack() button2.pack() button1.pack() # Display until closed manually top1.mainloop() # Create button to open toplevel1button = Button(root, text = \"open toplevel1\", command = open_Toplevel1)label1.pack() # position the buttonbutton.place(x = 155, y = 50) # Display until closed manuallyroot.mainloop()",
"e": 3457,
"s": 1678,
"text": null
},
{
"code": null,
"e": 3465,
"s": 3457,
"text": "Output "
},
{
"code": null,
"e": 3484,
"s": 3467,
"text": "arorakashish0911"
},
{
"code": null,
"e": 3499,
"s": 3484,
"text": "Python-tkinter"
},
{
"code": null,
"e": 3506,
"s": 3499,
"text": "Python"
}
] |
Python – Sum of tuple elements
|
19 Feb, 2020
Sometimes, while programming, we have a problem in which we might need to perform summation among tuple elements. This is an essential utility as we come across summation operation many times and tuples are immutable and hence required to be dealt with. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list() + sum()The above functions can be combined to perform this task. We can employ sum() to accumulate the result of summation logic. The list() function is used to perform interconversions.
# Python3 code to demonstrate working of # Tuple summation# Using list() + sum() # initializing tup test_tup = (7, 8, 9, 1, 10, 7) # printing original tupleprint("The original tuple is : " + str(test_tup)) # Tuple elements inversions# Using list() + sum()res = sum(list(test_tup)) # printing result print("The summation of tuple elements are : " + str(res))
The original tuple is : (7, 8, 9, 1, 10, 7)
The summation of tuple elements are : 42
Method #2 : Using map() + sum() + list()The combination of above functions can be used to perform this task. In this, we first convert the tuple to list, flatten it’s each list element using map(), perform summation of each using sum() and again employ sum() for overall summation of resultant list.
# Python 3 code to demonstrate working of # Tuple elements inversions# Using map() + list() + sum() # initializing tup test_tup = ([7, 8], [9, 1], [10, 7]) # printing original tupleprint("The original tuple is : " + str(test_tup)) # Tuple elements inversions# Using map() + list() + sum()res = sum(list(map(sum, list(test_tup)))) # printing result print("The summation of tuple elements are : " + str(res))
The original tuple is : (7, 8, 9, 1, 10, 7)
The summation of tuple elements are : 42
Python tuple-programs
Python
Python Programs
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
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Feb, 2020"
},
{
"code": null,
"e": 370,
"s": 52,
"text": "Sometimes, while programming, we have a problem in which we might need to perform summation among tuple elements. This is an essential utility as we come across summation operation many times and tuples are immutable and hence required to be dealt with. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 582,
"s": 370,
"text": "Method #1 : Using list() + sum()The above functions can be combined to perform this task. We can employ sum() to accumulate the result of summation logic. The list() function is used to perform interconversions."
},
{
"code": "# Python3 code to demonstrate working of # Tuple summation# Using list() + sum() # initializing tup test_tup = (7, 8, 9, 1, 10, 7) # printing original tupleprint(\"The original tuple is : \" + str(test_tup)) # Tuple elements inversions# Using list() + sum()res = sum(list(test_tup)) # printing result print(\"The summation of tuple elements are : \" + str(res)) ",
"e": 947,
"s": 582,
"text": null
},
{
"code": null,
"e": 1033,
"s": 947,
"text": "The original tuple is : (7, 8, 9, 1, 10, 7)\nThe summation of tuple elements are : 42\n"
},
{
"code": null,
"e": 1335,
"s": 1035,
"text": "Method #2 : Using map() + sum() + list()The combination of above functions can be used to perform this task. In this, we first convert the tuple to list, flatten it’s each list element using map(), perform summation of each using sum() and again employ sum() for overall summation of resultant list."
},
{
"code": "# Python 3 code to demonstrate working of # Tuple elements inversions# Using map() + list() + sum() # initializing tup test_tup = ([7, 8], [9, 1], [10, 7]) # printing original tupleprint(\"The original tuple is : \" + str(test_tup)) # Tuple elements inversions# Using map() + list() + sum()res = sum(list(map(sum, list(test_tup)))) # printing result print(\"The summation of tuple elements are : \" + str(res)) ",
"e": 1749,
"s": 1335,
"text": null
},
{
"code": null,
"e": 1835,
"s": 1749,
"text": "The original tuple is : (7, 8, 9, 1, 10, 7)\nThe summation of tuple elements are : 42\n"
},
{
"code": null,
"e": 1857,
"s": 1835,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 1864,
"s": 1857,
"text": "Python"
},
{
"code": null,
"e": 1880,
"s": 1864,
"text": "Python Programs"
},
{
"code": null,
"e": 1978,
"s": 1880,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1996,
"s": 1978,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2038,
"s": 1996,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2060,
"s": 2038,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2086,
"s": 2060,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2118,
"s": 2086,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2161,
"s": 2118,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2183,
"s": 2161,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2222,
"s": 2183,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2260,
"s": 2222,
"text": "Python | Convert a list to dictionary"
}
] |
Finding Exploit offline using Searchsploit in Kali Linux
|
24 Dec, 2020
SearchSploit is a command-line search tool for Exploit-DB that allows you to take a copy of the Exploit Database with you. Searchsploit is included in the Exploit Database repository on GitHub. SearchSploit is very useful for security assessments when you don’t have Internet access because it gives you the power to perform detailed offline searches for exploits in the saved Exploit-DB.
Installing SearchSploit – To run SearchSploit in Kali Linux, open the terminal and type “searchsploit” to run SearchSploit as “exploitdb” package is already included in Kali Linux. However, if you are using the Kali Light variant or your custom-build ISO then you can install SearchSploit manually using the below-mentioned command.
sudo apt update && sudo apt -y install exploitdb
Updating SearchSploit: In order to update SearchSploit, run the following command:
searchsploit -u
1. Basic Search – You can add any number of search terms you wish to look for. In the below image, we are searching for exploits containing the term “oracle” and “windows”.
In case you need help just type “searchsploit -h” in the terminal. By using -h, you can see all the options and features that are available to you:
2. Title Searching in SearchSploit: If you are performing Basic Search, searchsploit will check for both the path and the title of the exploit. Searches can be restricted to the titles by using the -t option as follows:
In the above search, we are looking for the exploits related to Oracle based on Windows OS.
3. Copying Exploit to Clipboard and Directory: If you want to copy the exploit to clipboard use ‘-p’. For example – ” searchsploit -p XYZ ” , here XYZ is the exploit ID. If you want to copy the exploit in your current working directory use ‘-m’. For example – ” searchsploit -m XYZ “, where XYZ is the exploit ID.
4. Examine an Exploit: If you want to examine an exploit or want to study an exploit, use ‘–examine’. For example – “searchsploit XYZ –examine” , where XYZ is the exploit ID.
5. Eliminate Unwanted Results: If you want to eliminate unwanted results from your search simply use ‘–exclude’. You can also remove multiple terms by separating the terms with a “|” (pipe). For example – searchsploit –exclude “PoC”.
Kali-Linux
Technical Scripter 2020
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
Introduction to Linux Operating System
nohup Command in Linux with Examples
Array Basics in Shell Scripting | Set 1
mv command in Linux with examples
chmod command in Linux with examples
screen command in Linux with Examples
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Dec, 2020"
},
{
"code": null,
"e": 417,
"s": 28,
"text": "SearchSploit is a command-line search tool for Exploit-DB that allows you to take a copy of the Exploit Database with you. Searchsploit is included in the Exploit Database repository on GitHub. SearchSploit is very useful for security assessments when you don’t have Internet access because it gives you the power to perform detailed offline searches for exploits in the saved Exploit-DB."
},
{
"code": null,
"e": 750,
"s": 417,
"text": "Installing SearchSploit – To run SearchSploit in Kali Linux, open the terminal and type “searchsploit” to run SearchSploit as “exploitdb” package is already included in Kali Linux. However, if you are using the Kali Light variant or your custom-build ISO then you can install SearchSploit manually using the below-mentioned command."
},
{
"code": null,
"e": 799,
"s": 750,
"text": "sudo apt update && sudo apt -y install exploitdb"
},
{
"code": null,
"e": 883,
"s": 799,
"text": "Updating SearchSploit: In order to update SearchSploit, run the following command:"
},
{
"code": null,
"e": 899,
"s": 883,
"text": "searchsploit -u"
},
{
"code": null,
"e": 1072,
"s": 899,
"text": "1. Basic Search – You can add any number of search terms you wish to look for. In the below image, we are searching for exploits containing the term “oracle” and “windows”."
},
{
"code": null,
"e": 1220,
"s": 1072,
"text": "In case you need help just type “searchsploit -h” in the terminal. By using -h, you can see all the options and features that are available to you:"
},
{
"code": null,
"e": 1440,
"s": 1220,
"text": "2. Title Searching in SearchSploit: If you are performing Basic Search, searchsploit will check for both the path and the title of the exploit. Searches can be restricted to the titles by using the -t option as follows:"
},
{
"code": null,
"e": 1533,
"s": 1440,
"text": "In the above search, we are looking for the exploits related to Oracle based on Windows OS. "
},
{
"code": null,
"e": 1847,
"s": 1533,
"text": "3. Copying Exploit to Clipboard and Directory: If you want to copy the exploit to clipboard use ‘-p’. For example – ” searchsploit -p XYZ ” , here XYZ is the exploit ID. If you want to copy the exploit in your current working directory use ‘-m’. For example – ” searchsploit -m XYZ “, where XYZ is the exploit ID."
},
{
"code": null,
"e": 2022,
"s": 1847,
"text": "4. Examine an Exploit: If you want to examine an exploit or want to study an exploit, use ‘–examine’. For example – “searchsploit XYZ –examine” , where XYZ is the exploit ID."
},
{
"code": null,
"e": 2256,
"s": 2022,
"text": "5. Eliminate Unwanted Results: If you want to eliminate unwanted results from your search simply use ‘–exclude’. You can also remove multiple terms by separating the terms with a “|” (pipe). For example – searchsploit –exclude “PoC”."
},
{
"code": null,
"e": 2267,
"s": 2256,
"text": "Kali-Linux"
},
{
"code": null,
"e": 2291,
"s": 2267,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 2302,
"s": 2291,
"text": "Linux-Unix"
},
{
"code": null,
"e": 2321,
"s": 2302,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2419,
"s": 2321,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2445,
"s": 2419,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 2480,
"s": 2445,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 2517,
"s": 2480,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 2546,
"s": 2517,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 2585,
"s": 2546,
"text": "Introduction to Linux Operating System"
},
{
"code": null,
"e": 2622,
"s": 2585,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 2662,
"s": 2622,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 2696,
"s": 2662,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 2733,
"s": 2696,
"text": "chmod command in Linux with examples"
}
] |
Python Program for Depth First Search or DFS for a Graph
|
22 Jun, 2022
Depth First Traversal (or Search) for a graph is similar to Depth First Traversal of a tree. The only catch here is, unlike trees, graphs may contain cycles, so we may come to the same node again. To avoid processing a node more than once, we use a boolean visited array.
For example, in the following graph, we start traversal from vertex 2. When we come to vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If we don\’t mark visited vertices, then 2 will be processed again and it will become a non-terminating process. A Depth First Traversal of the following graph is 2, 0, 1, 3.
See this post for all applications of Depth First Traversal.Following are implementations of simple Depth First Traversal. The C++ implementation uses adjacency list representation of graphs. STL\’s list container is used to store lists of adjacent nodes.
Python
# Python program to print DFS traversal for complete graphfrom collections import defaultdict # This class represents a directed graph using adjacency# list representationclass Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) # A function used by DFS def DFSUtil(self, v, visited): # Mark the current node as visited and print it visited[v]= True print v, # Recur for all the vertices adjacent to # this vertex for i in self.graph[v]: if visited[i] == False: self.DFSUtil(i, visited) # The function to do DFS traversal. It uses # recursive DFSUtil() def DFS(self): V = len(self.graph) #total vertices # Mark all the vertices as not visited visited =[False]*(V) # Call the recursive helper function to print # DFS traversal starting from all vertices one # by one for i in range(V): if visited[i] == False: self.DFSUtil(i, visited) # Driver code# Create a graph given in the above diagramg = Graph()g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3) print "Following is Depth First Traversal"g.DFS() # This code is contributed by Neelam Yadav
Time Complexity : O(V+E) where V is the number of vertices in graph and E is the number of edges in graphAuxiliary Space: O(V)Please refer complete article on Depth First Search or DFS for a Graph for more details!
ishankhandelwals
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 300,
"s": 28,
"text": "Depth First Traversal (or Search) for a graph is similar to Depth First Traversal of a tree. The only catch here is, unlike trees, graphs may contain cycles, so we may come to the same node again. To avoid processing a node more than once, we use a boolean visited array."
},
{
"code": null,
"e": 648,
"s": 300,
"text": "For example, in the following graph, we start traversal from vertex 2. When we come to vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If we don\\’t mark visited vertices, then 2 will be processed again and it will become a non-terminating process. A Depth First Traversal of the following graph is 2, 0, 1, 3."
},
{
"code": null,
"e": 904,
"s": 648,
"text": "See this post for all applications of Depth First Traversal.Following are implementations of simple Depth First Traversal. The C++ implementation uses adjacency list representation of graphs. STL\\’s list container is used to store lists of adjacent nodes."
},
{
"code": null,
"e": 911,
"s": 904,
"text": "Python"
},
{
"code": "# Python program to print DFS traversal for complete graphfrom collections import defaultdict # This class represents a directed graph using adjacency# list representationclass Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) # A function used by DFS def DFSUtil(self, v, visited): # Mark the current node as visited and print it visited[v]= True print v, # Recur for all the vertices adjacent to # this vertex for i in self.graph[v]: if visited[i] == False: self.DFSUtil(i, visited) # The function to do DFS traversal. It uses # recursive DFSUtil() def DFS(self): V = len(self.graph) #total vertices # Mark all the vertices as not visited visited =[False]*(V) # Call the recursive helper function to print # DFS traversal starting from all vertices one # by one for i in range(V): if visited[i] == False: self.DFSUtil(i, visited) # Driver code# Create a graph given in the above diagramg = Graph()g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3) print \"Following is Depth First Traversal\"g.DFS() # This code is contributed by Neelam Yadav",
"e": 2337,
"s": 911,
"text": null
},
{
"code": null,
"e": 2552,
"s": 2337,
"text": "Time Complexity : O(V+E) where V is the number of vertices in graph and E is the number of edges in graphAuxiliary Space: O(V)Please refer complete article on Depth First Search or DFS for a Graph for more details!"
},
{
"code": null,
"e": 2569,
"s": 2552,
"text": "ishankhandelwals"
},
{
"code": null,
"e": 2585,
"s": 2569,
"text": "Python Programs"
}
] |
<utility> in C++
|
03 Aug, 2021
It is a header file that contains utilities in unrelated domains.
Pairs: These are the objects which can hold two different types of values.
Generic Relational Approach: It is used for the relational operators !=, >, = under a specific namespace: rel_ops.
Generic swap function: This a standard definition used by default by the components of the standard library for all types that do not provide their own overload: swap.
Functions:
1. swap: It exchanges the value of two objects.
C++
// CPP program to illustrate// the use of swap function#include <iostream> #include <utility> using namespace std; // Driver Programint main (){ // a: _ _ _ _ (empty array in beginning) int a[4]; // Initializing, a: _ _ _ _ & b: 10 20 30 40 int b[] = {10, 20, 30, 40}; // After swapping, a: 10 20 30 40 & b: _ _ _ _ swap(a, b); cout << "a contains:"; for (int i; i<4;i++) cout << a[i]<<endl; return 0;}
Output:
a contains:10
20
30
40
2. make_pair: It constructs a pair with its first element set to x and its second element set to y.
C++
// CPP program to illustrate// the use of make_pair#include <utility> #include <iostream>using namespace std; // Driver programint main (){ // Initializing the pair with int type pair <int, int> a; pair <int, int> b; // Use of the make_pair function a = make_pair (10, 20); // It's ok to write like this as implicit // conversion takes place from pair<double, char> b = make_pair (15.5, 'B'); // Printing the first and second values of the pair cout << "a: " << a.first << ", " << a.second << endl; cout << "b: " << b.first << ", " << b.second << endl; return 0;}
Output:
a: 10, 20
b: 15, 66
3. move: It moves as rvalue. move is used to indicate that an object may be “moved from”, i.e. allowing the transfer of resources from an object(to be moved) to another object.
C++
// CPP program to illustrate// the use of move#include <utility> #include <iostream> #include <vector> #include <string> using namespace std; // Driver Programint main (){ string s = "Hello!!"; string s1 = "I am a geek."; vector<string> gfg; // It copies 's' in gfg gfg.push_back (s); // It moves 's1' in the gfg(containing 's') gfg.push_back (move(s1)); cout << "gfg contains:"; for (int i=0;i< gfg.size(); i++) cout << ' ' << gfg[i]; cout<<endl; return 0;}
Output:
gfg contains: Hello!! I am a geek.
4. move (range of elements): It moves the elements in the range [first, last) into the range beginning at result. After this operation the elements in the moved-from range will still contain valid values of the appropriate type, but not necessarily the same values as before the move.
C++
// CPP program to// Illustrate the use of vector// move range of elements#include <iostream> // for move (ranges)#include <algorithm> // for move (objects)#include <utility> #include <vector> #include <string>using namespace std; // Driver programint main (){ vector<string> string1 = {"Hello!", "I", "am", "a", "geek"}; vector<string> string2 (5); // moving ranges: cout << "Moving ranges...\n"; // use of move i.e.it moves from first to last element in // string 1 to the string2 from it's(string 2) starting move ( string1.begin(), string1.begin()+5, string2.begin() ); cout << "string1 contains " << string1.size() << " elements\n"; cout << "string2 contains " << string2.size() << " elements(after moving):"; for (int i=0; i<string2.size(); i++) cout << string2[i] << " "; cout << endl; return 0;}
Output:
Moving ranges...
string1 contains 5 elements
string2 contains 5 elements(after moving):Hello! I am a geek
5. move_if_noexcept: It obtains an rvalue reference to its argument if its move constructor does not throw exceptions, otherwise obtains an lvalue reference to its argument.
C++
// CPP program to illustrate// the use of move_if_noexcept#include<iostream>#include<utility>using namespace std; struct Bad{ Bad() {} // may throw Bad(Bad&&) { cout << "Throwing move constructor called"<<endl; } // may throw as well Bad(const Bad&) { cout << "Throwing copy constructor called"<<endl; }}; struct Good{ Good() {} // will NOT throw Good(Good&&) noexcept { cout << "Non-throwing move constructor called"<<endl; } // will NOT throw Good(const Good&) noexcept { cout << "Non-throwing copy constructor called"<<endl; }}; // Driver Programint main(){ Good g; Bad b; Good g2 = move_if_noexcept(g); Bad b2 = move_if_noexcept(b);}
Output:
Non-throwing move constructor called
Throwing copy constructor called
6. decval: It returns an rvalue reference without referring to any object. This function selects the type of an argument as an rvalue reference if its move constructor never throw, or alternatively, as an lvalue reference if the type is copy-constructible. If the type is neither, the function returns an rvalue, which will be selected for move-only types (even if they may throw). Some operations can be implemented both by moving or by copying objects, generally moving for rvalues and copying for lvalues: Moving is generally a more efficient operation than copying when the object is no longer needed (such as rvalues).
C++
// CPP program to illustrate// the use of declval#include <utility>#include <iostream>using namespace std; //classstruct A{virtual int value() = 0;}; // Class with constructorclass B : public A{ int val_; public: B(int i, int j):val_(i*j){} int value() { return val_; }}; // Driver Programint main(){ // int a decltype(declval<A>().value()) a; // int b decltype(declval<B>().value()) b; //same as constructor a = b = B(100, 20).value(); cout << a << endl; return 0;}
Output:
2000
This article is contributed by Shambhavi Singh. 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.
arorakashish0911
CPP-Library
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 95,
"s": 28,
"text": "It is a header file that contains utilities in unrelated domains. "
},
{
"code": null,
"e": 171,
"s": 95,
"text": "Pairs: These are the objects which can hold two different types of values. "
},
{
"code": null,
"e": 287,
"s": 171,
"text": "Generic Relational Approach: It is used for the relational operators !=, >, = under a specific namespace: rel_ops. "
},
{
"code": null,
"e": 455,
"s": 287,
"text": "Generic swap function: This a standard definition used by default by the components of the standard library for all types that do not provide their own overload: swap."
},
{
"code": null,
"e": 467,
"s": 455,
"text": "Functions: "
},
{
"code": null,
"e": 515,
"s": 467,
"text": "1. swap: It exchanges the value of two objects."
},
{
"code": null,
"e": 519,
"s": 515,
"text": "C++"
},
{
"code": "// CPP program to illustrate// the use of swap function#include <iostream> #include <utility> using namespace std; // Driver Programint main (){ // a: _ _ _ _ (empty array in beginning) int a[4]; // Initializing, a: _ _ _ _ & b: 10 20 30 40 int b[] = {10, 20, 30, 40}; // After swapping, a: 10 20 30 40 & b: _ _ _ _ swap(a, b); cout << \"a contains:\"; for (int i; i<4;i++) cout << a[i]<<endl; return 0;}",
"e": 1003,
"s": 519,
"text": null
},
{
"code": null,
"e": 1012,
"s": 1003,
"text": "Output: "
},
{
"code": null,
"e": 1035,
"s": 1012,
"text": "a contains:10\n20\n30\n40"
},
{
"code": null,
"e": 1135,
"s": 1035,
"text": "2. make_pair: It constructs a pair with its first element set to x and its second element set to y."
},
{
"code": null,
"e": 1139,
"s": 1135,
"text": "C++"
},
{
"code": "// CPP program to illustrate// the use of make_pair#include <utility> #include <iostream>using namespace std; // Driver programint main (){ // Initializing the pair with int type pair <int, int> a; pair <int, int> b; // Use of the make_pair function a = make_pair (10, 20); // It's ok to write like this as implicit // conversion takes place from pair<double, char> b = make_pair (15.5, 'B'); // Printing the first and second values of the pair cout << \"a: \" << a.first << \", \" << a.second << endl; cout << \"b: \" << b.first << \", \" << b.second << endl; return 0;}",
"e": 1767,
"s": 1139,
"text": null
},
{
"code": null,
"e": 1775,
"s": 1767,
"text": "Output:"
},
{
"code": null,
"e": 1795,
"s": 1775,
"text": "a: 10, 20\nb: 15, 66"
},
{
"code": null,
"e": 1972,
"s": 1795,
"text": "3. move: It moves as rvalue. move is used to indicate that an object may be “moved from”, i.e. allowing the transfer of resources from an object(to be moved) to another object."
},
{
"code": null,
"e": 1976,
"s": 1972,
"text": "C++"
},
{
"code": "// CPP program to illustrate// the use of move#include <utility> #include <iostream> #include <vector> #include <string> using namespace std; // Driver Programint main (){ string s = \"Hello!!\"; string s1 = \"I am a geek.\"; vector<string> gfg; // It copies 's' in gfg gfg.push_back (s); // It moves 's1' in the gfg(containing 's') gfg.push_back (move(s1)); cout << \"gfg contains:\"; for (int i=0;i< gfg.size(); i++) cout << ' ' << gfg[i]; cout<<endl; return 0;}",
"e": 2515,
"s": 1976,
"text": null
},
{
"code": null,
"e": 2523,
"s": 2515,
"text": "Output:"
},
{
"code": null,
"e": 2558,
"s": 2523,
"text": "gfg contains: Hello!! I am a geek."
},
{
"code": null,
"e": 2843,
"s": 2558,
"text": "4. move (range of elements): It moves the elements in the range [first, last) into the range beginning at result. After this operation the elements in the moved-from range will still contain valid values of the appropriate type, but not necessarily the same values as before the move."
},
{
"code": null,
"e": 2847,
"s": 2843,
"text": "C++"
},
{
"code": "// CPP program to// Illustrate the use of vector// move range of elements#include <iostream> // for move (ranges)#include <algorithm> // for move (objects)#include <utility> #include <vector> #include <string>using namespace std; // Driver programint main (){ vector<string> string1 = {\"Hello!\", \"I\", \"am\", \"a\", \"geek\"}; vector<string> string2 (5); // moving ranges: cout << \"Moving ranges...\\n\"; // use of move i.e.it moves from first to last element in // string 1 to the string2 from it's(string 2) starting move ( string1.begin(), string1.begin()+5, string2.begin() ); cout << \"string1 contains \" << string1.size() << \" elements\\n\"; cout << \"string2 contains \" << string2.size() << \" elements(after moving):\"; for (int i=0; i<string2.size(); i++) cout << string2[i] << \" \"; cout << endl; return 0;}",
"e": 3788,
"s": 2847,
"text": null
},
{
"code": null,
"e": 3796,
"s": 3788,
"text": "Output:"
},
{
"code": null,
"e": 3903,
"s": 3796,
"text": "Moving ranges...\nstring1 contains 5 elements\nstring2 contains 5 elements(after moving):Hello! I am a geek "
},
{
"code": null,
"e": 4077,
"s": 3903,
"text": "5. move_if_noexcept: It obtains an rvalue reference to its argument if its move constructor does not throw exceptions, otherwise obtains an lvalue reference to its argument."
},
{
"code": null,
"e": 4081,
"s": 4077,
"text": "C++"
},
{
"code": "// CPP program to illustrate// the use of move_if_noexcept#include<iostream>#include<utility>using namespace std; struct Bad{ Bad() {} // may throw Bad(Bad&&) { cout << \"Throwing move constructor called\"<<endl; } // may throw as well Bad(const Bad&) { cout << \"Throwing copy constructor called\"<<endl; }}; struct Good{ Good() {} // will NOT throw Good(Good&&) noexcept { cout << \"Non-throwing move constructor called\"<<endl; } // will NOT throw Good(const Good&) noexcept { cout << \"Non-throwing copy constructor called\"<<endl; }}; // Driver Programint main(){ Good g; Bad b; Good g2 = move_if_noexcept(g); Bad b2 = move_if_noexcept(b);}",
"e": 4839,
"s": 4081,
"text": null
},
{
"code": null,
"e": 4847,
"s": 4839,
"text": "Output:"
},
{
"code": null,
"e": 4917,
"s": 4847,
"text": "Non-throwing move constructor called\nThrowing copy constructor called"
},
{
"code": null,
"e": 5541,
"s": 4917,
"text": "6. decval: It returns an rvalue reference without referring to any object. This function selects the type of an argument as an rvalue reference if its move constructor never throw, or alternatively, as an lvalue reference if the type is copy-constructible. If the type is neither, the function returns an rvalue, which will be selected for move-only types (even if they may throw). Some operations can be implemented both by moving or by copying objects, generally moving for rvalues and copying for lvalues: Moving is generally a more efficient operation than copying when the object is no longer needed (such as rvalues)."
},
{
"code": null,
"e": 5545,
"s": 5541,
"text": "C++"
},
{
"code": "// CPP program to illustrate// the use of declval#include <utility>#include <iostream>using namespace std; //classstruct A{virtual int value() = 0;}; // Class with constructorclass B : public A{ int val_; public: B(int i, int j):val_(i*j){} int value() { return val_; }}; // Driver Programint main(){ // int a decltype(declval<A>().value()) a; // int b decltype(declval<B>().value()) b; //same as constructor a = b = B(100, 20).value(); cout << a << endl; return 0;}",
"e": 6084,
"s": 5545,
"text": null
},
{
"code": null,
"e": 6092,
"s": 6084,
"text": "Output:"
},
{
"code": null,
"e": 6097,
"s": 6092,
"text": "2000"
},
{
"code": null,
"e": 6520,
"s": 6097,
"text": "This article is contributed by Shambhavi Singh. 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."
},
{
"code": null,
"e": 6537,
"s": 6520,
"text": "arorakashish0911"
},
{
"code": null,
"e": 6549,
"s": 6537,
"text": "CPP-Library"
},
{
"code": null,
"e": 6553,
"s": 6549,
"text": "C++"
},
{
"code": null,
"e": 6557,
"s": 6553,
"text": "CPP"
}
] |
Python | Check if a Substring is Present in a Given String
|
24 Jun, 2022
In this article, we will cover how to check if a Python string contains another string or a substring in Python.
Given two strings, check if a substring is there in the given string or not.
Example 1: Input : Substring = "geeks"
String="geeks for geeks"
Output : yes
Example 2: Input : Substring = "geek"
String="geeks for geeks"
Output : yes
Yes, Checking a substring is one of the most used tasks in python. Python uses many methods to check a string containing a substring like, find(), index(), count(), etc. The most efficient and fast method is by using an “in” operator which is used as a comparison operator. Here we will cover different approaches like:
Using the if... in
Checking using the split() method
Using find() method
Using “count()” method
Using the index() method
Using __contains__” magic class.
Using regular expressions
Python3
# Take input from usersMyString1 = "A geek in need is a geek indeed" if "need" in MyString1: print("Yes! it is present in the string")else: print("No! it is not present")
Output:
Yes! it is present in the string
Checking if a substring is present in the given string or not without using any inbuilt function. First split the given string into words and store them in a variable s then using the if condition, check if a substring is present in the given string or not.
Python3
# Python code# To check if a substring is present in a given string or not # input strings str1 and substrstring = "geeks for geeks" # or string=input() -> taking input from the usersubstring = "geeks" # or substring=input() # splitting words in a given strings = string.split() # checking condition# if substring is present in the given string then it gives output as yesif substring in s: print("yes")else: print("no")
Output:
yes
We can iteratively check for every word, but Python provides us an inbuilt function find() which checks if a substring is present in the string, which is done in one line. find() function returns -1 if it is not found, else it returns the first occurrence, so using this function this problem can be solved.
Python3
# function to check if small string is# there in big string def check(string, sub_str): if (string.find(sub_str) == -1): print("NO") else: print("YES") # driver codestring = "geeks for geeks"sub_str = "geek"check(string, sub_str)
Output:
YES
You can also count the number of occurrences of a specific substring in a string, then you can use the Python count() method. If the substring is not found then “yes ” will print otherwise “no will be printed”.
Python3
def check(s2, s1): if (s2.count(s1) > 0): print("YES") else: print("NO") s2 = "A geek in need is a geek indeed"s1 = "geeks"check(s2, s1)
Output:
Yes
The .index() method returns the starting index of the substring passed as a parameter. Here “substring” is present at index 16.
Python3
any_string = "Geeks for Geeks substring "start = 0end = 1000any_string.index('substring', start, end)
Output:
16
Python String __contains__(). This method is used to check if the string is present in the other string or not.
Python3
a = ['Geeks-13', 'for-56', 'Geeks-78', 'xyz-46']for i in a: if i.__contains__("Geeks"): print(f"Yes! {i} is containing.")
Output:
Yes! Geeks-13 is containing.
Yes! Geeks-78 is containing.
RegEx can be used to check if a string contains the specified search pattern. Python has a built-in package called re, which can be used to work with Regular Expressions.
Python3
# When you have imported the re module,# you can start using regular expressions.import re # Take input from usersMyString1 = "A geek in need is a geek indeed"MyString2 = "geeks" # re.search() returns a Match object# if there is a match anywhere in the stringif re.search(MyString2, MyString1): print("YES,string '{0}' is present in string '{1}'" .format( MyString2, MyString1))else: print("NO,string '{0}' is not present in string '{1}' " .format( MyString2, MyString1))
Output:
NO,string 'geeks' is not present in string 'A geek in need is a geek indeed'
Divyu_Pandey
rachitggupta2
tusharvickey1999
laxmigangarajula03
riya55
surajkumarguptaintern
Python string-programs
Python
Strings
Strings
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
How to Install PIP on Windows ?
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Different Methods to Reverse a String in C++
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n24 Jun, 2022"
},
{
"code": null,
"e": 167,
"s": 53,
"text": "In this article, we will cover how to check if a Python string contains another string or a substring in Python. "
},
{
"code": null,
"e": 245,
"s": 167,
"text": "Given two strings, check if a substring is there in the given string or not. "
},
{
"code": null,
"e": 421,
"s": 245,
"text": "Example 1: Input : Substring = \"geeks\" \n String=\"geeks for geeks\"\nOutput : yes\nExample 2: Input : Substring = \"geek\"\n String=\"geeks for geeks\"\nOutput : yes"
},
{
"code": null,
"e": 741,
"s": 421,
"text": "Yes, Checking a substring is one of the most used tasks in python. Python uses many methods to check a string containing a substring like, find(), index(), count(), etc. The most efficient and fast method is by using an “in” operator which is used as a comparison operator. Here we will cover different approaches like:"
},
{
"code": null,
"e": 761,
"s": 741,
"text": "Using the if... in "
},
{
"code": null,
"e": 795,
"s": 761,
"text": "Checking using the split() method"
},
{
"code": null,
"e": 815,
"s": 795,
"text": "Using find() method"
},
{
"code": null,
"e": 838,
"s": 815,
"text": "Using “count()” method"
},
{
"code": null,
"e": 863,
"s": 838,
"text": "Using the index() method"
},
{
"code": null,
"e": 897,
"s": 863,
"text": "Using __contains__” magic class."
},
{
"code": null,
"e": 924,
"s": 897,
"text": "Using regular expressions "
},
{
"code": null,
"e": 932,
"s": 924,
"text": "Python3"
},
{
"code": "# Take input from usersMyString1 = \"A geek in need is a geek indeed\" if \"need\" in MyString1: print(\"Yes! it is present in the string\")else: print(\"No! it is not present\")",
"e": 1109,
"s": 932,
"text": null
},
{
"code": null,
"e": 1117,
"s": 1109,
"text": "Output:"
},
{
"code": null,
"e": 1150,
"s": 1117,
"text": "Yes! it is present in the string"
},
{
"code": null,
"e": 1408,
"s": 1150,
"text": "Checking if a substring is present in the given string or not without using any inbuilt function. First split the given string into words and store them in a variable s then using the if condition, check if a substring is present in the given string or not."
},
{
"code": null,
"e": 1416,
"s": 1408,
"text": "Python3"
},
{
"code": "# Python code# To check if a substring is present in a given string or not # input strings str1 and substrstring = \"geeks for geeks\" # or string=input() -> taking input from the usersubstring = \"geeks\" # or substring=input() # splitting words in a given strings = string.split() # checking condition# if substring is present in the given string then it gives output as yesif substring in s: print(\"yes\")else: print(\"no\")",
"e": 1845,
"s": 1416,
"text": null
},
{
"code": null,
"e": 1853,
"s": 1845,
"text": "Output:"
},
{
"code": null,
"e": 1857,
"s": 1853,
"text": "yes"
},
{
"code": null,
"e": 2166,
"s": 1857,
"text": "We can iteratively check for every word, but Python provides us an inbuilt function find() which checks if a substring is present in the string, which is done in one line. find() function returns -1 if it is not found, else it returns the first occurrence, so using this function this problem can be solved. "
},
{
"code": null,
"e": 2174,
"s": 2166,
"text": "Python3"
},
{
"code": "# function to check if small string is# there in big string def check(string, sub_str): if (string.find(sub_str) == -1): print(\"NO\") else: print(\"YES\") # driver codestring = \"geeks for geeks\"sub_str = \"geek\"check(string, sub_str)",
"e": 2426,
"s": 2174,
"text": null
},
{
"code": null,
"e": 2434,
"s": 2426,
"text": "Output:"
},
{
"code": null,
"e": 2438,
"s": 2434,
"text": "YES"
},
{
"code": null,
"e": 2649,
"s": 2438,
"text": "You can also count the number of occurrences of a specific substring in a string, then you can use the Python count() method. If the substring is not found then “yes ” will print otherwise “no will be printed”."
},
{
"code": null,
"e": 2657,
"s": 2649,
"text": "Python3"
},
{
"code": "def check(s2, s1): if (s2.count(s1) > 0): print(\"YES\") else: print(\"NO\") s2 = \"A geek in need is a geek indeed\"s1 = \"geeks\"check(s2, s1)",
"e": 2815,
"s": 2657,
"text": null
},
{
"code": null,
"e": 2823,
"s": 2815,
"text": "Output:"
},
{
"code": null,
"e": 2827,
"s": 2823,
"text": "Yes"
},
{
"code": null,
"e": 2955,
"s": 2827,
"text": "The .index() method returns the starting index of the substring passed as a parameter. Here “substring” is present at index 16."
},
{
"code": null,
"e": 2963,
"s": 2955,
"text": "Python3"
},
{
"code": "any_string = \"Geeks for Geeks substring \"start = 0end = 1000any_string.index('substring', start, end)",
"e": 3065,
"s": 2963,
"text": null
},
{
"code": null,
"e": 3073,
"s": 3065,
"text": "Output:"
},
{
"code": null,
"e": 3076,
"s": 3073,
"text": "16"
},
{
"code": null,
"e": 3189,
"s": 3076,
"text": "Python String __contains__(). This method is used to check if the string is present in the other string or not. "
},
{
"code": null,
"e": 3197,
"s": 3189,
"text": "Python3"
},
{
"code": "a = ['Geeks-13', 'for-56', 'Geeks-78', 'xyz-46']for i in a: if i.__contains__(\"Geeks\"): print(f\"Yes! {i} is containing.\")",
"e": 3329,
"s": 3197,
"text": null
},
{
"code": null,
"e": 3337,
"s": 3329,
"text": "Output:"
},
{
"code": null,
"e": 3395,
"s": 3337,
"text": "Yes! Geeks-13 is containing.\nYes! Geeks-78 is containing."
},
{
"code": null,
"e": 3567,
"s": 3395,
"text": "RegEx can be used to check if a string contains the specified search pattern. Python has a built-in package called re, which can be used to work with Regular Expressions. "
},
{
"code": null,
"e": 3575,
"s": 3567,
"text": "Python3"
},
{
"code": "# When you have imported the re module,# you can start using regular expressions.import re # Take input from usersMyString1 = \"A geek in need is a geek indeed\"MyString2 = \"geeks\" # re.search() returns a Match object# if there is a match anywhere in the stringif re.search(MyString2, MyString1): print(\"YES,string '{0}' is present in string '{1}'\" .format( MyString2, MyString1))else: print(\"NO,string '{0}' is not present in string '{1}' \" .format( MyString2, MyString1))",
"e": 4067,
"s": 3575,
"text": null
},
{
"code": null,
"e": 4075,
"s": 4067,
"text": "Output:"
},
{
"code": null,
"e": 4153,
"s": 4075,
"text": "NO,string 'geeks' is not present in string 'A geek in need is a geek indeed' "
},
{
"code": null,
"e": 4166,
"s": 4153,
"text": "Divyu_Pandey"
},
{
"code": null,
"e": 4180,
"s": 4166,
"text": "rachitggupta2"
},
{
"code": null,
"e": 4197,
"s": 4180,
"text": "tusharvickey1999"
},
{
"code": null,
"e": 4216,
"s": 4197,
"text": "laxmigangarajula03"
},
{
"code": null,
"e": 4223,
"s": 4216,
"text": "riya55"
},
{
"code": null,
"e": 4245,
"s": 4223,
"text": "surajkumarguptaintern"
},
{
"code": null,
"e": 4268,
"s": 4245,
"text": "Python string-programs"
},
{
"code": null,
"e": 4275,
"s": 4268,
"text": "Python"
},
{
"code": null,
"e": 4283,
"s": 4275,
"text": "Strings"
},
{
"code": null,
"e": 4291,
"s": 4283,
"text": "Strings"
},
{
"code": null,
"e": 4389,
"s": 4291,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4407,
"s": 4389,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4449,
"s": 4407,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4471,
"s": 4449,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4506,
"s": 4471,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 4538,
"s": 4506,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4584,
"s": 4538,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 4609,
"s": 4584,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 4669,
"s": 4609,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 4684,
"s": 4669,
"text": "C++ Data Types"
}
] |
PHP | unlink() Function
|
23 Nov, 2020
The unlink() function is an inbuilt function in PHP which is used to delete files. It is similar to UNIX unlink() function. The $filename is sent as a parameter that needs to be deleted and the function returns True on success and false on failure.
Syntax:
unlink( $filename, $context )
Parameters: This function accepts two parameters as mentioned above and described below:
$filename: It is a mandatory parameter which specifies the filename of the file which has to be deleted.
$context: It is an optional parameter which specifies the context of the file handle which can be used to modify the nature of the stream.
Return Value: It returns True on success and False on failure.
Errors And Exception:
The unlink() function generates an E_WARNING level error on failure.
The web server user must have write permissions to the directory for using the unlink() function.
The unlink() function returns Boolean False but many times it happens that it returns a non-Boolean value which evaluates to False.
Below programs illustrate the unlink() function in PHP:
Suppose there is a file named as “gfg.txt”Program 1:
PHP
<?php// PHP program to delete a file named gfg.txt// using unlink() function $file_pointer = "gfg.txt"; // Use unlink() function to delete a fileif (!unlink($file_pointer)) { echo ("$file_pointer cannot be deleted due to an error");}else { echo ("$file_pointer has been deleted");} ?>
Output:
gfg.txt has been deleted
Program 2:
PHP
<?php// PHP program to delete a file named gfg.txt// using unlink() function $file_pointer = fopen('gfg.txt', 'w+'); // writing on a file named gfg.txtfwrite($file_pointer, 'A computer science portal for geeks!');fclose($file_pointer); // Use unlink() function to delete a fileif (!unlink($file_pointer)) { echo ("$file_pointer cannot be deleted due to an error");}else { echo ("$file_pointer has been deleted");} ?>
Output:
Warning: unlink() expects parameter 1 to be a valid path, resource
given in C:\xampp\htdocs\server.php on line 12
Resource id #3 cannot be deleted due to an error
Reference: http://php.net/manual/en/function.unlink.php
iamabhishek
arorakashish0911
simranarora5sos
PHP-file-handling
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
How to get parameters from a URL string in PHP?
Split a comma delimited string into an array in PHP
Download file from URL using PHP
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Nov, 2020"
},
{
"code": null,
"e": 277,
"s": 28,
"text": "The unlink() function is an inbuilt function in PHP which is used to delete files. It is similar to UNIX unlink() function. The $filename is sent as a parameter that needs to be deleted and the function returns True on success and false on failure."
},
{
"code": null,
"e": 285,
"s": 277,
"text": "Syntax:"
},
{
"code": null,
"e": 316,
"s": 285,
"text": "unlink( $filename, $context )\n"
},
{
"code": null,
"e": 406,
"s": 316,
"text": "Parameters: This function accepts two parameters as mentioned above and described below: "
},
{
"code": null,
"e": 511,
"s": 406,
"text": "$filename: It is a mandatory parameter which specifies the filename of the file which has to be deleted."
},
{
"code": null,
"e": 650,
"s": 511,
"text": "$context: It is an optional parameter which specifies the context of the file handle which can be used to modify the nature of the stream."
},
{
"code": null,
"e": 713,
"s": 650,
"text": "Return Value: It returns True on success and False on failure."
},
{
"code": null,
"e": 735,
"s": 713,
"text": "Errors And Exception:"
},
{
"code": null,
"e": 804,
"s": 735,
"text": "The unlink() function generates an E_WARNING level error on failure."
},
{
"code": null,
"e": 902,
"s": 804,
"text": "The web server user must have write permissions to the directory for using the unlink() function."
},
{
"code": null,
"e": 1034,
"s": 902,
"text": "The unlink() function returns Boolean False but many times it happens that it returns a non-Boolean value which evaluates to False."
},
{
"code": null,
"e": 1090,
"s": 1034,
"text": "Below programs illustrate the unlink() function in PHP:"
},
{
"code": null,
"e": 1143,
"s": 1090,
"text": "Suppose there is a file named as “gfg.txt”Program 1:"
},
{
"code": null,
"e": 1147,
"s": 1143,
"text": "PHP"
},
{
"code": "<?php// PHP program to delete a file named gfg.txt// using unlink() function $file_pointer = \"gfg.txt\"; // Use unlink() function to delete a fileif (!unlink($file_pointer)) { echo (\"$file_pointer cannot be deleted due to an error\");}else { echo (\"$file_pointer has been deleted\");} ?>",
"e": 1438,
"s": 1147,
"text": null
},
{
"code": null,
"e": 1447,
"s": 1438,
"text": "Output: "
},
{
"code": null,
"e": 1473,
"s": 1447,
"text": "gfg.txt has been deleted\n"
},
{
"code": null,
"e": 1484,
"s": 1473,
"text": "Program 2:"
},
{
"code": null,
"e": 1488,
"s": 1484,
"text": "PHP"
},
{
"code": "<?php// PHP program to delete a file named gfg.txt// using unlink() function $file_pointer = fopen('gfg.txt', 'w+'); // writing on a file named gfg.txtfwrite($file_pointer, 'A computer science portal for geeks!');fclose($file_pointer); // Use unlink() function to delete a fileif (!unlink($file_pointer)) { echo (\"$file_pointer cannot be deleted due to an error\");}else { echo (\"$file_pointer has been deleted\");} ?>",
"e": 1916,
"s": 1488,
"text": null
},
{
"code": null,
"e": 1925,
"s": 1916,
"text": "Output: "
},
{
"code": null,
"e": 2089,
"s": 1925,
"text": "Warning: unlink() expects parameter 1 to be a valid path, resource\ngiven in C:\\xampp\\htdocs\\server.php on line 12\nResource id #3 cannot be deleted due to an error\n"
},
{
"code": null,
"e": 2146,
"s": 2089,
"text": "Reference: http://php.net/manual/en/function.unlink.php "
},
{
"code": null,
"e": 2158,
"s": 2146,
"text": "iamabhishek"
},
{
"code": null,
"e": 2175,
"s": 2158,
"text": "arorakashish0911"
},
{
"code": null,
"e": 2191,
"s": 2175,
"text": "simranarora5sos"
},
{
"code": null,
"e": 2209,
"s": 2191,
"text": "PHP-file-handling"
},
{
"code": null,
"e": 2222,
"s": 2209,
"text": "PHP-function"
},
{
"code": null,
"e": 2226,
"s": 2222,
"text": "PHP"
},
{
"code": null,
"e": 2243,
"s": 2226,
"text": "Web Technologies"
},
{
"code": null,
"e": 2247,
"s": 2243,
"text": "PHP"
},
{
"code": null,
"e": 2345,
"s": 2247,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2385,
"s": 2345,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 2430,
"s": 2385,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 2478,
"s": 2430,
"text": "How to get parameters from a URL string in PHP?"
},
{
"code": null,
"e": 2530,
"s": 2478,
"text": "Split a comma delimited string into an array in PHP"
},
{
"code": null,
"e": 2563,
"s": 2530,
"text": "Download file from URL using PHP"
},
{
"code": null,
"e": 2596,
"s": 2563,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2658,
"s": 2596,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2719,
"s": 2658,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2769,
"s": 2719,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Java Examples - Producer Consumer Problem
|
How to solve the producer consumer problem using thread?
Following example demonstrates how to solve the producer consumer problem using thread.
public class ProducerConsumerTest {
public static void main(String[] args) {
CubbyHole c = new CubbyHole();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();
c1.start();
}
}
class CubbyHole {
private int contents;
private boolean available = false;
public synchronized int get() {
while (available == false) {
try {
wait();
} catch (InterruptedException e) {}
}
available = false;
notifyAll();
return contents;
}
public synchronized void put(int value) {
while (available == true) {
try {
wait();
} catch (InterruptedException e) { }
}
contents = value;
available = true;
notifyAll();
}
}
class Consumer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Consumer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
int value = 0;
for (int i = 0; i < 10; i++) {
value = cubbyhole.get();
System.out.println("Consumer #" + this.number + " got: " + value);
}
}
}
class Producer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Producer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
for (int i = 0; i < 10; i++) {
cubbyhole.put(i);
System.out.println("Producer #" + this.number + " put: " + i);
try {
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) { }
}
}
}
The above code sample will produce the following result.
Producer #1 put: 0
Consumer #1 got: 0
Producer #1 put: 1
Consumer #1 got: 1
Producer #1 put: 2
Consumer #1 got: 2
Producer #1 put: 3
Consumer #1 got: 3
Producer #1 put: 4
Consumer #1 got: 4
Producer #1 put: 5
Consumer #1 got: 5
Producer #1 put: 6
Consumer #1 got: 6
Producer #1 put: 7
Consumer #1 got: 7
Producer #1 put: 8
Consumer #1 got: 8
Producer #1 put: 9
Consumer #1 got: 9
|
[
{
"code": null,
"e": 2259,
"s": 2202,
"text": "How to solve the producer consumer problem using thread?"
},
{
"code": null,
"e": 2347,
"s": 2259,
"text": "Following example demonstrates how to solve the producer consumer problem using thread."
},
{
"code": null,
"e": 4015,
"s": 2347,
"text": "public class ProducerConsumerTest {\n public static void main(String[] args) {\n CubbyHole c = new CubbyHole();\n Producer p1 = new Producer(c, 1);\n Consumer c1 = new Consumer(c, 1);\n p1.start(); \n c1.start();\n }\n}\nclass CubbyHole {\n private int contents;\n private boolean available = false;\n \n public synchronized int get() {\n while (available == false) {\n try {\n wait();\n } catch (InterruptedException e) {}\n }\n available = false;\n notifyAll();\n return contents;\n }\n public synchronized void put(int value) {\n while (available == true) {\n try {\n wait();\n } catch (InterruptedException e) { } \n }\n contents = value;\n available = true;\n notifyAll();\n }\n}\nclass Consumer extends Thread {\n private CubbyHole cubbyhole;\n private int number;\n \n public Consumer(CubbyHole c, int number) {\n cubbyhole = c;\n this.number = number;\n }\n public void run() {\n int value = 0;\n for (int i = 0; i < 10; i++) {\n value = cubbyhole.get();\n System.out.println(\"Consumer #\" + this.number + \" got: \" + value);\n }\n }\n}\nclass Producer extends Thread {\n private CubbyHole cubbyhole;\n private int number;\n public Producer(CubbyHole c, int number) {\n cubbyhole = c;\n this.number = number;\n } \n public void run() {\n for (int i = 0; i < 10; i++) {\n cubbyhole.put(i);\n System.out.println(\"Producer #\" + this.number + \" put: \" + i);\n try {\n sleep((int)(Math.random() * 100));\n } catch (InterruptedException e) { }\n } \n }\n} "
},
{
"code": null,
"e": 4072,
"s": 4015,
"text": "The above code sample will produce the following result."
}
] |
Cisco Router modes
|
09 Nov, 2021
A router is a layer 3 device used to forward packets from one network to another. It forwards the packet through one of its ports on the basis of destination IP address and the entry in the routing table. By using a routing table, it finds an optimized path between the source and destination network.
Let’s discuss the Cisco router’s different modes.
Modes of router – There are mainly 5 modes in the router:
User execution mode – As soon as the interface up message appears and press enter, the router> prompt will pop up. This is called user execution mode. This mode is limited to some monitoring commands. Privileged mode – As we type enable to user mode, we enter into Privileged mode where we can view and change the configuration of the router. Different commands like show running-configuration, show IP interface brief, etc can run on this mode which is used for troubleshooting purposes. Global configuration mode – As we type configure terminal to the user mode, we will enter into the global configuration mode. Commands entered in these modes are called global commands and they affect the running configuration of the router. In this mode, a different configuration like making a local database on the router by providing username and password can set enable and secret password, etc. Interface configuration mode – In this mode, only the configuration of interfaces is done. Assigning an IP address to an interface, bringing up the interface are the common tasks done in this mode. ROMMON mode – We can enter this mode when we interrupt the boot process of the router. Generally, we enter in this mode while the password recovery process or Backing up of IOS on devices like TFTP server. It is like the BIOS mode of a PC.
User execution mode – As soon as the interface up message appears and press enter, the router> prompt will pop up. This is called user execution mode. This mode is limited to some monitoring commands.
Privileged mode – As we type enable to user mode, we enter into Privileged mode where we can view and change the configuration of the router. Different commands like show running-configuration, show IP interface brief, etc can run on this mode which is used for troubleshooting purposes.
Global configuration mode – As we type configure terminal to the user mode, we will enter into the global configuration mode. Commands entered in these modes are called global commands and they affect the running configuration of the router. In this mode, a different configuration like making a local database on the router by providing username and password can set enable and secret password, etc.
Interface configuration mode – In this mode, only the configuration of interfaces is done. Assigning an IP address to an interface, bringing up the interface are the common tasks done in this mode.
ROMMON mode – We can enter this mode when we interrupt the boot process of the router. Generally, we enter in this mode while the password recovery process or Backing up of IOS on devices like TFTP server. It is like the BIOS mode of a PC.
Entering and exiting in different modes:
Configuration – The user execution mode:
router>
Entering into privilege mode from user execution mode:
router>enable
router#
Exiting from privilege mode to user execution mode:
router#disable
router>
Entering in global configuration mode from privilege mode:
router#configure terminal
router(config)#
Exiting from global configuration mode to privilege mode:
router(config)#exit
router#
Entering into interface mode from global configuration mode. Here we have to specify the router’s interface.
router(config)#interface fa0/0
router(config-if)#
Exiting from interface mode to global configuration mode.
router(config-if)#exit
router(config)#
Exiting from interface mode to privilege mode.
router(config-if)#end
router#
Entering into ROMMON mode from privilege mode.
router#reload
gulshankumarar231
Pushpender007
23603vaibhav2021
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Nov, 2021"
},
{
"code": null,
"e": 355,
"s": 52,
"text": "A router is a layer 3 device used to forward packets from one network to another. It forwards the packet through one of its ports on the basis of destination IP address and the entry in the routing table. By using a routing table, it finds an optimized path between the source and destination network. "
},
{
"code": null,
"e": 406,
"s": 355,
"text": "Let’s discuss the Cisco router’s different modes. "
},
{
"code": null,
"e": 466,
"s": 406,
"text": "Modes of router – There are mainly 5 modes in the router: "
},
{
"code": null,
"e": 1800,
"s": 466,
"text": "User execution mode – As soon as the interface up message appears and press enter, the router> prompt will pop up. This is called user execution mode. This mode is limited to some monitoring commands. Privileged mode – As we type enable to user mode, we enter into Privileged mode where we can view and change the configuration of the router. Different commands like show running-configuration, show IP interface brief, etc can run on this mode which is used for troubleshooting purposes. Global configuration mode – As we type configure terminal to the user mode, we will enter into the global configuration mode. Commands entered in these modes are called global commands and they affect the running configuration of the router. In this mode, a different configuration like making a local database on the router by providing username and password can set enable and secret password, etc. Interface configuration mode – In this mode, only the configuration of interfaces is done. Assigning an IP address to an interface, bringing up the interface are the common tasks done in this mode. ROMMON mode – We can enter this mode when we interrupt the boot process of the router. Generally, we enter in this mode while the password recovery process or Backing up of IOS on devices like TFTP server. It is like the BIOS mode of a PC. "
},
{
"code": null,
"e": 2003,
"s": 1800,
"text": "User execution mode – As soon as the interface up message appears and press enter, the router> prompt will pop up. This is called user execution mode. This mode is limited to some monitoring commands. "
},
{
"code": null,
"e": 2293,
"s": 2003,
"text": "Privileged mode – As we type enable to user mode, we enter into Privileged mode where we can view and change the configuration of the router. Different commands like show running-configuration, show IP interface brief, etc can run on this mode which is used for troubleshooting purposes. "
},
{
"code": null,
"e": 2696,
"s": 2293,
"text": "Global configuration mode – As we type configure terminal to the user mode, we will enter into the global configuration mode. Commands entered in these modes are called global commands and they affect the running configuration of the router. In this mode, a different configuration like making a local database on the router by providing username and password can set enable and secret password, etc. "
},
{
"code": null,
"e": 2896,
"s": 2696,
"text": "Interface configuration mode – In this mode, only the configuration of interfaces is done. Assigning an IP address to an interface, bringing up the interface are the common tasks done in this mode. "
},
{
"code": null,
"e": 3138,
"s": 2896,
"text": "ROMMON mode – We can enter this mode when we interrupt the boot process of the router. Generally, we enter in this mode while the password recovery process or Backing up of IOS on devices like TFTP server. It is like the BIOS mode of a PC. "
},
{
"code": null,
"e": 3180,
"s": 3138,
"text": "Entering and exiting in different modes: "
},
{
"code": null,
"e": 3223,
"s": 3180,
"text": "Configuration – The user execution mode: "
},
{
"code": null,
"e": 3231,
"s": 3223,
"text": "router>"
},
{
"code": null,
"e": 3288,
"s": 3231,
"text": "Entering into privilege mode from user execution mode: "
},
{
"code": null,
"e": 3311,
"s": 3288,
"text": "router>enable\nrouter# "
},
{
"code": null,
"e": 3365,
"s": 3311,
"text": "Exiting from privilege mode to user execution mode: "
},
{
"code": null,
"e": 3388,
"s": 3365,
"text": "router#disable\nrouter>"
},
{
"code": null,
"e": 3449,
"s": 3388,
"text": "Entering in global configuration mode from privilege mode: "
},
{
"code": null,
"e": 3491,
"s": 3449,
"text": "router#configure terminal\nrouter(config)#"
},
{
"code": null,
"e": 3551,
"s": 3491,
"text": "Exiting from global configuration mode to privilege mode: "
},
{
"code": null,
"e": 3579,
"s": 3551,
"text": "router(config)#exit\nrouter#"
},
{
"code": null,
"e": 3690,
"s": 3579,
"text": "Entering into interface mode from global configuration mode. Here we have to specify the router’s interface. "
},
{
"code": null,
"e": 3740,
"s": 3690,
"text": "router(config)#interface fa0/0\nrouter(config-if)#"
},
{
"code": null,
"e": 3800,
"s": 3740,
"text": "Exiting from interface mode to global configuration mode. "
},
{
"code": null,
"e": 3839,
"s": 3800,
"text": "router(config-if)#exit\nrouter(config)#"
},
{
"code": null,
"e": 3888,
"s": 3839,
"text": "Exiting from interface mode to privilege mode. "
},
{
"code": null,
"e": 3918,
"s": 3888,
"text": "router(config-if)#end\nrouter#"
},
{
"code": null,
"e": 3966,
"s": 3918,
"text": "Entering into ROMMON mode from privilege mode. "
},
{
"code": null,
"e": 3980,
"s": 3966,
"text": "router#reload"
},
{
"code": null,
"e": 3998,
"s": 3980,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 4012,
"s": 3998,
"text": "Pushpender007"
},
{
"code": null,
"e": 4029,
"s": 4012,
"text": "23603vaibhav2021"
},
{
"code": null,
"e": 4047,
"s": 4029,
"text": "Computer Networks"
},
{
"code": null,
"e": 4065,
"s": 4047,
"text": "Computer Networks"
}
] |
Program for Stair Case Patterns
|
23 Nov, 2021
Programs to print following pattern.Examples:
Input : 6
Output :
* *
* *
* * * *
* * * *
* * * * * *
* * * * * *
C++
Java
Python3
C#
PHP
Javascript
// CPP program to print stair case pattern.#include <iostream> using namespace std; // Function definitionvoid pattern(int n){ // for loop for rows for (int i = 1; i <= n; i++) { // conditional operator int k = (i % 2 != 0) ? i + 1 : i; // according to value of k carry // out further operation for (int j = 0; j < k; j++) cout << " * "; cout << endl; }} // Driver codeint main(){ int n = 6; pattern(n); return 0;}
// Java program to print// stair case pattern.import java.io.*; class GFG { // Function definition static void pattern(int n) { // for loop for rows for (int i = 1; i <= n; i++) { // conditional operator int k ; if(i % 2 != 0) k = i + 1 ; else k = i ; // according to value of k carry // out further operation for (int j = 0; j < k; j++) System.out.print(" * "); System.out.println(); } } // Driver code public static void main(String args[]) { int n = 6; pattern(n); }} /*This code is contributed by Nikita Tiwari.*/
# Python3 program to print stair case pattern. # Function definitiondef pattern(n): # for loop for rows for i in range(1, n + 1): # conditional operator k = i + 1 if (i % 2 != 0) else i # according to value of k carry # out further operation for j in range(0, k): if j == k - 1: print(" * ") else: print(" * ", end = " ") # Driver coden = 6pattern(n) # This code is contributed by Smitha Dinesh Semwal
// C# program to print stair case pattern.using System; class GFG { // Function definition static void pattern(int n) { // for loop for rows for (int i = 1; i <= n; i++) { // conditional operator int k ; if(i % 2 != 0) k = i + 1 ; else k = i ; // according to value of k carry // out further operation for (int j = 0; j < k; j++) Console.Write(" * "); Console.WriteLine(); } } // Driver code public static void Main() { int n = 6; pattern(n); }} // This code is contributed by nitin mittal.
<?php// PHP program to print// stair case pattern. // Function definitionfunction pattern($n){ // for loop for rows for ($i = 1; $i <= $n; $i++) { // conditional operator $k = ($i % 2 != 0) ? $i + 1 : $i; // according to value // of k carry out // further operation for ($j = 0; $j < $k; $j++) echo " * "; echo"\n"; }} // Driver code$n = 6;pattern($n); // This code is contributed// by anuj_67.?>
<script>// Javascript program to print// stair case pattern. // Function definition function pattern( n) { // for loop for rows for ( i = 1; i <= n; i++) { // conditional operator let k; if (i % 2 != 0) k = i + 1; else k = i; // according to value of k carry // out further operation for ( j = 0; j < k; j++) document.write(" * "); document.write("<br/>"); } } // Driver code let n = 6; pattern(n); // This code is contributed by gauravrajput1 </script>
Output:
* *
* *
* * * *
* * * *
* * * * * *
* * * * * *
Program to print following pattern.Examples:
Input : 6
Output :
* *
* *
* * * *
* * * *
* * * * * *
* * * * * *
C++
Java
Python3
C#
PHP
Javascript
// C++ Program for Stair Case Patterns#include <iostream> using namespace std; // Function definitionvoid pattern(int n){ // for loop for rows for (int i = 1; i <= n; i++) { // conditional operator int k = (i % 2 != 0) ? i + 1 : i; // for loop for printing spaces for (int g = n; g > k; g--) cout << " "; // according to value of k carry // out further operation for (int j = 0; j < k; j++) cout << "* "; cout << endl; }} // Driver codeint main(){ int n = 6; pattern(n); return 0;}
// Java code for above// Stair Case Patternsimport java.io.*; class GFG { // Function definition static void pattern(int n) { // for loop for rows for (int i = 1; i <= n; i++) { // conditional operator int k; if(i % 2 != 0) k = i + 1 ; else k = i; // for loop for printing spaces for (int g = n; g > k; g--) System.out.print(" "); // according to value of k carry // out further operation for (int j = 0; j < k; j++) System.out.print("* "); System.out.println(); } } // Driver code public static void main(String args[]) { int n = 6; pattern(n); }} /*This code is contributed by Nikita Tiwari.*/
# Python 3 program to# print above pattern # Function definitiondef pattern(n) : # for loop for rows for i in range(1,n+1) : # conditional operator if(i % 2 != 0) : k = i + 1 else : k = i # for loop for printing spaces for g in range(n ,k,-1) : print(" ",end="") # according to value of k carry # out further operation for j in range( 0, k): print("* ",end="") print() # Driver Coden = 6pattern(n) #This code is contributed by Nikita Tiwari.
// C# code for above// Stair Case Patternsusing System; class GFG{ // Function definitionstatic void pattern(int n){ // for loop for rows for (int i = 1; i <= n; i++) { // conditional operator int k; if(i % 2 != 0) k = i + 1 ; else k = i; // for loop for // printing spaces for (int g = n; g > k; g--) Console.Write(" "); // according to value of // k carry out further // operation for (int j = 0; j < k; j++) Console.Write("* "); Console.WriteLine(); }} // Driver codepublic static void Main(){ int n = 6; pattern(n);}} // This code is contributed by anuj_67.
<?php// PHP code for above// Stair Case Pattern // Function definitionfunction pattern($n){ // for loop for rows for ($i = 1; $i <= $n; $i++) { // conditional operator $k = ($i % 2 != 0) ? $i + 1 : $i; // for loop for printing spaces for ($g = $n; $g > $k; $g--) echo " "; // according to value of k carry // out further operation for ($j = 0; $j < $k; $j++) echo " *"; echo "\n"; }} // Driver code$n = 6;pattern($n); // This code is contributed// by Akanksha Rai(Abby_akku)?>
<script> // JavaScript code for above// Stair Case Patterns // Function definition function pattern(n) { // for loop for rows for (i = 1; i <= n; i++) { // conditional operator var k; if (i % 2 != 0) k = i + 1; else k = i; // for loop for printing spaces for (g = n; g > k; g--) document.write(" "); // according to value of k carry // out further operation for (j = 0; j < k; j++) document.write("* "); document.write("<br/>"); } } // Driver code var n = 6; pattern(n); // This code is contributed by aashish1995 </script>
Output:
* *
* *
* * * *
* * * *
* * * * * *
* * * * * *
Program to print following pattern.Examples:
Input : 6
Output :
* * * * * *
* * * * * *
* * * *
* * * *
* *
* *
C++
Java
Python 3
C#
PHP
Javascript
// C++ program for above// Stair Case Patterns#include <iostream> using namespace std; // Function definitionvoid pattern(int n){ // for loop for rows for (int i = n; i > 0; i--) { // conditional operator int k = (i % 2 != 0) ? i + 1 : i; // according to value of k carry // out further operation for (int j = 0; j < k; j++) cout << " * "; cout << endl; }} // Driver codeint main(){ int n = 6; pattern(n); return 0;}
// java Program for print the above patternimport java.io.*; class GFG { // Function definition static void pattern(int n) { // for loop for rows for (int i = n; i > 0; i--) { // conditional operator int k; if (i % 2 != 0) k = i + 1; else k = i; // according to value of k carry // out further operation for (int j = 0; j < k; j++) System.out.print(" * "); System.out.println(); } } // Driver code public static void main(String args[]) { int n = 6; pattern(n); }} /* This code is contributed by Nikita Tiwari.*/
# Python 3 Program for print the above pattern# Function definitiondef pattern(n) : # for loop for rows for i in range(n,0,-1) : # conditional operator if(i % 2 != 0) : k = i + 1 else : k = i # for loop for printing spaces for g in range(n, k) : print(" ",end="") # according to value of k carry # out further operation for j in range(0, k) : print(" * ",end="") print() # Driver coden = 6pattern(n) #This code is contributed by Nikita Tiwari.
// C# Program for print// above stair case patternusing System; class GFG{ // Function definitionstatic void pattern(int n){ // for loop for rows for (int i = n; i > 0; i--) { // conditional operator int k; if (i % 2 != 0) k = i + 1; else k = i; // according to value // of k carry out // further operation for (int j = 0; j < k; j++) Console.Write(" * "); Console.WriteLine(); }} // Driver codepublic static void Main(){ int n = 6; pattern(n);}} // This code is contributed// by anuj_67.
<?php// PHP Program for print// above stair case pattern // Function definitionfunction pattern($n){ // for loop for rows for ($i = $n; $i > 0; $i--) { // conditional operator $k = ($i % 2 != 0) ? $i + 1 : $i; // according to value // of k carry out // further operation for ($j = 0; $j < $k; $j++) echo("* "); echo("\n"); }} // Driver code$n = 6;pattern($n); // This code is contributed// by Smitha ?>
<script>// javascript Program for print the above pattern // Function definition function pattern(n) { // for loop for rows for (var i = n; i > 0; i--) { // conditional operator var k; if (i % 2 != 0) k = i + 1; else k = i; // according to value of k carry // out further operation for (var j = 0; j < k; j++) document.write(" * "); document.write("<br/>"); } } // Driver code var n = 6; pattern(n); // This code contributed by gauravrajput1</script>
Output:
* * * * * *
* * * * * *
* * * *
* * * *
* *
* *
Program to print following pattern.Examples:
Input : 6
Output :
* * * * * *
* * * * * *
* * * *
* * * *
* *
* *
C++
Java
Python3
C#
PHP
Javascript
// C++ program to// print above pattern.#include <iostream> using namespace std; // Function definitionvoid pattern(int n){ // for loop for rows for (int i = n; i > 0; i--) { // conditional operator int k = (i % 2 != 0) ? i + 1 : i; // for loop for printing spaces for (int g = k; g < n; g++) cout << " "; // according to value of k carry // out further operation for (int j = 0; j < k; j++) cout << "* "; cout << endl; }} // Driver codeint main(){ int n = 6; pattern(n); return 0;}
// Java program to// print above pattern.import java.io.*; class GFG{ // Function definition static void pattern(int n) { // for loop for rows for (int i = n; i > 0; i--) { // conditional operator int k = (i % 2 != 0) ? i + 1 : i; // for loop for printing spaces for (int g = k; g < n; g++) System.out.print(" "); // according to value of k carry // out further operation for (int j = 0; j < k; j++) System.out.print("* "); System.out.println(); } } // Driver code public static void main(String args[]) { int n = 6; pattern(n); }} // This code is contributed// by Nikita Tiwari
# Python 3 program to# print above pattern. # Function definitiondef pattern(n) : # for loop for rows for i in range(n, 0, -1) : # conditional operator if(i % 2 != 0) : k = i + 1 else : k = i # for loop for printing spaces for g in range(k, n) : print(" ", end = "") # according to value of k carry # out further operation for j in range(0,k) : print("* ", end = "") print() # Driver coden = 6pattern(n) # This code is contributed# by Nikita Tiwari.
// C# program to// print above pattern.using System; class GFG{ // Function definition static void pattern(int n) { // for loop for rows for (int i = n; i > 0; i--) { // conditional operator int k = (i % 2 != 0) ? i + 1 : i; // for loop for printing spaces for (int g = k; g < n; g++) Console.Write(" "); // according to value of k carry // out further operation for (int j = 0; j < k; j++) Console.Write("* "); Console.WriteLine(); } } // Driver code public static void Main () { int n = 6; pattern(n); }} // This code is contributed by ajit
<?php// PHP program to// print above pattern. // Function definitionfunction pattern($n){ // for loop for rows for ($i = $n; $i > 0; $i--) { // conditional operator $k = ($i % 2 != 0) ? $i + 1 : $i; // for loop for // printing spaces for ($g = $k; $g < $n; $g++) echo " "; // according to value of k // carry out further operation for ($j = 0; $j < $k; $j++) echo "* "; echo "\n"; }} // Driver code$n = 6;pattern($n); // This code is contributed// by Akanksha Rai(Abby_akku)?>
<script> // Javascript program to// print above pattern. // Function definitionfunction pattern(n){ // For loop for rows for(i = n; i > 0; i--) { // conditional operator var k = (i % 2 != 0) ? i + 1 : i; // For loop for printing spaces for(g = k; g < n; g++) document.write(" "); // According to value of k carry // out further operation for(j = 0; j < k; j++) document.write("* "); document.write("<br/>"); }} // Driver codevar n = 6; pattern(n); // This code is contributed by aashish1995 </script>
Output:
* * * * * *
* * * * * *
* * * *
* * * *
* *
* *
nitin mittal
jit_t
vt_m
Smitha Dinesh Semwal
Akanksha_Rai
GauravRajput1
aashish1995
ankita_saini
pattern-printing
School Programming
pattern-printing
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Constructors in Java
Exceptions in Java
Python Exception Handling
Python Try Except
Ternary Operator in Python
How JVM Works - JVM Architecture?
Python program to add two numbers
Variables in Java
Data types in Java
Difference between Abstract Class and Interface in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Nov, 2021"
},
{
"code": null,
"e": 75,
"s": 28,
"text": "Programs to print following pattern.Examples: "
},
{
"code": null,
"e": 142,
"s": 75,
"text": "Input : 6\nOutput :\n* *\n* *\n* * * *\n* * * *\n* * * * * *\n* * * * * *"
},
{
"code": null,
"e": 146,
"s": 142,
"text": "C++"
},
{
"code": null,
"e": 151,
"s": 146,
"text": "Java"
},
{
"code": null,
"e": 159,
"s": 151,
"text": "Python3"
},
{
"code": null,
"e": 162,
"s": 159,
"text": "C#"
},
{
"code": null,
"e": 166,
"s": 162,
"text": "PHP"
},
{
"code": null,
"e": 177,
"s": 166,
"text": "Javascript"
},
{
"code": "// CPP program to print stair case pattern.#include <iostream> using namespace std; // Function definitionvoid pattern(int n){ // for loop for rows for (int i = 1; i <= n; i++) { // conditional operator int k = (i % 2 != 0) ? i + 1 : i; // according to value of k carry // out further operation for (int j = 0; j < k; j++) cout << \" * \"; cout << endl; }} // Driver codeint main(){ int n = 6; pattern(n); return 0;}",
"e": 665,
"s": 177,
"text": null
},
{
"code": "// Java program to print// stair case pattern.import java.io.*; class GFG { // Function definition static void pattern(int n) { // for loop for rows for (int i = 1; i <= n; i++) { // conditional operator int k ; if(i % 2 != 0) k = i + 1 ; else k = i ; // according to value of k carry // out further operation for (int j = 0; j < k; j++) System.out.print(\" * \"); System.out.println(); } } // Driver code public static void main(String args[]) { int n = 6; pattern(n); }} /*This code is contributed by Nikita Tiwari.*/",
"e": 1409,
"s": 665,
"text": null
},
{
"code": "# Python3 program to print stair case pattern. # Function definitiondef pattern(n): # for loop for rows for i in range(1, n + 1): # conditional operator k = i + 1 if (i % 2 != 0) else i # according to value of k carry # out further operation for j in range(0, k): if j == k - 1: print(\" * \") else: print(\" * \", end = \" \") # Driver coden = 6pattern(n) # This code is contributed by Smitha Dinesh Semwal",
"e": 1927,
"s": 1409,
"text": null
},
{
"code": "// C# program to print stair case pattern.using System; class GFG { // Function definition static void pattern(int n) { // for loop for rows for (int i = 1; i <= n; i++) { // conditional operator int k ; if(i % 2 != 0) k = i + 1 ; else k = i ; // according to value of k carry // out further operation for (int j = 0; j < k; j++) Console.Write(\" * \"); Console.WriteLine(); } } // Driver code public static void Main() { int n = 6; pattern(n); }} // This code is contributed by nitin mittal.",
"e": 2650,
"s": 1927,
"text": null
},
{
"code": "<?php// PHP program to print// stair case pattern. // Function definitionfunction pattern($n){ // for loop for rows for ($i = 1; $i <= $n; $i++) { // conditional operator $k = ($i % 2 != 0) ? $i + 1 : $i; // according to value // of k carry out // further operation for ($j = 0; $j < $k; $j++) echo \" * \"; echo\"\\n\"; }} // Driver code$n = 6;pattern($n); // This code is contributed// by anuj_67.?>",
"e": 3142,
"s": 2650,
"text": null
},
{
"code": "<script>// Javascript program to print// stair case pattern. // Function definition function pattern( n) { // for loop for rows for ( i = 1; i <= n; i++) { // conditional operator let k; if (i % 2 != 0) k = i + 1; else k = i; // according to value of k carry // out further operation for ( j = 0; j < k; j++) document.write(\" * \"); document.write(\"<br/>\"); } } // Driver code let n = 6; pattern(n); // This code is contributed by gauravrajput1 </script>",
"e": 3805,
"s": 3142,
"text": null
},
{
"code": null,
"e": 3814,
"s": 3805,
"text": "Output: "
},
{
"code": null,
"e": 3862,
"s": 3814,
"text": "* *\n* *\n* * * *\n* * * *\n* * * * * *\n* * * * * *"
},
{
"code": null,
"e": 3908,
"s": 3862,
"text": "Program to print following pattern.Examples: "
},
{
"code": null,
"e": 3993,
"s": 3908,
"text": "Input : 6\nOutput :\n * * \n * * \n * * * * \n * * * * \n* * * * * * \n* * * * * * "
},
{
"code": null,
"e": 3997,
"s": 3993,
"text": "C++"
},
{
"code": null,
"e": 4002,
"s": 3997,
"text": "Java"
},
{
"code": null,
"e": 4010,
"s": 4002,
"text": "Python3"
},
{
"code": null,
"e": 4013,
"s": 4010,
"text": "C#"
},
{
"code": null,
"e": 4017,
"s": 4013,
"text": "PHP"
},
{
"code": null,
"e": 4028,
"s": 4017,
"text": "Javascript"
},
{
"code": "// C++ Program for Stair Case Patterns#include <iostream> using namespace std; // Function definitionvoid pattern(int n){ // for loop for rows for (int i = 1; i <= n; i++) { // conditional operator int k = (i % 2 != 0) ? i + 1 : i; // for loop for printing spaces for (int g = n; g > k; g--) cout << \" \"; // according to value of k carry // out further operation for (int j = 0; j < k; j++) cout << \"* \"; cout << endl; }} // Driver codeint main(){ int n = 6; pattern(n); return 0;}",
"e": 4609,
"s": 4028,
"text": null
},
{
"code": "// Java code for above// Stair Case Patternsimport java.io.*; class GFG { // Function definition static void pattern(int n) { // for loop for rows for (int i = 1; i <= n; i++) { // conditional operator int k; if(i % 2 != 0) k = i + 1 ; else k = i; // for loop for printing spaces for (int g = n; g > k; g--) System.out.print(\" \"); // according to value of k carry // out further operation for (int j = 0; j < k; j++) System.out.print(\"* \"); System.out.println(); } } // Driver code public static void main(String args[]) { int n = 6; pattern(n); }} /*This code is contributed by Nikita Tiwari.*/",
"e": 5473,
"s": 4609,
"text": null
},
{
"code": "# Python 3 program to# print above pattern # Function definitiondef pattern(n) : # for loop for rows for i in range(1,n+1) : # conditional operator if(i % 2 != 0) : k = i + 1 else : k = i # for loop for printing spaces for g in range(n ,k,-1) : print(\" \",end=\"\") # according to value of k carry # out further operation for j in range( 0, k): print(\"* \",end=\"\") print() # Driver Coden = 6pattern(n) #This code is contributed by Nikita Tiwari.",
"e": 6079,
"s": 5473,
"text": null
},
{
"code": "// C# code for above// Stair Case Patternsusing System; class GFG{ // Function definitionstatic void pattern(int n){ // for loop for rows for (int i = 1; i <= n; i++) { // conditional operator int k; if(i % 2 != 0) k = i + 1 ; else k = i; // for loop for // printing spaces for (int g = n; g > k; g--) Console.Write(\" \"); // according to value of // k carry out further // operation for (int j = 0; j < k; j++) Console.Write(\"* \"); Console.WriteLine(); }} // Driver codepublic static void Main(){ int n = 6; pattern(n);}} // This code is contributed by anuj_67.",
"e": 6799,
"s": 6079,
"text": null
},
{
"code": "<?php// PHP code for above// Stair Case Pattern // Function definitionfunction pattern($n){ // for loop for rows for ($i = 1; $i <= $n; $i++) { // conditional operator $k = ($i % 2 != 0) ? $i + 1 : $i; // for loop for printing spaces for ($g = $n; $g > $k; $g--) echo \" \"; // according to value of k carry // out further operation for ($j = 0; $j < $k; $j++) echo \" *\"; echo \"\\n\"; }} // Driver code$n = 6;pattern($n); // This code is contributed// by Akanksha Rai(Abby_akku)?>",
"e": 7369,
"s": 6799,
"text": null
},
{
"code": "<script> // JavaScript code for above// Stair Case Patterns // Function definition function pattern(n) { // for loop for rows for (i = 1; i <= n; i++) { // conditional operator var k; if (i % 2 != 0) k = i + 1; else k = i; // for loop for printing spaces for (g = n; g > k; g--) document.write(\" \"); // according to value of k carry // out further operation for (j = 0; j < k; j++) document.write(\"* \"); document.write(\"<br/>\"); } } // Driver code var n = 6; pattern(n); // This code is contributed by aashish1995 </script>",
"e": 8121,
"s": 7369,
"text": null
},
{
"code": null,
"e": 8130,
"s": 8121,
"text": "Output: "
},
{
"code": null,
"e": 8196,
"s": 8130,
"text": " * * \n * * \n * * * * \n * * * * \n* * * * * * \n* * * * * * "
},
{
"code": null,
"e": 8242,
"s": 8196,
"text": "Program to print following pattern.Examples: "
},
{
"code": null,
"e": 8310,
"s": 8242,
"text": "Input : 6\nOutput :\n\n* * * * * *\n* * * * * *\n* * * *\n* * * *\n* *\n* *"
},
{
"code": null,
"e": 8314,
"s": 8310,
"text": "C++"
},
{
"code": null,
"e": 8319,
"s": 8314,
"text": "Java"
},
{
"code": null,
"e": 8328,
"s": 8319,
"text": "Python 3"
},
{
"code": null,
"e": 8331,
"s": 8328,
"text": "C#"
},
{
"code": null,
"e": 8335,
"s": 8331,
"text": "PHP"
},
{
"code": null,
"e": 8346,
"s": 8335,
"text": "Javascript"
},
{
"code": "// C++ program for above// Stair Case Patterns#include <iostream> using namespace std; // Function definitionvoid pattern(int n){ // for loop for rows for (int i = n; i > 0; i--) { // conditional operator int k = (i % 2 != 0) ? i + 1 : i; // according to value of k carry // out further operation for (int j = 0; j < k; j++) cout << \" * \"; cout << endl; }} // Driver codeint main(){ int n = 6; pattern(n); return 0;}",
"e": 8836,
"s": 8346,
"text": null
},
{
"code": "// java Program for print the above patternimport java.io.*; class GFG { // Function definition static void pattern(int n) { // for loop for rows for (int i = n; i > 0; i--) { // conditional operator int k; if (i % 2 != 0) k = i + 1; else k = i; // according to value of k carry // out further operation for (int j = 0; j < k; j++) System.out.print(\" * \"); System.out.println(); } } // Driver code public static void main(String args[]) { int n = 6; pattern(n); }} /* This code is contributed by Nikita Tiwari.*/",
"e": 9562,
"s": 8836,
"text": null
},
{
"code": "# Python 3 Program for print the above pattern# Function definitiondef pattern(n) : # for loop for rows for i in range(n,0,-1) : # conditional operator if(i % 2 != 0) : k = i + 1 else : k = i # for loop for printing spaces for g in range(n, k) : print(\" \",end=\"\") # according to value of k carry # out further operation for j in range(0, k) : print(\" * \",end=\"\") print() # Driver coden = 6pattern(n) #This code is contributed by Nikita Tiwari.",
"e": 10159,
"s": 9562,
"text": null
},
{
"code": "// C# Program for print// above stair case patternusing System; class GFG{ // Function definitionstatic void pattern(int n){ // for loop for rows for (int i = n; i > 0; i--) { // conditional operator int k; if (i % 2 != 0) k = i + 1; else k = i; // according to value // of k carry out // further operation for (int j = 0; j < k; j++) Console.Write(\" * \"); Console.WriteLine(); }} // Driver codepublic static void Main(){ int n = 6; pattern(n);}} // This code is contributed// by anuj_67.",
"e": 10764,
"s": 10159,
"text": null
},
{
"code": "<?php// PHP Program for print// above stair case pattern // Function definitionfunction pattern($n){ // for loop for rows for ($i = $n; $i > 0; $i--) { // conditional operator $k = ($i % 2 != 0) ? $i + 1 : $i; // according to value // of k carry out // further operation for ($j = 0; $j < $k; $j++) echo(\"* \"); echo(\"\\n\"); }} // Driver code$n = 6;pattern($n); // This code is contributed// by Smitha ?>",
"e": 11260,
"s": 10764,
"text": null
},
{
"code": "<script>// javascript Program for print the above pattern // Function definition function pattern(n) { // for loop for rows for (var i = n; i > 0; i--) { // conditional operator var k; if (i % 2 != 0) k = i + 1; else k = i; // according to value of k carry // out further operation for (var j = 0; j < k; j++) document.write(\" * \"); document.write(\"<br/>\"); } } // Driver code var n = 6; pattern(n); // This code contributed by gauravrajput1</script>",
"e": 11900,
"s": 11260,
"text": null
},
{
"code": null,
"e": 11909,
"s": 11900,
"text": "Output: "
},
{
"code": null,
"e": 11957,
"s": 11909,
"text": "* * * * * *\n* * * * * *\n* * * *\n* * * *\n* *\n* *"
},
{
"code": null,
"e": 12003,
"s": 11957,
"text": "Program to print following pattern.Examples: "
},
{
"code": null,
"e": 12089,
"s": 12003,
"text": "Input : 6\nOutput :\n\n* * * * * * \n* * * * * * \n * * * * \n * * * * \n * * \n * * "
},
{
"code": null,
"e": 12093,
"s": 12089,
"text": "C++"
},
{
"code": null,
"e": 12098,
"s": 12093,
"text": "Java"
},
{
"code": null,
"e": 12106,
"s": 12098,
"text": "Python3"
},
{
"code": null,
"e": 12109,
"s": 12106,
"text": "C#"
},
{
"code": null,
"e": 12113,
"s": 12109,
"text": "PHP"
},
{
"code": null,
"e": 12124,
"s": 12113,
"text": "Javascript"
},
{
"code": "// C++ program to// print above pattern.#include <iostream> using namespace std; // Function definitionvoid pattern(int n){ // for loop for rows for (int i = n; i > 0; i--) { // conditional operator int k = (i % 2 != 0) ? i + 1 : i; // for loop for printing spaces for (int g = k; g < n; g++) cout << \" \"; // according to value of k carry // out further operation for (int j = 0; j < k; j++) cout << \"* \"; cout << endl; }} // Driver codeint main(){ int n = 6; pattern(n); return 0;}",
"e": 12728,
"s": 12124,
"text": null
},
{
"code": "// Java program to// print above pattern.import java.io.*; class GFG{ // Function definition static void pattern(int n) { // for loop for rows for (int i = n; i > 0; i--) { // conditional operator int k = (i % 2 != 0) ? i + 1 : i; // for loop for printing spaces for (int g = k; g < n; g++) System.out.print(\" \"); // according to value of k carry // out further operation for (int j = 0; j < k; j++) System.out.print(\"* \"); System.out.println(); } } // Driver code public static void main(String args[]) { int n = 6; pattern(n); }} // This code is contributed// by Nikita Tiwari",
"e": 13496,
"s": 12728,
"text": null
},
{
"code": "# Python 3 program to# print above pattern. # Function definitiondef pattern(n) : # for loop for rows for i in range(n, 0, -1) : # conditional operator if(i % 2 != 0) : k = i + 1 else : k = i # for loop for printing spaces for g in range(k, n) : print(\" \", end = \"\") # according to value of k carry # out further operation for j in range(0,k) : print(\"* \", end = \"\") print() # Driver coden = 6pattern(n) # This code is contributed# by Nikita Tiwari.",
"e": 14111,
"s": 13496,
"text": null
},
{
"code": "// C# program to// print above pattern.using System; class GFG{ // Function definition static void pattern(int n) { // for loop for rows for (int i = n; i > 0; i--) { // conditional operator int k = (i % 2 != 0) ? i + 1 : i; // for loop for printing spaces for (int g = k; g < n; g++) Console.Write(\" \"); // according to value of k carry // out further operation for (int j = 0; j < k; j++) Console.Write(\"* \"); Console.WriteLine(); } } // Driver code public static void Main () { int n = 6; pattern(n); }} // This code is contributed by ajit",
"e": 14834,
"s": 14111,
"text": null
},
{
"code": "<?php// PHP program to// print above pattern. // Function definitionfunction pattern($n){ // for loop for rows for ($i = $n; $i > 0; $i--) { // conditional operator $k = ($i % 2 != 0) ? $i + 1 : $i; // for loop for // printing spaces for ($g = $k; $g < $n; $g++) echo \" \"; // according to value of k // carry out further operation for ($j = 0; $j < $k; $j++) echo \"* \"; echo \"\\n\"; }} // Driver code$n = 6;pattern($n); // This code is contributed// by Akanksha Rai(Abby_akku)?>",
"e": 15430,
"s": 14834,
"text": null
},
{
"code": "<script> // Javascript program to// print above pattern. // Function definitionfunction pattern(n){ // For loop for rows for(i = n; i > 0; i--) { // conditional operator var k = (i % 2 != 0) ? i + 1 : i; // For loop for printing spaces for(g = k; g < n; g++) document.write(\" \"); // According to value of k carry // out further operation for(j = 0; j < k; j++) document.write(\"* \"); document.write(\"<br/>\"); }} // Driver codevar n = 6; pattern(n); // This code is contributed by aashish1995 </script>",
"e": 16052,
"s": 15430,
"text": null
},
{
"code": null,
"e": 16061,
"s": 16052,
"text": "Output: "
},
{
"code": null,
"e": 16127,
"s": 16061,
"text": "* * * * * * \n* * * * * * \n * * * * \n * * * * \n * * \n * * "
},
{
"code": null,
"e": 16142,
"s": 16129,
"text": "nitin mittal"
},
{
"code": null,
"e": 16148,
"s": 16142,
"text": "jit_t"
},
{
"code": null,
"e": 16153,
"s": 16148,
"text": "vt_m"
},
{
"code": null,
"e": 16174,
"s": 16153,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 16187,
"s": 16174,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 16201,
"s": 16187,
"text": "GauravRajput1"
},
{
"code": null,
"e": 16213,
"s": 16201,
"text": "aashish1995"
},
{
"code": null,
"e": 16226,
"s": 16213,
"text": "ankita_saini"
},
{
"code": null,
"e": 16243,
"s": 16226,
"text": "pattern-printing"
},
{
"code": null,
"e": 16262,
"s": 16243,
"text": "School Programming"
},
{
"code": null,
"e": 16279,
"s": 16262,
"text": "pattern-printing"
},
{
"code": null,
"e": 16377,
"s": 16279,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 16398,
"s": 16377,
"text": "Constructors in Java"
},
{
"code": null,
"e": 16417,
"s": 16398,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 16443,
"s": 16417,
"text": "Python Exception Handling"
},
{
"code": null,
"e": 16461,
"s": 16443,
"text": "Python Try Except"
},
{
"code": null,
"e": 16488,
"s": 16461,
"text": "Ternary Operator in Python"
},
{
"code": null,
"e": 16522,
"s": 16488,
"text": "How JVM Works - JVM Architecture?"
},
{
"code": null,
"e": 16556,
"s": 16522,
"text": "Python program to add two numbers"
},
{
"code": null,
"e": 16574,
"s": 16556,
"text": "Variables in Java"
},
{
"code": null,
"e": 16593,
"s": 16574,
"text": "Data types in Java"
}
] |
RC5 Encryption Algorithm
|
09 Aug, 2019
RC5 is a symmetric key block encryption algorithm designed by Ron Rivest in 1994. It is notable for being simple, fast (on account of using only primitive computer operations like XOR, shift, etc.) and consumes less memory.
Example:
Key : 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Plain Text : 00000000 00000000
Cipher Text : EEDBA521 6D8F4B15
RC5 is a block cipher and addresses two word blocks at a time.Depending on input plain text block size, number of rounds and key size, various instances of RC5 can be defined and each instance is denoted as RC5-w/r/b where w=word size in bits, r=number of rounds and b=key size in bytes.Allowed values are:
Note – Since at a time, RC5 uses 2 word blocks, the plain text block size can be 32, 64 or 128 bits.
Notation used in the algorithm:
Step-1: Initialization of constants P and Q.RC5 makes use of 2 magic constants P and Q whose value is defined by the word size w.
For any other word size, P and Q can be determined as:
P = Odd((e-2))
Q = Odd((-2))
Here, Odd(x) is the odd integer nearest to x, e is the base of natural logarithms and is the golden ratio.
Step-2: Converting secret key K from bytes to words.Secret key K of size b bytes is used to initialize array L consisting of c words where c = b/u, u = w/8 and w = word size used for that particular instance of RC5. For example, if we choose w=32 bits and Key k is of size 96 bytes then, u=32/8=4, c=b/u=96/4=24.L is pre initialized to 0 value before adding secret key K to it.
for i=b-1 to 0
L[i/u] = (L[u/i] <<< 8) + K[i]
Step-3: Initializing sub-key S.Sub-key S of size t=2(r+1) is initialized using magic constants P and Q.
S[0] = P
for i = 1 to 2(r+1)-1
S[i] = S[i-1] + Q)
Step-4: Sub-key mixing.The RC5 encryption algorithm uses Sub key S. L is merely, a temporary array formed on the basis of user entered secret key.Mix in user’s secret key with S and L.
i = j = 0
A = B = 0
do 3 * max(t, c) times:
A = S[i] = (S[i] + A + B) <<< 3
B = L[j] = (L[j] + A + B) <<< (A + B)
i = (i + 1) % t
j = (j + 1) % c
Step-5: Encryption.We divide the input plain text block into two registers A and B each of size w bits. After undergoing the encryption process the result of A and B together forms the cipher text block.RC5 Encryption Algorithm:
One time initialization of plain text blocks A and B by adding S[0] and S[1] to A and B respectively. These operations are mod.XOR A and B. A=A^BCyclic left shift new value of A by B bits.Add S[2*i] to the output of previous step. This is the new value of A.XOR B with new value of A and store in B.Cyclic left shift new value of B by A bits.Add S[2*i+1] to the output of previous step. This is the new value of B.Repeat entire procedure (except one time initialization) r times.
One time initialization of plain text blocks A and B by adding S[0] and S[1] to A and B respectively. These operations are mod.
XOR A and B. A=A^B
Cyclic left shift new value of A by B bits.
Add S[2*i] to the output of previous step. This is the new value of A.
XOR B with new value of A and store in B.
Cyclic left shift new value of B by A bits.
Add S[2*i+1] to the output of previous step. This is the new value of B.
Repeat entire procedure (except one time initialization) r times.
A = A + S[0]
B = B + S[1]
for i = 1 to r do:
A = ((A ^ B) <<< B) + S[2 * i]
B = ((B ^ A) <<< A) + S[2 * i + 1]
return A, B
Alternatively, RC5 Decryption can be defined as:
for i = r down to 1 do:
B = ((B - S[2 * i + 1]) >>> A) ^ A
A = ((A - S[2 * i]) >>> B) ^ B
B = B - S[1]
A = A - S[0]
return A, B
Computer Networks
GATE CS
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Aug, 2019"
},
{
"code": null,
"e": 276,
"s": 52,
"text": "RC5 is a symmetric key block encryption algorithm designed by Ron Rivest in 1994. It is notable for being simple, fast (on account of using only primitive computer operations like XOR, shift, etc.) and consumes less memory."
},
{
"code": null,
"e": 285,
"s": 276,
"text": "Example:"
},
{
"code": null,
"e": 403,
"s": 285,
"text": "Key : 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\nPlain Text : 00000000 00000000\nCipher Text : EEDBA521 6D8F4B15\n"
},
{
"code": null,
"e": 710,
"s": 403,
"text": "RC5 is a block cipher and addresses two word blocks at a time.Depending on input plain text block size, number of rounds and key size, various instances of RC5 can be defined and each instance is denoted as RC5-w/r/b where w=word size in bits, r=number of rounds and b=key size in bytes.Allowed values are:"
},
{
"code": null,
"e": 811,
"s": 710,
"text": "Note – Since at a time, RC5 uses 2 word blocks, the plain text block size can be 32, 64 or 128 bits."
},
{
"code": null,
"e": 843,
"s": 811,
"text": "Notation used in the algorithm:"
},
{
"code": null,
"e": 973,
"s": 843,
"text": "Step-1: Initialization of constants P and Q.RC5 makes use of 2 magic constants P and Q whose value is defined by the word size w."
},
{
"code": null,
"e": 1028,
"s": 973,
"text": "For any other word size, P and Q can be determined as:"
},
{
"code": null,
"e": 1059,
"s": 1028,
"text": "P = Odd((e-2)) \nQ = Odd((-2))\n"
},
{
"code": null,
"e": 1167,
"s": 1059,
"text": "Here, Odd(x) is the odd integer nearest to x, e is the base of natural logarithms and is the golden ratio."
},
{
"code": null,
"e": 1545,
"s": 1167,
"text": "Step-2: Converting secret key K from bytes to words.Secret key K of size b bytes is used to initialize array L consisting of c words where c = b/u, u = w/8 and w = word size used for that particular instance of RC5. For example, if we choose w=32 bits and Key k is of size 96 bytes then, u=32/8=4, c=b/u=96/4=24.L is pre initialized to 0 value before adding secret key K to it."
},
{
"code": null,
"e": 1596,
"s": 1545,
"text": "for i=b-1 to 0\n L[i/u] = (L[u/i] <<< 8) + K[i]\n"
},
{
"code": null,
"e": 1700,
"s": 1596,
"text": "Step-3: Initializing sub-key S.Sub-key S of size t=2(r+1) is initialized using magic constants P and Q."
},
{
"code": null,
"e": 1755,
"s": 1700,
"text": "S[0] = P\nfor i = 1 to 2(r+1)-1\n S[i] = S[i-1] + Q)\n"
},
{
"code": null,
"e": 1940,
"s": 1755,
"text": "Step-4: Sub-key mixing.The RC5 encryption algorithm uses Sub key S. L is merely, a temporary array formed on the basis of user entered secret key.Mix in user’s secret key with S and L."
},
{
"code": null,
"e": 2103,
"s": 1940,
"text": "i = j = 0\nA = B = 0\ndo 3 * max(t, c) times:\n A = S[i] = (S[i] + A + B) <<< 3\n B = L[j] = (L[j] + A + B) <<< (A + B)\n i = (i + 1) % t\n j = (j + 1) % c\n"
},
{
"code": null,
"e": 2332,
"s": 2103,
"text": "Step-5: Encryption.We divide the input plain text block into two registers A and B each of size w bits. After undergoing the encryption process the result of A and B together forms the cipher text block.RC5 Encryption Algorithm:"
},
{
"code": null,
"e": 2812,
"s": 2332,
"text": "One time initialization of plain text blocks A and B by adding S[0] and S[1] to A and B respectively. These operations are mod.XOR A and B. A=A^BCyclic left shift new value of A by B bits.Add S[2*i] to the output of previous step. This is the new value of A.XOR B with new value of A and store in B.Cyclic left shift new value of B by A bits.Add S[2*i+1] to the output of previous step. This is the new value of B.Repeat entire procedure (except one time initialization) r times."
},
{
"code": null,
"e": 2940,
"s": 2812,
"text": "One time initialization of plain text blocks A and B by adding S[0] and S[1] to A and B respectively. These operations are mod."
},
{
"code": null,
"e": 2959,
"s": 2940,
"text": "XOR A and B. A=A^B"
},
{
"code": null,
"e": 3003,
"s": 2959,
"text": "Cyclic left shift new value of A by B bits."
},
{
"code": null,
"e": 3074,
"s": 3003,
"text": "Add S[2*i] to the output of previous step. This is the new value of A."
},
{
"code": null,
"e": 3116,
"s": 3074,
"text": "XOR B with new value of A and store in B."
},
{
"code": null,
"e": 3160,
"s": 3116,
"text": "Cyclic left shift new value of B by A bits."
},
{
"code": null,
"e": 3233,
"s": 3160,
"text": "Add S[2*i+1] to the output of previous step. This is the new value of B."
},
{
"code": null,
"e": 3299,
"s": 3233,
"text": "Repeat entire procedure (except one time initialization) r times."
},
{
"code": null,
"e": 3432,
"s": 3299,
"text": "A = A + S[0] \nB = B + S[1]\nfor i = 1 to r do:\n A = ((A ^ B) <<< B) + S[2 * i]\n B = ((B ^ A) <<< A) + S[2 * i + 1]\nreturn A, B\n"
},
{
"code": null,
"e": 3481,
"s": 3432,
"text": "Alternatively, RC5 Decryption can be defined as:"
},
{
"code": null,
"e": 3618,
"s": 3481,
"text": "for i = r down to 1 do:\n B = ((B - S[2 * i + 1]) >>> A) ^ A\n A = ((A - S[2 * i]) >>> B) ^ B\nB = B - S[1]\nA = A - S[0]\nreturn A, B\n"
},
{
"code": null,
"e": 3636,
"s": 3618,
"text": "Computer Networks"
},
{
"code": null,
"e": 3644,
"s": 3636,
"text": "GATE CS"
},
{
"code": null,
"e": 3662,
"s": 3644,
"text": "Computer Networks"
}
] |
Deep Search JSON Object JavaScript
|
Suppose we have the following nested JSON object −
const obj = {
id: 1,
title: 'hello world',
child: {
id: null,
title: 'foobar',
child: {
id: null,
title: 'i should be in results array '
}
},
foo: {
id: null,
title: 'i should be in results array too!' },
deep: [
{
id: null,
value: 'yo'
}, {
id: null,
value: 'yo2'
}
]
};
We are required to write a JavaScript function that takes in one such object as the first argument, a key string as the second and a value string as the third argument. The function should then check for the given key value pair in the JSON object.
If there exists any object then the function should return an array of all such objects.
We will use the following approach to solve this problem −
if the searched item is false or if it’s not an object, then we return
if given key and value match, then we add the actual object to the result set,
we get the keys and iterate over the properties and call the function again.
At last, we return the array with the collected objects.
const obj = {
id: 1,
title: 'hello world',
child: {
id: null,
title: 'foobar',
child: {
id: null,
title: 'i should be in results array '
}
},
foo: {
id: null,
title: 'i should be in results array too!' },
deep: [
{
id: null, value: 'yo'
}, {
id: null, value: 'yo2'
}
]
};
const findObject = (obj = {}, key, value) => {
const result = [];
const recursiveSearch = (obj = {}) => {
if (!obj || typeof obj !== 'object') { return;
};
if (obj[key] === value){
result.push(obj);
};
Object.keys(obj).forEach(function (k) {
recursiveSearch(obj[k]);
});
} recursiveSearch(obj);
return result;
} console.log(findObject(obj, 'id', null));
[
{
id: null,
title: 'foobar',
child: {
id: null, title: 'i should be in results array '
}
},
{
id: null, title: 'i should be in results array '
}, {
id: null, title: 'i should be in results array too!'
}, {
id: null, value: 'yo'
}, { id: null, value: 'yo2'
}
]
|
[
{
"code": null,
"e": 1113,
"s": 1062,
"text": "Suppose we have the following nested JSON object −"
},
{
"code": null,
"e": 1517,
"s": 1113,
"text": "const obj = {\n id: 1,\n title: 'hello world',\n child: {\n id: null,\n title: 'foobar',\n child: {\n id: null,\n title: 'i should be in results array '\n }\n },\n foo: {\n id: null,\n title: 'i should be in results array too!' },\n deep: [\n {\n id: null,\n value: 'yo'\n }, {\n id: null,\n value: 'yo2'\n }\n ]\n};"
},
{
"code": null,
"e": 1766,
"s": 1517,
"text": "We are required to write a JavaScript function that takes in one such object as the first argument, a key string as the second and a value string as the third argument. The function should then check for the given key value pair in the JSON object."
},
{
"code": null,
"e": 1855,
"s": 1766,
"text": "If there exists any object then the function should return an array of all such objects."
},
{
"code": null,
"e": 1914,
"s": 1855,
"text": "We will use the following approach to solve this problem −"
},
{
"code": null,
"e": 1985,
"s": 1914,
"text": "if the searched item is false or if it’s not an object, then we return"
},
{
"code": null,
"e": 2064,
"s": 1985,
"text": "if given key and value match, then we add the actual object to the result set,"
},
{
"code": null,
"e": 2141,
"s": 2064,
"text": "we get the keys and iterate over the properties and call the function again."
},
{
"code": null,
"e": 2198,
"s": 2141,
"text": "At last, we return the array with the collected objects."
},
{
"code": null,
"e": 2977,
"s": 2198,
"text": "const obj = {\n id: 1,\n title: 'hello world',\n child: {\n id: null,\n title: 'foobar',\n child: {\n id: null,\n title: 'i should be in results array '\n }\n },\n foo: {\n id: null,\n title: 'i should be in results array too!' },\n deep: [\n {\n id: null, value: 'yo'\n }, {\n id: null, value: 'yo2'\n }\n ]\n};\nconst findObject = (obj = {}, key, value) => {\n const result = [];\n const recursiveSearch = (obj = {}) => {\n if (!obj || typeof obj !== 'object') { return;\n };\n if (obj[key] === value){\n result.push(obj);\n };\n Object.keys(obj).forEach(function (k) {\n recursiveSearch(obj[k]);\n });\n} recursiveSearch(obj);\nreturn result;\n} console.log(findObject(obj, 'id', null));"
},
{
"code": null,
"e": 3323,
"s": 2977,
"text": "[\n {\n id: null,\n title: 'foobar',\n child: {\n id: null, title: 'i should be in results array '\n }\n },\n {\n id: null, title: 'i should be in results array '\n }, {\n id: null, title: 'i should be in results array too!'\n }, {\n id: null, value: 'yo'\n }, { id: null, value: 'yo2'\n }\n]"
}
] |
Convert.ToString Method in C#
|
Convert the specified value to its equivalent string using the ToString() method.
Initialize a bool value.
bool boolVal = false;
Now, to convert it to a string, use the ToString() method.
Convert.ToString(boolVal)
The following is the complete example.
Live Demo
using System;
public class Demo {
public static void Main() {
bool boolVal = false;
Console.WriteLine(Convert.ToString(boolVal));
}
}
False
|
[
{
"code": null,
"e": 1144,
"s": 1062,
"text": "Convert the specified value to its equivalent string using the ToString() method."
},
{
"code": null,
"e": 1169,
"s": 1144,
"text": "Initialize a bool value."
},
{
"code": null,
"e": 1191,
"s": 1169,
"text": "bool boolVal = false;"
},
{
"code": null,
"e": 1250,
"s": 1191,
"text": "Now, to convert it to a string, use the ToString() method."
},
{
"code": null,
"e": 1276,
"s": 1250,
"text": "Convert.ToString(boolVal)"
},
{
"code": null,
"e": 1315,
"s": 1276,
"text": "The following is the complete example."
},
{
"code": null,
"e": 1326,
"s": 1315,
"text": " Live Demo"
},
{
"code": null,
"e": 1478,
"s": 1326,
"text": "using System;\npublic class Demo {\n public static void Main() {\n bool boolVal = false;\n Console.WriteLine(Convert.ToString(boolVal));\n }\n}"
},
{
"code": null,
"e": 1484,
"s": 1478,
"text": "False"
}
] |
Batch Script - REM
|
This batch command is used for remarks in batch files, preventing the content of the remark from being executed.
REM remark description
@echo off
REM This is a batch file
None
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2282,
"s": 2169,
"text": "This batch command is used for remarks in batch files, preventing the content of the remark from being executed."
},
{
"code": null,
"e": 2306,
"s": 2282,
"text": "REM remark description\n"
},
{
"code": null,
"e": 2342,
"s": 2306,
"text": "@echo off \nREM This is a batch file"
},
{
"code": null,
"e": 2348,
"s": 2342,
"text": "None\n"
},
{
"code": null,
"e": 2355,
"s": 2348,
"text": " Print"
},
{
"code": null,
"e": 2366,
"s": 2355,
"text": " Add Notes"
}
] |
Creating an Email Parser with Python and SQL | by Benjamin Dornel | Towards Data Science
|
You might be wondering what an email parser is, and why you might need one.
In short, an email parser is a software that looks for and extracts data from inbound emails and attachments. More importantly, an email parser uses conditional processing to pull the specific data that matters to you.
So why does this matter? If you’ve ever spent any time working a regular office job, you’ve probably become intimately familiar with reports, and by extension, copy-pasting lines of text from Microsoft Outlook to Excel or Word.
You might even end up doing the same report, week after week. Add in formatting and spellchecking, and this ends up as a huge time drain when you could be focusing on more important tasks.
The good news is that you can automate most of this process with Python and SQL.
In this post, I’ll cover how to open Outlook emails with Python and extract the body text as HTML. I’ll then cover how to parse this in Python and how to upload the final data to a SQL database. From there, you can write this data to Excel or transform it into a Pandas Dataframe.
We’ll be using a few key Python libraries here, namely os, sqlite3 and pywin32.
To start off, we’ll first need to decide what we want to extract from our emails. For example, let’s say we have a bunch of emails that each contain a list of news articles like this:
Let’s then say that we want to extract the header of each bullet point, which includes the title, the publication, media platforms, and URL links. In short, we want to take the entire header of each bullet point, then break it down into four different parts.
Our pseudocode so far should look something like this:
1. Create list of emails that we want to parse2. Open first email3. Iterate over each bullet point4. Extract data from bullet point5. Upload data from bullet point to a database6. Repeat until all data is parsed, then move to next email
Before parsing our emails, we’ll first want to set up a SQL database with Python. We’ll do this by establishing a connection to the SQLite database with a connection object that we’ll call db.
# Create & connect to databasedb = sqlite3.connect("emails.db")
If it doesn’t already exist, a new database will be created as emails.db. We can then create tables in our database that our email parser can write to later on.
# Create empty tablesdb.execute("""CREATE TABLE IF NOT EXISTS "articles" ("id" INTEGER,"title" TEXT UNIQUE,"publication" TEXT,PRIMARY KEY("id" AUTOINCREMENT))""")db.execute("""CREATE TABLE IF NOT EXISTS "links" ("article_id" INTEGER,"link0" TEXT,"link1" TEXT,"link2" TEXT,PRIMARY KEY("article_id"))""")db.execute("""CREATE TABLE IF NOT EXISTS "platforms" ("article_id" INTEGER,"platform0" TEXT,"platform1" TEXT,"platform2" TEXT,PRIMARY KEY("article_id"))""")
In essence, we’re creating three tables, where our main table is ‘articles’, which has a one-to-many relationship with ‘platforms’ and ‘links’. In other words, this reflects how one article can have many different platforms and links.
You’ll want to move the emails that you want to parse from Outlook to a folder. The simplest method to do this is by dragging and dropping.
Next, create a variable storing the folder path of your emails. You can do this manually e.g. folder_path = r‘C:\Users\Username\EmailFolder’ or with tkinter and os, which will generate a file explorer prompt to select a folder.
# Create an folder input dialog with tkinterfolder_path = os.path.normpath(askdirectory(title='Select Folder'))
Here, we’re using a file input prompt created with tkinter to save our folder path, then normalizing the path with os to remove any redundant separators.
We’ll then want to obtain the path headings of each email. We can do this with os.listdir(), which gives a list of all files in the specified directory.
# Initialise & populate list of emailsemail_list = [file for file in os.listdir(folder_path) if file.endswith(".msg")]
This will save the file name of each email in list that we can access later.
Next, you’ll want to create an object that will allow us to control Outlook from Python. This is enabled through the pywin32 library that helps to connect Python to Outlook via the Microsoft Outlook Messaging API (MAPI).
# Connect to Outlook with MAPIoutlook = win32com.client.Dispatch(“Outlook.Application”) .GetNamespace(“MAPI”)
With this, we can begin to open each item as a HTML object, and use regular expressions i.e. Regex to extract the body text of each email.
While conventional wisdom dictates that you shouldn’t use Regex to parse HTML, we’re not worried about this here, as we’re only looking to extract very specific text snippets out of a standard email format (Some commercial email parsers like Parseur are heavily built around Regex).
From this point, Regex can be used to narrow down the specific data that you want to extract.
# Iterate through every emailfor i, _ in enumerate(email_list): # Create variable storing info from current email being parsed msg = outlook.OpenSharedItem(os.path.join(folder_path, email_list[i])) # Search email HTML for body text regex = re.search(r"<body([\s\S]*)</body>", msg.HTMLBody) body = regex.group()
This is how the first bullet point of our email might look as HTML:
Okay — so we can see that there are several key characteristics here, namely that our data exists as a bulleted list or li class=MsoListParagraph. We can use Regex to extract each bullet point.
# Search email body text for unique entriespattern = r"li class=MsoListParagraph([\s\S]*?)</li>"results = re.findall(pattern, body)
Each bullet point is extracted as a string, and each string is stored in a list. Our first bullet point should look something like this with Regex:
To retrieve our title and publication, we can use Regex again. This time, we’ll also use call html.unescape() on our text to help translate our HTML to string e.g. &8211; → – (a unicode dash).
regex = re.search(r"[^<>]+(?=\(|sans-serif’>([\s\S]*?)</span>)", header)# HTML unescape to get remove remaining HTMLtitle_pub = html.unescape(regex.group())
From here, it’s as simple as splitting our text. We can use split_list = title_pub.split("–") to give us a list: ["New Arrival: Dell G Series Gaming Computers", "Tech4tea"].
We can then remove any redundant whitespaces and save each item as a variable.
title = split_list[0].strip()publication = split_list[1].strip()
That’s two down!
To get our media platforms, we’ll use a more straightforward method.
# List of publications to check forplatform_list = ["Online", "Facebook", "Instagram", "Twitter", "LinkedIn", "Youtube"]# Create empty list to store publicationsplatform = []# Iterate and check for each item in my first listfor p in platform_list: if p in header: platform.append(p)
This will give us a list of publications: ["Online", "Facebook", "LinkedIn"]
Now for the URLs:
# Find all links using regexlinks = re.findall(r"<a href=\”([\s\S]*?)\”>", header)
This will then give us the characters highlighted in green below:
Our data so far should look something like this:
Title: New Arrival: Dell G Series Gaming ComputersPublication: Tech4teaPlatform: [‘Online’, ‘Facebook’, ‘LinkedIn’]Links: [‘http://tech4tea.com/blog/2020/06/26/new-arrival-dell-g-series-gaming-computers-monitors-keyboards/', ‘https://business.facebook.com/gotech4tea/posts/4598490146843826', ‘https://www.linkedin.com/feed/update/urn:li:activity:6682511823100542976/']
The final step in this process is to upload each piece of data to our SQL database.
We’ll start by uploading our title and publication data. This can be accomplished with the following code:
# Insert title & pub by substituting values into each ? placeholderdb.execute("INSERT INTO articles (title, publication) VALUES (?, ?)", (title, publication))
Uploading our links and platforms are a bit more tricky. First, we’ll copy over our primary id from our main table, then iterate over each platform and link individually.
# Get article id and copy to platforms & links tablesarticle_id = db.execute(“SELECT id FROM articles WHERE title = ?”, (title,))for item in article_id: _id = item[0]for i, _ in enumerate(platform): db.execute(f”UPDATE platforms SET platform{i} = ? WHERE article_id = ?”, (platform[i], _id))for i, _ in enumerate(links): db.execute(f”UPDATE links SET link{i} = ? WHERE article_id = ?”, (links[i], _id))# Commit changesdb.commit()
The last step here is to commit all these changes to the database. With that done, our email parser is complete! If you’d like, you can use something like DB Browser to check that the contents of your database have been successfully updated.
In case you need it, I’ve uploaded the full code for this on my website and Github.
|
[
{
"code": null,
"e": 247,
"s": 171,
"text": "You might be wondering what an email parser is, and why you might need one."
},
{
"code": null,
"e": 466,
"s": 247,
"text": "In short, an email parser is a software that looks for and extracts data from inbound emails and attachments. More importantly, an email parser uses conditional processing to pull the specific data that matters to you."
},
{
"code": null,
"e": 694,
"s": 466,
"text": "So why does this matter? If you’ve ever spent any time working a regular office job, you’ve probably become intimately familiar with reports, and by extension, copy-pasting lines of text from Microsoft Outlook to Excel or Word."
},
{
"code": null,
"e": 883,
"s": 694,
"text": "You might even end up doing the same report, week after week. Add in formatting and spellchecking, and this ends up as a huge time drain when you could be focusing on more important tasks."
},
{
"code": null,
"e": 964,
"s": 883,
"text": "The good news is that you can automate most of this process with Python and SQL."
},
{
"code": null,
"e": 1245,
"s": 964,
"text": "In this post, I’ll cover how to open Outlook emails with Python and extract the body text as HTML. I’ll then cover how to parse this in Python and how to upload the final data to a SQL database. From there, you can write this data to Excel or transform it into a Pandas Dataframe."
},
{
"code": null,
"e": 1325,
"s": 1245,
"text": "We’ll be using a few key Python libraries here, namely os, sqlite3 and pywin32."
},
{
"code": null,
"e": 1509,
"s": 1325,
"text": "To start off, we’ll first need to decide what we want to extract from our emails. For example, let’s say we have a bunch of emails that each contain a list of news articles like this:"
},
{
"code": null,
"e": 1768,
"s": 1509,
"text": "Let’s then say that we want to extract the header of each bullet point, which includes the title, the publication, media platforms, and URL links. In short, we want to take the entire header of each bullet point, then break it down into four different parts."
},
{
"code": null,
"e": 1823,
"s": 1768,
"text": "Our pseudocode so far should look something like this:"
},
{
"code": null,
"e": 2060,
"s": 1823,
"text": "1. Create list of emails that we want to parse2. Open first email3. Iterate over each bullet point4. Extract data from bullet point5. Upload data from bullet point to a database6. Repeat until all data is parsed, then move to next email"
},
{
"code": null,
"e": 2253,
"s": 2060,
"text": "Before parsing our emails, we’ll first want to set up a SQL database with Python. We’ll do this by establishing a connection to the SQLite database with a connection object that we’ll call db."
},
{
"code": null,
"e": 2317,
"s": 2253,
"text": "# Create & connect to databasedb = sqlite3.connect(\"emails.db\")"
},
{
"code": null,
"e": 2478,
"s": 2317,
"text": "If it doesn’t already exist, a new database will be created as emails.db. We can then create tables in our database that our email parser can write to later on."
},
{
"code": null,
"e": 2943,
"s": 2478,
"text": "# Create empty tablesdb.execute(\"\"\"CREATE TABLE IF NOT EXISTS \"articles\" (\"id\" INTEGER,\"title\" TEXT UNIQUE,\"publication\" TEXT,PRIMARY KEY(\"id\" AUTOINCREMENT))\"\"\")db.execute(\"\"\"CREATE TABLE IF NOT EXISTS \"links\" (\"article_id\" INTEGER,\"link0\" TEXT,\"link1\" TEXT,\"link2\" TEXT,PRIMARY KEY(\"article_id\"))\"\"\")db.execute(\"\"\"CREATE TABLE IF NOT EXISTS \"platforms\" (\"article_id\" INTEGER,\"platform0\" TEXT,\"platform1\" TEXT,\"platform2\" TEXT,PRIMARY KEY(\"article_id\"))\"\"\")"
},
{
"code": null,
"e": 3178,
"s": 2943,
"text": "In essence, we’re creating three tables, where our main table is ‘articles’, which has a one-to-many relationship with ‘platforms’ and ‘links’. In other words, this reflects how one article can have many different platforms and links."
},
{
"code": null,
"e": 3318,
"s": 3178,
"text": "You’ll want to move the emails that you want to parse from Outlook to a folder. The simplest method to do this is by dragging and dropping."
},
{
"code": null,
"e": 3546,
"s": 3318,
"text": "Next, create a variable storing the folder path of your emails. You can do this manually e.g. folder_path = r‘C:\\Users\\Username\\EmailFolder’ or with tkinter and os, which will generate a file explorer prompt to select a folder."
},
{
"code": null,
"e": 3658,
"s": 3546,
"text": "# Create an folder input dialog with tkinterfolder_path = os.path.normpath(askdirectory(title='Select Folder'))"
},
{
"code": null,
"e": 3812,
"s": 3658,
"text": "Here, we’re using a file input prompt created with tkinter to save our folder path, then normalizing the path with os to remove any redundant separators."
},
{
"code": null,
"e": 3965,
"s": 3812,
"text": "We’ll then want to obtain the path headings of each email. We can do this with os.listdir(), which gives a list of all files in the specified directory."
},
{
"code": null,
"e": 4084,
"s": 3965,
"text": "# Initialise & populate list of emailsemail_list = [file for file in os.listdir(folder_path) if file.endswith(\".msg\")]"
},
{
"code": null,
"e": 4161,
"s": 4084,
"text": "This will save the file name of each email in list that we can access later."
},
{
"code": null,
"e": 4382,
"s": 4161,
"text": "Next, you’ll want to create an object that will allow us to control Outlook from Python. This is enabled through the pywin32 library that helps to connect Python to Outlook via the Microsoft Outlook Messaging API (MAPI)."
},
{
"code": null,
"e": 4509,
"s": 4382,
"text": "# Connect to Outlook with MAPIoutlook = win32com.client.Dispatch(“Outlook.Application”) .GetNamespace(“MAPI”)"
},
{
"code": null,
"e": 4648,
"s": 4509,
"text": "With this, we can begin to open each item as a HTML object, and use regular expressions i.e. Regex to extract the body text of each email."
},
{
"code": null,
"e": 4931,
"s": 4648,
"text": "While conventional wisdom dictates that you shouldn’t use Regex to parse HTML, we’re not worried about this here, as we’re only looking to extract very specific text snippets out of a standard email format (Some commercial email parsers like Parseur are heavily built around Regex)."
},
{
"code": null,
"e": 5025,
"s": 4931,
"text": "From this point, Regex can be used to narrow down the specific data that you want to extract."
},
{
"code": null,
"e": 5348,
"s": 5025,
"text": "# Iterate through every emailfor i, _ in enumerate(email_list): # Create variable storing info from current email being parsed msg = outlook.OpenSharedItem(os.path.join(folder_path, email_list[i])) # Search email HTML for body text regex = re.search(r\"<body([\\s\\S]*)</body>\", msg.HTMLBody) body = regex.group()"
},
{
"code": null,
"e": 5416,
"s": 5348,
"text": "This is how the first bullet point of our email might look as HTML:"
},
{
"code": null,
"e": 5610,
"s": 5416,
"text": "Okay — so we can see that there are several key characteristics here, namely that our data exists as a bulleted list or li class=MsoListParagraph. We can use Regex to extract each bullet point."
},
{
"code": null,
"e": 5742,
"s": 5610,
"text": "# Search email body text for unique entriespattern = r\"li class=MsoListParagraph([\\s\\S]*?)</li>\"results = re.findall(pattern, body)"
},
{
"code": null,
"e": 5890,
"s": 5742,
"text": "Each bullet point is extracted as a string, and each string is stored in a list. Our first bullet point should look something like this with Regex:"
},
{
"code": null,
"e": 6083,
"s": 5890,
"text": "To retrieve our title and publication, we can use Regex again. This time, we’ll also use call html.unescape() on our text to help translate our HTML to string e.g. &8211; → – (a unicode dash)."
},
{
"code": null,
"e": 6240,
"s": 6083,
"text": "regex = re.search(r\"[^<>]+(?=\\(|sans-serif’>([\\s\\S]*?)</span>)\", header)# HTML unescape to get remove remaining HTMLtitle_pub = html.unescape(regex.group())"
},
{
"code": null,
"e": 6414,
"s": 6240,
"text": "From here, it’s as simple as splitting our text. We can use split_list = title_pub.split(\"–\") to give us a list: [\"New Arrival: Dell G Series Gaming Computers\", \"Tech4tea\"]."
},
{
"code": null,
"e": 6493,
"s": 6414,
"text": "We can then remove any redundant whitespaces and save each item as a variable."
},
{
"code": null,
"e": 6558,
"s": 6493,
"text": "title = split_list[0].strip()publication = split_list[1].strip()"
},
{
"code": null,
"e": 6575,
"s": 6558,
"text": "That’s two down!"
},
{
"code": null,
"e": 6644,
"s": 6575,
"text": "To get our media platforms, we’ll use a more straightforward method."
},
{
"code": null,
"e": 6934,
"s": 6644,
"text": "# List of publications to check forplatform_list = [\"Online\", \"Facebook\", \"Instagram\", \"Twitter\", \"LinkedIn\", \"Youtube\"]# Create empty list to store publicationsplatform = []# Iterate and check for each item in my first listfor p in platform_list: if p in header: platform.append(p)"
},
{
"code": null,
"e": 7011,
"s": 6934,
"text": "This will give us a list of publications: [\"Online\", \"Facebook\", \"LinkedIn\"]"
},
{
"code": null,
"e": 7029,
"s": 7011,
"text": "Now for the URLs:"
},
{
"code": null,
"e": 7112,
"s": 7029,
"text": "# Find all links using regexlinks = re.findall(r\"<a href=\\”([\\s\\S]*?)\\”>\", header)"
},
{
"code": null,
"e": 7178,
"s": 7112,
"text": "This will then give us the characters highlighted in green below:"
},
{
"code": null,
"e": 7227,
"s": 7178,
"text": "Our data so far should look something like this:"
},
{
"code": null,
"e": 7596,
"s": 7227,
"text": "Title: New Arrival: Dell G Series Gaming ComputersPublication: Tech4teaPlatform: [‘Online’, ‘Facebook’, ‘LinkedIn’]Links: [‘http://tech4tea.com/blog/2020/06/26/new-arrival-dell-g-series-gaming-computers-monitors-keyboards/', ‘https://business.facebook.com/gotech4tea/posts/4598490146843826', ‘https://www.linkedin.com/feed/update/urn:li:activity:6682511823100542976/']"
},
{
"code": null,
"e": 7680,
"s": 7596,
"text": "The final step in this process is to upload each piece of data to our SQL database."
},
{
"code": null,
"e": 7787,
"s": 7680,
"text": "We’ll start by uploading our title and publication data. This can be accomplished with the following code:"
},
{
"code": null,
"e": 7946,
"s": 7787,
"text": "# Insert title & pub by substituting values into each ? placeholderdb.execute(\"INSERT INTO articles (title, publication) VALUES (?, ?)\", (title, publication))"
},
{
"code": null,
"e": 8117,
"s": 7946,
"text": "Uploading our links and platforms are a bit more tricky. First, we’ll copy over our primary id from our main table, then iterate over each platform and link individually."
},
{
"code": null,
"e": 8562,
"s": 8117,
"text": "# Get article id and copy to platforms & links tablesarticle_id = db.execute(“SELECT id FROM articles WHERE title = ?”, (title,))for item in article_id: _id = item[0]for i, _ in enumerate(platform): db.execute(f”UPDATE platforms SET platform{i} = ? WHERE article_id = ?”, (platform[i], _id))for i, _ in enumerate(links): db.execute(f”UPDATE links SET link{i} = ? WHERE article_id = ?”, (links[i], _id))# Commit changesdb.commit()"
},
{
"code": null,
"e": 8804,
"s": 8562,
"text": "The last step here is to commit all these changes to the database. With that done, our email parser is complete! If you’d like, you can use something like DB Browser to check that the contents of your database have been successfully updated."
}
] |
java.time.LocalDateTime.ofInstant() Method Example
|
The java.time.LocalDateTime.ofInstant(Instant instant, ZoneId zone) method obtains an instance of LocalDateTime from an Instant and zone ID.
Following is the declaration for java.time.LocalDateTime.ofInstant(Instant instant, ZoneId zone) method.
public static LocalDateTime ofInstant(Instant instant, ZoneId zone)
instant − the instant to create the date-time from, not null.
instant − the instant to create the date-time from, not null.
zone − the time-zone, which may be an offset, not null.
zone − the time-zone, which may be an offset, not null.
the local date, not null.
DateTimeException − if the result exceeds the supported range.
The following example shows the usage of java.time.LocalDateTime.ofInstant(Instant instant, ZoneId zone) method.
package com.tutorialspoint;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
public class LocalDateTimeDemo {
public static void main(String[] args) {
LocalDateTime date = LocalDateTime.ofInstant(Instant.now(), ZoneId.systemDefault());
System.out.println(date);
}
}
Let us compile and run the above program, this will produce the following result −
2017-03-17T15:50:22.770
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2056,
"s": 1915,
"text": "The java.time.LocalDateTime.ofInstant(Instant instant, ZoneId zone) method obtains an instance of LocalDateTime from an Instant and zone ID."
},
{
"code": null,
"e": 2161,
"s": 2056,
"text": "Following is the declaration for java.time.LocalDateTime.ofInstant(Instant instant, ZoneId zone) method."
},
{
"code": null,
"e": 2230,
"s": 2161,
"text": "public static LocalDateTime ofInstant(Instant instant, ZoneId zone)\n"
},
{
"code": null,
"e": 2292,
"s": 2230,
"text": "instant − the instant to create the date-time from, not null."
},
{
"code": null,
"e": 2354,
"s": 2292,
"text": "instant − the instant to create the date-time from, not null."
},
{
"code": null,
"e": 2410,
"s": 2354,
"text": "zone − the time-zone, which may be an offset, not null."
},
{
"code": null,
"e": 2466,
"s": 2410,
"text": "zone − the time-zone, which may be an offset, not null."
},
{
"code": null,
"e": 2492,
"s": 2466,
"text": "the local date, not null."
},
{
"code": null,
"e": 2555,
"s": 2492,
"text": "DateTimeException − if the result exceeds the supported range."
},
{
"code": null,
"e": 2668,
"s": 2555,
"text": "The following example shows the usage of java.time.LocalDateTime.ofInstant(Instant instant, ZoneId zone) method."
},
{
"code": null,
"e": 2992,
"s": 2668,
"text": "package com.tutorialspoint;\n\nimport java.time.Instant;\nimport java.time.LocalDateTime;\nimport java.time.ZoneId;\n\npublic class LocalDateTimeDemo {\n public static void main(String[] args) {\n \n LocalDateTime date = LocalDateTime.ofInstant(Instant.now(), ZoneId.systemDefault());\n System.out.println(date); \n }\n}"
},
{
"code": null,
"e": 3075,
"s": 2992,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 3100,
"s": 3075,
"text": "2017-03-17T15:50:22.770\n"
},
{
"code": null,
"e": 3107,
"s": 3100,
"text": " Print"
},
{
"code": null,
"e": 3118,
"s": 3107,
"text": " Add Notes"
}
] |
Count number of trees in a forest in C++
|
Given vertices of a forest ( collection of trees). The goal is to find the number of trees in that forest. We will do this by running a DFS (depth first search) algorithm on the forest.
For Example
edges = { { 1,3 }, {2,8}, {2,6}, {3,5}, {3,7}, {4,8} }
Count of number of trees in a forest are: 3
The number of trees that are present in the forest are −
Approach used in the below program is as follows −
In this approach we apply Depth First search algorithm on the graph recursively. We will increment count if every connected node is marked visited from one source ( which
means a tree is formed ).
Take an integer vertice as a number of vertices on a graph.
Take an integer vertice as a number of vertices on a graph.
Take a vector vector<int> vec[vertice] for storing vertices as integers.
Take a vector vector<int> vec[vertice] for storing vertices as integers.
Function insert(vector<int> vec[], int parent, int child) takes vec[] and adds an edge between nodes parent and child in that vector.
Function insert(vector<int> vec[], int parent, int child) takes vec[] and adds an edge between nodes parent and child in that vector.
Add edge using vec[parent].push_back(child) and vec[child].push_back(parent).
Add edge using vec[parent].push_back(child) and vec[child].push_back(parent).
Function recurred(int temp, vector<int> vec[], vector<bool> &check) applies DFS on graph from starting vertex temp.
Function recurred(int temp, vector<int> vec[], vector<bool> &check) applies DFS on graph from starting vertex temp.
Array check[temp] is used to set nodes as visited/unvisited using true/false.
Array check[temp] is used to set nodes as visited/unvisited using true/false.
Traverse vector vec[] using for loop and if check[vec[temp][i]] is false then call
recurred(vec[temp][i], vec, check) recursively for connected nodes.
Traverse vector vec[] using for loop and if check[vec[temp][i]] is false then call
recurred(vec[temp][i], vec, check) recursively for connected nodes.
Function Trees_Forest(vector<int> vec[], int vertice) takes vec[] and returns the count of trees in the forest given as adjacency list in vec[].
Function Trees_Forest(vector<int> vec[], int vertice) takes vec[] and returns the count of trees in the forest given as adjacency list in vec[].
Take initial count of forests as 0.
Take initial count of forests as 0.
Take vector<bool> check(vertice, false) to mark vertices of graph as visited.
Take vector<bool> check(vertice, false) to mark vertices of graph as visited.
Traverse all vertices using for loop.
Traverse all vertices using for loop.
If check[i] is false then apply dfs using recurred(i, vec, check) and increment
count.
If check[i] is false then apply dfs using recurred(i, vec, check) and increment
count.
At the end of all loops return count as result.
At the end of all loops return count as result.
Live Demo
#include<bits/stdc++.h>
using namespace std;
void insert(vector<int> vec[], int parent, int child){
vec[parent].push_back(child);
vec[child].push_back(parent);
}
void recurred(int temp, vector<int> vec[], vector<bool> &check){
check[temp] = true;
int size = vec[temp].size();
for(int i = 0; i < size; i++){
if (check[vec[temp][i]] == false){
recurred(vec[temp][i], vec, check);
}
}
}
int Trees_Forest(vector<int> vec[], int vertice){
int count = 0;
vector<bool> check(vertice, false);
for(int i = 0; i < vertice; i++){
if(check[i] == false){
recurred(i, vec, check);
count++;
}
}
return count;
}
int main(){
int vertice = 9;
vector<int> vec[vertice];
insert(vec, 1, 3);
insert(vec, 2, 8);
insert(vec, 2, 6);
insert(vec, 3, 5);
insert(vec, 3, 7);
insert(vec, 4, 8);
cout<<"Count of number of trees in a forest are: "<<Trees_Forest(vec, vertice);
return 0;
}
If we run the above code it will generate the following output −
Count of number of trees in a forest are: 3
|
[
{
"code": null,
"e": 1248,
"s": 1062,
"text": "Given vertices of a forest ( collection of trees). The goal is to find the number of trees in that forest. We will do this by running a DFS (depth first search) algorithm on the forest."
},
{
"code": null,
"e": 1260,
"s": 1248,
"text": "For Example"
},
{
"code": null,
"e": 1315,
"s": 1260,
"text": "edges = { { 1,3 }, {2,8}, {2,6}, {3,5}, {3,7}, {4,8} }"
},
{
"code": null,
"e": 1359,
"s": 1315,
"text": "Count of number of trees in a forest are: 3"
},
{
"code": null,
"e": 1416,
"s": 1359,
"text": "The number of trees that are present in the forest are −"
},
{
"code": null,
"e": 1467,
"s": 1416,
"text": "Approach used in the below program is as follows −"
},
{
"code": null,
"e": 1664,
"s": 1467,
"text": "In this approach we apply Depth First search algorithm on the graph recursively. We will increment count if every connected node is marked visited from one source ( which\nmeans a tree is formed )."
},
{
"code": null,
"e": 1724,
"s": 1664,
"text": "Take an integer vertice as a number of vertices on a graph."
},
{
"code": null,
"e": 1784,
"s": 1724,
"text": "Take an integer vertice as a number of vertices on a graph."
},
{
"code": null,
"e": 1857,
"s": 1784,
"text": "Take a vector vector<int> vec[vertice] for storing vertices as integers."
},
{
"code": null,
"e": 1930,
"s": 1857,
"text": "Take a vector vector<int> vec[vertice] for storing vertices as integers."
},
{
"code": null,
"e": 2064,
"s": 1930,
"text": "Function insert(vector<int> vec[], int parent, int child) takes vec[] and adds an edge between nodes parent and child in that vector."
},
{
"code": null,
"e": 2198,
"s": 2064,
"text": "Function insert(vector<int> vec[], int parent, int child) takes vec[] and adds an edge between nodes parent and child in that vector."
},
{
"code": null,
"e": 2276,
"s": 2198,
"text": "Add edge using vec[parent].push_back(child) and vec[child].push_back(parent)."
},
{
"code": null,
"e": 2354,
"s": 2276,
"text": "Add edge using vec[parent].push_back(child) and vec[child].push_back(parent)."
},
{
"code": null,
"e": 2470,
"s": 2354,
"text": "Function recurred(int temp, vector<int> vec[], vector<bool> &check) applies DFS on graph from starting vertex temp."
},
{
"code": null,
"e": 2586,
"s": 2470,
"text": "Function recurred(int temp, vector<int> vec[], vector<bool> &check) applies DFS on graph from starting vertex temp."
},
{
"code": null,
"e": 2664,
"s": 2586,
"text": "Array check[temp] is used to set nodes as visited/unvisited using true/false."
},
{
"code": null,
"e": 2742,
"s": 2664,
"text": "Array check[temp] is used to set nodes as visited/unvisited using true/false."
},
{
"code": null,
"e": 2893,
"s": 2742,
"text": "Traverse vector vec[] using for loop and if check[vec[temp][i]] is false then call\nrecurred(vec[temp][i], vec, check) recursively for connected nodes."
},
{
"code": null,
"e": 3044,
"s": 2893,
"text": "Traverse vector vec[] using for loop and if check[vec[temp][i]] is false then call\nrecurred(vec[temp][i], vec, check) recursively for connected nodes."
},
{
"code": null,
"e": 3189,
"s": 3044,
"text": "Function Trees_Forest(vector<int> vec[], int vertice) takes vec[] and returns the count of trees in the forest given as adjacency list in vec[]."
},
{
"code": null,
"e": 3334,
"s": 3189,
"text": "Function Trees_Forest(vector<int> vec[], int vertice) takes vec[] and returns the count of trees in the forest given as adjacency list in vec[]."
},
{
"code": null,
"e": 3370,
"s": 3334,
"text": "Take initial count of forests as 0."
},
{
"code": null,
"e": 3406,
"s": 3370,
"text": "Take initial count of forests as 0."
},
{
"code": null,
"e": 3484,
"s": 3406,
"text": "Take vector<bool> check(vertice, false) to mark vertices of graph as visited."
},
{
"code": null,
"e": 3562,
"s": 3484,
"text": "Take vector<bool> check(vertice, false) to mark vertices of graph as visited."
},
{
"code": null,
"e": 3600,
"s": 3562,
"text": "Traverse all vertices using for loop."
},
{
"code": null,
"e": 3638,
"s": 3600,
"text": "Traverse all vertices using for loop."
},
{
"code": null,
"e": 3725,
"s": 3638,
"text": "If check[i] is false then apply dfs using recurred(i, vec, check) and increment\ncount."
},
{
"code": null,
"e": 3812,
"s": 3725,
"text": "If check[i] is false then apply dfs using recurred(i, vec, check) and increment\ncount."
},
{
"code": null,
"e": 3860,
"s": 3812,
"text": "At the end of all loops return count as result."
},
{
"code": null,
"e": 3908,
"s": 3860,
"text": "At the end of all loops return count as result."
},
{
"code": null,
"e": 3919,
"s": 3908,
"text": " Live Demo"
},
{
"code": null,
"e": 4890,
"s": 3919,
"text": "#include<bits/stdc++.h>\nusing namespace std;\nvoid insert(vector<int> vec[], int parent, int child){\n vec[parent].push_back(child);\n vec[child].push_back(parent);\n}\nvoid recurred(int temp, vector<int> vec[], vector<bool> &check){\n check[temp] = true;\n int size = vec[temp].size();\n for(int i = 0; i < size; i++){\n if (check[vec[temp][i]] == false){\n recurred(vec[temp][i], vec, check);\n }\n }\n}\nint Trees_Forest(vector<int> vec[], int vertice){\n int count = 0;\n vector<bool> check(vertice, false);\n for(int i = 0; i < vertice; i++){\n if(check[i] == false){\n recurred(i, vec, check);\n count++;\n }\n }\n return count;\n}\nint main(){\n int vertice = 9;\n vector<int> vec[vertice];\n insert(vec, 1, 3);\n insert(vec, 2, 8);\n insert(vec, 2, 6);\n insert(vec, 3, 5);\n insert(vec, 3, 7);\n insert(vec, 4, 8);\n cout<<\"Count of number of trees in a forest are: \"<<Trees_Forest(vec, vertice);\n return 0;\n}"
},
{
"code": null,
"e": 4955,
"s": 4890,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 4999,
"s": 4955,
"text": "Count of number of trees in a forest are: 3"
}
] |
Python - How to read config.ini files - onlinetutorialspoint
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we are going to see how to read python config .ini file.
The python’s configparser module used to read the .ini files, typically these file contains configuration information.
The following few examples illustrate some of the more interesting features of the ConfigParsermodule. First, consider a sample .ini file:
[dev]
LOG_FILE_PATH = %(BASEDIR)s/app.log
secret_key = DEV_SECRET_KEY
secret_value = DEV_SECRET_VALUE
BASEDIR = /opt/logs
port = 8080
is_debug = on
app_base_url = dev.myapp.com
[stage]
LOG_FILE_PATH = %(basedir)s/app.log
secret_key = STAGE_SECRET_KEY
secret_value = STAGE_SECRET_VALUE
BASEDIR = /opt/logs
port = 8088
is_debug = off
app_base_url = stage.myapp.com
Let’s read the above app_config.ini file using the python configparser module.
from configparser import ConfigParser
cfg = ConfigParser()
cfg.read('app_config.ini')
print ("Sections : ", cfg.sections())
for section in cfg.sections():
print("SECTION -> ",section)
print("-------------------")
print('LOG_FILE_PATH - ' , cfg.get(section,'LOG_FILE_PATH'))
print('SECRET_KEY - ', cfg.get(section,'SECRET_KEY'))
print('SECRET_VALUE - ' , cfg.get(section,'SECRET_VALUE'))
print('PORT - ' , cfg.get(section,'PORT'))
print('APP_BASE_URL - ' , cfg.get(section,'APP_BASE_URL'))
print('IS_DEBUG - ', cfg.getboolean(section, 'IS_DEBUG'))
Output:
Sections : ['dev', 'stage']
SECTION -> dev
-------------------
LOG_FILE_PATH - /opt/logs/app.log
SECRET_KEY - DEV_SECRET_KEY
SECRET_VALUE - DEV_SECRET_VALUE
PORT - 8080
APP_BASE_URL - dev.myapp.com
IS_DEBUG - True
SECTION -> stage
-------------------
LOG_FILE_PATH - /opt/logs/app.log
SECRET_KEY - STAGE_SECRET_KEY
SECRET_VALUE - STAGE_SECRET_VALUE
PORT - 8088
APP_BASE_URL - stage.myapp.com
IS_DEBUG - False
Configuration parameters are case insensitive. Thus, if your program is reading a parameter 'log_file_path', it does not matter if the configuration file uses 'log_file_path', 'LOG_FILE_PATH', or 'Log_File_Path
Configuration parameters can include variable substitutions such as '%(BASEDIR)s' as seen in the file. These substitutions are also case insensitive.
The definition order of configuration parameters does not matter in these substitutions. For example, in config.ini, the LOGFILE parameter makes a reference to the BASEDIR parameter, which is defined later in the file.
The values in configuration files are often interpreted correctly even if they don’t exactly match Python syntax or datatypes. For example, the 'on' value of the IS_DEBUG parameter is interpreted as True by the cfg.getboolean()method.
The configuration files have the ability to merge together, suppose we have separate .ini file for each environment, we can merge among them and read the content.
[prod]
LOG_FILE_PATH = %(BASEDIR)s/app.log
secret_key = PROD_SECRET_KEY
secret_value = PROD_SECRET_VALUE
BASEDIR = /opt/app/logs
port = 8000
is_debug = off
app_base_url = myapp.com
read the prod_app_config.ini file soon after reading the config.ini file like below, so that both the config files made available to read the content.
from configparser import ConfigParser
cfg = ConfigParser()
cfg.read('app_config.ini')
cfg.read('prod_app_config.ini')
print ("Sections : ", cfg.sections())
for section in cfg.sections():
print("SECTION -> ",section)
print("-------------------")
print('LOG_FILE_PATH - ' , cfg.get(section,'LOG_FILE_PATH'))
print('SECRET_KEY - ', cfg.get(section,'SECRET_KEY'))
print('SECRET_VALUE - ' , cfg.get(section,'SECRET_VALUE'))
print('PORT - ' , cfg.get(section,'PORT'))
print('APP_BASE_URL - ' , cfg.get(section,'APP_BASE_URL'))
print('IS_DEBUG - ' , cfg.getboolean(section,'is_debug'))
you can observe the Sections in the output now we could see [‘dev’, ‘stage’, ‘prod’].
Sections : ['dev', 'stage', 'prod']
SECTION -> dev
-------------------
LOG_FILE_PATH - /opt/logs/app.log
SECRET_KEY - DEV_SECRET_KEY
SECRET_VALUE - DEV_SECRET_VALUE
PORT - 8080
APP_BASE_URL - dev.myapp.com
IS_DEBUG - True
SECTION -> stage
-------------------
LOG_FILE_PATH - /opt/logs/app.log
SECRET_KEY - STAGE_SECRET_KEY
SECRET_VALUE - STAGE_SECRET_VALUE
PORT - 8088
APP_BASE_URL - stage.myapp.com
IS_DEBUG - False
SECTION -> prod
-------------------
LOG_FILE_PATH - /opt/app/logs/app.log
SECRET_KEY - PROD_SECRET_KEY
SECRET_VALUE - PROD_SECRET_VALUE
PORT - 8000
APP_BASE_URL - myapp.com
IS_DEBUG - False
More on ConfigParser
Python command-line arguments
Happy Learning 🙂
Pandas read_excel – Read Excel files in Pandas
Python How to read input from keyboard
Python raw_input read input from keyboard
How to read a text file in Python ?
How to read JSON file in Python ?
How to Read CSV File in Python
Java 8 walk How to Read all files in a folder
Python read data from MySQL Database
Python – How to Read Google Search Results in Selenium
Pandas read_csv – Read CSV file in Pandas and prepare Dataframe
How to Delete a File or Directory in Python
Python – How to create Zip File in Python ?
How to Remove Spaces from String in Python
How to do Multiprocessing in Python
How to get Words Count in Python from a File
Pandas read_excel – Read Excel files in Pandas
Python How to read input from keyboard
Python raw_input read input from keyboard
How to read a text file in Python ?
How to read JSON file in Python ?
How to Read CSV File in Python
Java 8 walk How to Read all files in a folder
Python read data from MySQL Database
Python – How to Read Google Search Results in Selenium
Pandas read_csv – Read CSV file in Pandas and prepare Dataframe
How to Delete a File or Directory in Python
Python – How to create Zip File in Python ?
How to Remove Spaces from String in Python
How to do Multiprocessing in Python
How to get Words Count in Python from a File
Δ
Python – Introduction
Python – Features
Python – Install on Windows
Python – Modes of Program
Python – Number System
Python – Identifiers
Python – Operators
Python – Ternary Operator
Python – Command Line Arguments
Python – Keywords
Python – Data Types
Python – Upgrade Python PIP
Python – Virtual Environment
Pyhton – Type Casting
Python – String to Int
Python – Conditional Statements
Python – if statement
Python – *args and **kwargs
Python – Date Formatting
Python – Read input from keyboard
Python – raw_input
Python – List In Depth
Python – List Comprehension
Python – Set in Depth
Python – Dictionary in Depth
Python – Tuple in Depth
Python – Stack Datastructure
Python – Classes and Objects
Python – Constructors
Python – Object Introspection
Python – Inheritance
Python – Decorators
Python – Serialization with Pickle
Python – Exceptions Handling
Python – User defined Exceptions
Python – Multiprocessing
Python – Default function parameters
Python – Lambdas Functions
Python – NumPy Library
Python – MySQL Connector
Python – MySQL Create Database
Python – MySQL Read Data
Python – MySQL Insert Data
Python – MySQL Update Records
Python – MySQL Delete Records
Python – String Case Conversion
Howto – Find biggest of 2 numbers
Howto – Remove duplicates from List
Howto – Convert any Number to Binary
Howto – Merge two Lists
Howto – Merge two dicts
Howto – Get Characters Count in a File
Howto – Get Words Count in a File
Howto – Remove Spaces from String
Howto – Read Env variables
Howto – Read a text File
Howto – Read a JSON File
Howto – Read Config.ini files
Howto – Iterate Dictionary
Howto – Convert List Of Objects to CSV
Howto – Merge two dict in Python
Howto – create Zip File
Howto – Get OS info
Howto – Get size of Directory
Howto – Check whether a file exists
Howto – Remove key from dictionary
Howto – Sort Objects
Howto – Create or Delete Directories
Howto – Read CSV File
Howto – Create Python Iterable class
Howto – Access for loop index
Howto – Clear all elements from List
Howto – Remove empty lists from a List
Howto – Remove special characters from String
Howto – Sort dictionary by key
Howto – Filter a list
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 473,
"s": 398,
"text": "In this tutorial, we are going to see how to read python config .ini file."
},
{
"code": null,
"e": 592,
"s": 473,
"text": "The python’s configparser module used to read the .ini files, typically these file contains configuration information."
},
{
"code": null,
"e": 731,
"s": 592,
"text": "The following few examples illustrate some of the more interesting features of the ConfigParsermodule. First, consider a sample .ini file:"
},
{
"code": null,
"e": 1095,
"s": 731,
"text": "[dev]\nLOG_FILE_PATH = %(BASEDIR)s/app.log\nsecret_key = DEV_SECRET_KEY\nsecret_value = DEV_SECRET_VALUE\nBASEDIR = /opt/logs\nport = 8080\nis_debug = on\napp_base_url = dev.myapp.com\n\n[stage]\nLOG_FILE_PATH = %(basedir)s/app.log\nsecret_key = STAGE_SECRET_KEY\nsecret_value = STAGE_SECRET_VALUE\nBASEDIR = /opt/logs\nport = 8088\nis_debug = off\napp_base_url = stage.myapp.com"
},
{
"code": null,
"e": 1174,
"s": 1095,
"text": "Let’s read the above app_config.ini file using the python configparser module."
},
{
"code": null,
"e": 1756,
"s": 1174,
"text": "from configparser import ConfigParser\n\ncfg = ConfigParser()\ncfg.read('app_config.ini')\n\nprint (\"Sections : \", cfg.sections())\n\nfor section in cfg.sections():\n print(\"SECTION -> \",section)\n print(\"-------------------\")\n print('LOG_FILE_PATH - ' , cfg.get(section,'LOG_FILE_PATH'))\n print('SECRET_KEY - ', cfg.get(section,'SECRET_KEY'))\n print('SECRET_VALUE - ' , cfg.get(section,'SECRET_VALUE'))\n print('PORT - ' , cfg.get(section,'PORT'))\n print('APP_BASE_URL - ' , cfg.get(section,'APP_BASE_URL'))\n print('IS_DEBUG - ', cfg.getboolean(section, 'IS_DEBUG'))"
},
{
"code": null,
"e": 1764,
"s": 1756,
"text": "Output:"
},
{
"code": null,
"e": 2186,
"s": 1764,
"text": "Sections : ['dev', 'stage']\nSECTION -> dev\n-------------------\nLOG_FILE_PATH - /opt/logs/app.log\nSECRET_KEY - DEV_SECRET_KEY\nSECRET_VALUE - DEV_SECRET_VALUE\nPORT - 8080\nAPP_BASE_URL - dev.myapp.com\nIS_DEBUG - True\nSECTION -> stage\n-------------------\nLOG_FILE_PATH - /opt/logs/app.log\nSECRET_KEY - STAGE_SECRET_KEY\nSECRET_VALUE - STAGE_SECRET_VALUE\nPORT - 8088\nAPP_BASE_URL - stage.myapp.com\nIS_DEBUG - False"
},
{
"code": null,
"e": 2397,
"s": 2186,
"text": "Configuration parameters are case insensitive. Thus, if your program is reading a parameter 'log_file_path', it does not matter if the configuration file uses 'log_file_path', 'LOG_FILE_PATH', or 'Log_File_Path"
},
{
"code": null,
"e": 2547,
"s": 2397,
"text": "Configuration parameters can include variable substitutions such as '%(BASEDIR)s' as seen in the file. These substitutions are also case insensitive."
},
{
"code": null,
"e": 2766,
"s": 2547,
"text": "The definition order of configuration parameters does not matter in these substitutions. For example, in config.ini, the LOGFILE parameter makes a reference to the BASEDIR parameter, which is defined later in the file."
},
{
"code": null,
"e": 3001,
"s": 2766,
"text": "The values in configuration files are often interpreted correctly even if they don’t exactly match Python syntax or datatypes. For example, the 'on' value of the IS_DEBUG parameter is interpreted as True by the cfg.getboolean()method."
},
{
"code": null,
"e": 3164,
"s": 3001,
"text": "The configuration files have the ability to merge together, suppose we have separate .ini file for each environment, we can merge among them and read the content."
},
{
"code": null,
"e": 3346,
"s": 3164,
"text": "[prod]\nLOG_FILE_PATH = %(BASEDIR)s/app.log\nsecret_key = PROD_SECRET_KEY\nsecret_value = PROD_SECRET_VALUE\nBASEDIR = /opt/app/logs\nport = 8000\nis_debug = off\napp_base_url = myapp.com\n"
},
{
"code": null,
"e": 3497,
"s": 3346,
"text": "read the prod_app_config.ini file soon after reading the config.ini file like below, so that both the config files made available to read the content."
},
{
"code": null,
"e": 4112,
"s": 3497,
"text": "from configparser import ConfigParser\n\ncfg = ConfigParser()\ncfg.read('app_config.ini')\ncfg.read('prod_app_config.ini')\n\nprint (\"Sections : \", cfg.sections())\n\nfor section in cfg.sections():\n print(\"SECTION -> \",section)\n print(\"-------------------\")\n print('LOG_FILE_PATH - ' , cfg.get(section,'LOG_FILE_PATH'))\n print('SECRET_KEY - ', cfg.get(section,'SECRET_KEY'))\n print('SECRET_VALUE - ' , cfg.get(section,'SECRET_VALUE'))\n print('PORT - ' , cfg.get(section,'PORT'))\n print('APP_BASE_URL - ' , cfg.get(section,'APP_BASE_URL'))\n print('IS_DEBUG - ' , cfg.getboolean(section,'is_debug'))\n"
},
{
"code": null,
"e": 4198,
"s": 4112,
"text": "you can observe the Sections in the output now we could see [‘dev’, ‘stage’, ‘prod’]."
},
{
"code": null,
"e": 4827,
"s": 4198,
"text": "Sections : ['dev', 'stage', 'prod']\nSECTION -> dev\n-------------------\nLOG_FILE_PATH - /opt/logs/app.log\nSECRET_KEY - DEV_SECRET_KEY\nSECRET_VALUE - DEV_SECRET_VALUE\nPORT - 8080\nAPP_BASE_URL - dev.myapp.com\nIS_DEBUG - True\nSECTION -> stage\n-------------------\nLOG_FILE_PATH - /opt/logs/app.log\nSECRET_KEY - STAGE_SECRET_KEY\nSECRET_VALUE - STAGE_SECRET_VALUE\nPORT - 8088\nAPP_BASE_URL - stage.myapp.com\nIS_DEBUG - False\nSECTION -> prod\n-------------------\nLOG_FILE_PATH - /opt/app/logs/app.log\nSECRET_KEY - PROD_SECRET_KEY\nSECRET_VALUE - PROD_SECRET_VALUE\nPORT - 8000\nAPP_BASE_URL - myapp.com\nIS_DEBUG - False"
},
{
"code": null,
"e": 4848,
"s": 4827,
"text": "More on ConfigParser"
},
{
"code": null,
"e": 4878,
"s": 4848,
"text": "Python command-line arguments"
},
{
"code": null,
"e": 4895,
"s": 4878,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 5540,
"s": 4895,
"text": "\nPandas read_excel – Read Excel files in Pandas\nPython How to read input from keyboard\nPython raw_input read input from keyboard\nHow to read a text file in Python ?\nHow to read JSON file in Python ?\nHow to Read CSV File in Python\nJava 8 walk How to Read all files in a folder\nPython read data from MySQL Database\nPython – How to Read Google Search Results in Selenium\nPandas read_csv – Read CSV file in Pandas and prepare Dataframe\nHow to Delete a File or Directory in Python\nPython – How to create Zip File in Python ?\nHow to Remove Spaces from String in Python\nHow to do Multiprocessing in Python\nHow to get Words Count in Python from a File\n"
},
{
"code": null,
"e": 5587,
"s": 5540,
"text": "Pandas read_excel – Read Excel files in Pandas"
},
{
"code": null,
"e": 5626,
"s": 5587,
"text": "Python How to read input from keyboard"
},
{
"code": null,
"e": 5668,
"s": 5626,
"text": "Python raw_input read input from keyboard"
},
{
"code": null,
"e": 5704,
"s": 5668,
"text": "How to read a text file in Python ?"
},
{
"code": null,
"e": 5738,
"s": 5704,
"text": "How to read JSON file in Python ?"
},
{
"code": null,
"e": 5769,
"s": 5738,
"text": "How to Read CSV File in Python"
},
{
"code": null,
"e": 5815,
"s": 5769,
"text": "Java 8 walk How to Read all files in a folder"
},
{
"code": null,
"e": 5852,
"s": 5815,
"text": "Python read data from MySQL Database"
},
{
"code": null,
"e": 5907,
"s": 5852,
"text": "Python – How to Read Google Search Results in Selenium"
},
{
"code": null,
"e": 5971,
"s": 5907,
"text": "Pandas read_csv – Read CSV file in Pandas and prepare Dataframe"
},
{
"code": null,
"e": 6015,
"s": 5971,
"text": "How to Delete a File or Directory in Python"
},
{
"code": null,
"e": 6059,
"s": 6015,
"text": "Python – How to create Zip File in Python ?"
},
{
"code": null,
"e": 6102,
"s": 6059,
"text": "How to Remove Spaces from String in Python"
},
{
"code": null,
"e": 6138,
"s": 6102,
"text": "How to do Multiprocessing in Python"
},
{
"code": null,
"e": 6183,
"s": 6138,
"text": "How to get Words Count in Python from a File"
},
{
"code": null,
"e": 6189,
"s": 6187,
"text": "Δ"
},
{
"code": null,
"e": 6212,
"s": 6189,
"text": " Python – Introduction"
},
{
"code": null,
"e": 6231,
"s": 6212,
"text": " Python – Features"
},
{
"code": null,
"e": 6260,
"s": 6231,
"text": " Python – Install on Windows"
},
{
"code": null,
"e": 6287,
"s": 6260,
"text": " Python – Modes of Program"
},
{
"code": null,
"e": 6311,
"s": 6287,
"text": " Python – Number System"
},
{
"code": null,
"e": 6333,
"s": 6311,
"text": " Python – Identifiers"
},
{
"code": null,
"e": 6353,
"s": 6333,
"text": " Python – Operators"
},
{
"code": null,
"e": 6380,
"s": 6353,
"text": " Python – Ternary Operator"
},
{
"code": null,
"e": 6413,
"s": 6380,
"text": " Python – Command Line Arguments"
},
{
"code": null,
"e": 6432,
"s": 6413,
"text": " Python – Keywords"
},
{
"code": null,
"e": 6453,
"s": 6432,
"text": " Python – Data Types"
},
{
"code": null,
"e": 6482,
"s": 6453,
"text": " Python – Upgrade Python PIP"
},
{
"code": null,
"e": 6512,
"s": 6482,
"text": " Python – Virtual Environment"
},
{
"code": null,
"e": 6535,
"s": 6512,
"text": " Pyhton – Type Casting"
},
{
"code": null,
"e": 6559,
"s": 6535,
"text": " Python – String to Int"
},
{
"code": null,
"e": 6592,
"s": 6559,
"text": " Python – Conditional Statements"
},
{
"code": null,
"e": 6615,
"s": 6592,
"text": " Python – if statement"
},
{
"code": null,
"e": 6644,
"s": 6615,
"text": " Python – *args and **kwargs"
},
{
"code": null,
"e": 6670,
"s": 6644,
"text": " Python – Date Formatting"
},
{
"code": null,
"e": 6705,
"s": 6670,
"text": " Python – Read input from keyboard"
},
{
"code": null,
"e": 6725,
"s": 6705,
"text": " Python – raw_input"
},
{
"code": null,
"e": 6749,
"s": 6725,
"text": " Python – List In Depth"
},
{
"code": null,
"e": 6778,
"s": 6749,
"text": " Python – List Comprehension"
},
{
"code": null,
"e": 6801,
"s": 6778,
"text": " Python – Set in Depth"
},
{
"code": null,
"e": 6831,
"s": 6801,
"text": " Python – Dictionary in Depth"
},
{
"code": null,
"e": 6856,
"s": 6831,
"text": " Python – Tuple in Depth"
},
{
"code": null,
"e": 6886,
"s": 6856,
"text": " Python – Stack Datastructure"
},
{
"code": null,
"e": 6916,
"s": 6886,
"text": " Python – Classes and Objects"
},
{
"code": null,
"e": 6939,
"s": 6916,
"text": " Python – Constructors"
},
{
"code": null,
"e": 6970,
"s": 6939,
"text": " Python – Object Introspection"
},
{
"code": null,
"e": 6992,
"s": 6970,
"text": " Python – Inheritance"
},
{
"code": null,
"e": 7013,
"s": 6992,
"text": " Python – Decorators"
},
{
"code": null,
"e": 7049,
"s": 7013,
"text": " Python – Serialization with Pickle"
},
{
"code": null,
"e": 7079,
"s": 7049,
"text": " Python – Exceptions Handling"
},
{
"code": null,
"e": 7113,
"s": 7079,
"text": " Python – User defined Exceptions"
},
{
"code": null,
"e": 7139,
"s": 7113,
"text": " Python – Multiprocessing"
},
{
"code": null,
"e": 7177,
"s": 7139,
"text": " Python – Default function parameters"
},
{
"code": null,
"e": 7205,
"s": 7177,
"text": " Python – Lambdas Functions"
},
{
"code": null,
"e": 7229,
"s": 7205,
"text": " Python – NumPy Library"
},
{
"code": null,
"e": 7255,
"s": 7229,
"text": " Python – MySQL Connector"
},
{
"code": null,
"e": 7287,
"s": 7255,
"text": " Python – MySQL Create Database"
},
{
"code": null,
"e": 7313,
"s": 7287,
"text": " Python – MySQL Read Data"
},
{
"code": null,
"e": 7341,
"s": 7313,
"text": " Python – MySQL Insert Data"
},
{
"code": null,
"e": 7372,
"s": 7341,
"text": " Python – MySQL Update Records"
},
{
"code": null,
"e": 7403,
"s": 7372,
"text": " Python – MySQL Delete Records"
},
{
"code": null,
"e": 7436,
"s": 7403,
"text": " Python – String Case Conversion"
},
{
"code": null,
"e": 7471,
"s": 7436,
"text": " Howto – Find biggest of 2 numbers"
},
{
"code": null,
"e": 7508,
"s": 7471,
"text": " Howto – Remove duplicates from List"
},
{
"code": null,
"e": 7546,
"s": 7508,
"text": " Howto – Convert any Number to Binary"
},
{
"code": null,
"e": 7572,
"s": 7546,
"text": " Howto – Merge two Lists"
},
{
"code": null,
"e": 7597,
"s": 7572,
"text": " Howto – Merge two dicts"
},
{
"code": null,
"e": 7637,
"s": 7597,
"text": " Howto – Get Characters Count in a File"
},
{
"code": null,
"e": 7672,
"s": 7637,
"text": " Howto – Get Words Count in a File"
},
{
"code": null,
"e": 7707,
"s": 7672,
"text": " Howto – Remove Spaces from String"
},
{
"code": null,
"e": 7736,
"s": 7707,
"text": " Howto – Read Env variables"
},
{
"code": null,
"e": 7762,
"s": 7736,
"text": " Howto – Read a text File"
},
{
"code": null,
"e": 7788,
"s": 7762,
"text": " Howto – Read a JSON File"
},
{
"code": null,
"e": 7820,
"s": 7788,
"text": " Howto – Read Config.ini files"
},
{
"code": null,
"e": 7848,
"s": 7820,
"text": " Howto – Iterate Dictionary"
},
{
"code": null,
"e": 7888,
"s": 7848,
"text": " Howto – Convert List Of Objects to CSV"
},
{
"code": null,
"e": 7922,
"s": 7888,
"text": " Howto – Merge two dict in Python"
},
{
"code": null,
"e": 7947,
"s": 7922,
"text": " Howto – create Zip File"
},
{
"code": null,
"e": 7968,
"s": 7947,
"text": " Howto – Get OS info"
},
{
"code": null,
"e": 7999,
"s": 7968,
"text": " Howto – Get size of Directory"
},
{
"code": null,
"e": 8036,
"s": 7999,
"text": " Howto – Check whether a file exists"
},
{
"code": null,
"e": 8073,
"s": 8036,
"text": " Howto – Remove key from dictionary"
},
{
"code": null,
"e": 8095,
"s": 8073,
"text": " Howto – Sort Objects"
},
{
"code": null,
"e": 8133,
"s": 8095,
"text": " Howto – Create or Delete Directories"
},
{
"code": null,
"e": 8156,
"s": 8133,
"text": " Howto – Read CSV File"
},
{
"code": null,
"e": 8194,
"s": 8156,
"text": " Howto – Create Python Iterable class"
},
{
"code": null,
"e": 8225,
"s": 8194,
"text": " Howto – Access for loop index"
},
{
"code": null,
"e": 8263,
"s": 8225,
"text": " Howto – Clear all elements from List"
},
{
"code": null,
"e": 8303,
"s": 8263,
"text": " Howto – Remove empty lists from a List"
},
{
"code": null,
"e": 8350,
"s": 8303,
"text": " Howto – Remove special characters from String"
},
{
"code": null,
"e": 8382,
"s": 8350,
"text": " Howto – Sort dictionary by key"
}
] |
Creating a solid Data Science development environment | by Gabriel dos Santos Gonçalves | Towards Data Science
|
Starting a Data Science project is usually fun, at least in the beginning. You get some data, start asking questions and exploring it, make some plots, try some models and after a few minutes, you have a bunch of interesting and chaotic insights and more data wrangling to do. Then you realize you have to organize your Jupyter notebook, start commenting and versioning your code, and that you need to dedicate some time to the “not so fun” part of your analysis. And more problems ahead if you need to share your findings with others, or put the model into production, as you find out that you don’t know exactly which libraries and versions you used during your analysis.
In general, we Data Scientists tend to focus more on the results (a model, a visualization, etc) than the process itself, meaning that we don’t pay enough attention to documentation and versioning as a much as a software engineer.
That being so, there is a general need to establish good practices for the development of Data Science projects, using the proper tools available today.
OBJECTIVE: The goal of this article is to present tools and directions for Data Scientists to manage their projects in a solid and reproducible manner by using four key tools: Conda, Git, DVC, and JupyterLab. By the end of this tutorial, you are going to be able to create a repository, version your scrips, datasets and models, and replicate this same development environment on new machines.
This tutorial was performed on a Linux machine running Ubuntu 18.04, but can be easily replicated on Mac or Windows using other command-line package managers like Homebrew (Mac), or Chocolatey (Windows).
Also, we are going to use AWS S3 to store our data files with DVC. To follow the same steps on the tutorial you need an AWS account with awscli installed and configured.
The project repository created following this tutorial can be accessed on my GitHub page.
Conda is an environment and package manager that can replace pipenv and pip in Python. It is part of Anaconda, a Python (and R) distribution focused on Data Science. You can choose to install the full version (Anaconda, around 3GB) or the light version (Miniconda, around 400MB). I recommend using Miniconda as you’ll only install the libraries you need. For a broader review, please take a look on Gergely Szerovay's article on Conda.
Git is a version control system for managing software development. With Git you can keep track of all the changes made on your code stored on your repository folder. You usually use cloud services like GitHub, Bitbucket or GitLab to connect to your local repositories to manage and store your repositories. We are going to use GitHub to store our project repository, so you need an active account to follow the steps of the tutorial.
DVC (Data Version Control) is the Git equivalent for managing your datasets and machine learning models. You link your Git repository to a cloud (AWS, Azure, Google Cloud Platform, etc) or local storage through DVC to store large files, as Git is not suited for files larger than 100MB. For a complete tutorial on DVC, please take a look on Dmitry Petrov’s article.
JupyterLab is an interactive development environment for Jupyter notebooks, code, and data. It is the latest release from Project Jupyter and it offers all the functionalities found in traditional Jupyter notebooks, with a more solid interface. Notebooks have become popular on Data Science projects for doing data wrangling and visualization, as it offers a great way to dynamically explore your data.
Code Editors are a must-have tool for programmers, and there are many open-source and paid options available today. So feel free to choose the code editor that better suits your needs.
Git Clients are tools that offer a graphical user interface for versioning your code and can be an interesting addition to the set of tools to help you manage your project.
To start organizing our development environment we need first to install the tools. We’ll start by installing Git (1) and configuring it (2) using our terminal.
# 1) Install Gitsudo apt-get install git# 2) Configure your Git accountgit config --global user.name "Your Name" git config --global user.email "yourmail@mail.com"
Next, we’ll install Miniconda, by downloading its latest release (3), changing the permission for the installation file (4) and running it (5). It is also important to add the Miniconda folder to your system’s path (6) to run its command by just typing conda on the terminal.
# 3) Download Miniconda latest release for Linuxwget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh# 4) Change the permission to run the Miniconda bash filechmod +x Miniconda3-latest-Linux-x86_64.sh# 5) Run Miniconda installation file./Miniconda3-latest-Linux-x86_64.sh# 6) Export the path to Miniconda installation folderexport PATH=/home/YOURNAME/miniconda3/bin:$PATH
Now that we have the tools installed it’s time to start setting our development environment.
First, we are going to define the variables with our GitHub information (8), create a remote repository on GitHub(9), and check if the creation was successful (10). Next, we create a local folder to store our project repository (11) and README file (12). Then we initiate our local Git repository (13) and push our first commit to GitHub (14).
# 8) Define the your GitHub information as variablesGitHubName=<YourGitHubName>GitHubPassword=<YourGitHubPassword># 9) Create a new git repository on GitHub # named "DataScience_DevEnv"curl -u $GitHubName:$GitHubPassword https://api.github.com/user/repos -d '{"name":"DataScience_DevEnv"}'# 10) Check if your new repository is available on GitHubcurl "https://api.github.com/users/$GitHubName/repos?per_page=100" | grep -w clone_url | grep -o '[^"]\+://.\+.git'# 11) Create a folder with the name of your repositorymkdir DataScience_DevEnvcd DataScience_DevEnv# 12) Create a README file for your repositoryecho "# Data Science development environment repository" >> README.md# 13) Initiate our local Git repositorygit init# 14) Add, commit and push README.md to GitHubgit add README.mdgit commit -m "first commit with README file"git remote add origin https://github.com/GabrielSGoncalves/DataScience_DevEnv.gitgit push -u origin master
We can check on our GitHub page if the repository were properly created with the first commit containing the README file.
Now that we have our Git repository all set, we are going to create our conda environment (15). We only need to define the name of our environment (-n), the python version and the libraries (eg. pandas and scikit-learn) we want to install. After the creation, we only need to type conda activate and the name of the environment (16).
# 15) Create o Conda environmentconda create -n datascience_devenv python=3.7 pandas scikit-learn# 16) Activate your environmentconda activate datascience_devenv
Now that we are working inside our conda environment, we can install JupyterLab (17) and DVC (18). Another great aspect of using conda is that it can also be used to install packages, just like we do with pip.
# 17) Install JupyterLab with# condaconda install -c conda-forge jupyterlab# or pippip install jupyterlab# 18) Install DVC with# condaconda install -c conda-forge dvc# or pippip install dvc
We can list the libraries available on our current environment by using the command list(19). We can also generate requirements files for your environments using conda or pip (20).
# 19) List your packages installed# with condaconda list# with pippip list# 20) Create requirements file# with condaconda list --export > requirements.txt# with pippip freeze > requirements.txt
To use DVC to store your large data files you need to configure a remote storage folder. We are going to use AWS S3 on our tutorial, but you have other options (local folder, Azure Blob Storage, Google Cloud Storage, Secure Shell, Hadoop Distributed File System, HTTP, and HTTPS protocols). During DVC installation you have to define the type of storage you are going to use and specify it under brackets (21). After the installation of the AWS S3 dependency for DVC, we initialize our DVC repository (22). Next, we are going to create a folder named data inside our repository to store our data files and to be versioned with DVC (23). Then we create an S3 bucket to remotely store our data files (24). It’s important to remember that we have already configured our awscli with our IAM credentials to run AWS commands using the terminal. After creating the S3 bucket, we define it as our DVC remote folder (25) and check if the last step was accepted (26). Now we can download a csv file to our data folder (27) and start versioning it with DVC (28).
# 21) Install DVC and its dependecies for connection with S3pip install dvc[s3]# 22) Initialize DVC repositorydvc init# 23) Create folder on repository to store data filesmkdir data# 24) Create S3 bucketaws s3 mb s3://dvc-datascience-devenv# 25) Define the new bucket as remote storage for DVCdvc remote add -d myremote s3://dvc-datascience-devenv# 26) List your DVC remote folderdvc remote list # 27) Download data filewget -P data/ https://dvc-repos-gsg.s3.amazonaws.com/models_pytorch_n_params.csv# 28) Add data file to DVCdvc add data/models_pytorch_n_params.csv
Whenever we add a file to DVC, it creates a .dvc file that tracks the changes made on the original file and can be versioned with Git. DVC also creates a .gitignore inside the data folder and adds the data file to it so that Git can ignore it, and we don't need to set it manually (29). Finally, we push our data file to our remote folder (the S3 bucket we created) using DVC (30).
# 29) Start tracking DVC file and .gitignore with Gitgit add data/.gitignore data/models_pytorch_n_params.csv.dvcgit commit -m "Start versioning csv file stored with DVC on S3 bucket"git push# 30) Push data file to DVC remote storage on S3 bucketdvc push
DVC can also help us built pipelines and perform experiments, making it easier to test and reproduce specific ETL steps. For more information on DVC features, please check out Gleb Ivashkevich’s article.
After installing JupyterLab we can run it by typing jupyter lab on our terminal. As a default setting, JupyterLab uses our base Python installation as the kernel, so if we try importing a library that you installed on our newly created conda environment (but not on base Python environment) we’ll get a ModuleNotFoundError . To fix this issue, we need to install the ipython kernel (31) from our environment (32). By doing this, we’ll have a kernel that corresponds to our conda environment, so every installed and newly installed library is going to be available on our JupyterLab environment. We can also check the available Jupyter kernels installed on our machine (33).
# 31) Install ipython using condaconda install ipykernel# 32) Install your kernel based on your working environmentipython kernel install --user --name=datascience_devenv# 33) List the kernels you have availablejupyter kernelspec list
As mentioned in the introduction, one important aspect of a solid development environment is the possibility to easily replicate it. One way to do it is by exporting the information about your conda environment to a YAML file (34). Remember that in order to do it you need to activate the environment first.
# 34) To export your current conda environment to YAMLconda env export > datascience_devenv.yaml# 35) Add the yaml file to our GitHub repositorygit add datascience_devenv.yamlgit commit -m 'add environment yaml to repo'git push
Until now our project repository has the following structure (36).
# 36) Project repository structuretree.├── data│ ├── models_pytorch_n_params.csv│ └── models_pytorch_n_params.csv.dvc├── datascience_devenv.yaml├── README.md└── requirements.txt
If we use the parameter -a with the command tree we can have a better notion of the configuration files that make Git and DVC (37). As mentioned before, DVC creates a .gitignore for each data file we add, so that Git avoid tracking it.
# 37) Detailed repository structuretree -a.├── data│ ├── .gitignore│ ├── models_pytorch_n_params.csv│ └── models_pytorch_n_params.csv.dvc├── datascience_devenv.yaml├── .dvc│ ├── cache│ │ └── 6f│ │ └── 387350081297a29ecde86ebfdf632c│ ├── config│ ├── .gitignore│ ├── state│ ├── tmp│ └── updater├── .git│ ├── branches│ ├── COMMIT_EDITMSG│ ├── config│ ├── description│ ├── HEAD│ ├── hooks│ │ ├── applypatch-msg.sample│ │ ├── commit-msg.sample│ │ ├── fsmonitor-watchman.sample│ │ ├── post-update.sample│ │ ├── pre-applypatch.sample│ │ ├── pre-commit.sample│ │ ├── prepare-commit-msg.sample│ │ ├── pre-push.sample│ │ ├── pre-rebase.sample│ │ ├── pre-receive.sample│ │ └── update.sample│ ├── index│ ├── info│ │ └── exclude│ ├── logs│ │ ├── HEAD│ │ └── refs│ │ ├── heads│ │ │ └── master│ │ └── remotes│ │ └── origin│ │ └── master│ ├── objects│ │ ├── 10│ │ │ └── c06accd2ad99b6cde7fc6e3f3cd36e766ce88f│ │ ├── 19│ │ │ └── 193f4a173c56c8d174ecc19700204d250e9067│ │ ├── 4e│ │ │ └── 0790499d1d09db63aaf1436ddbd91bfa043058│ │ ├── 52│ │ │ └── 4cb7d319626c1bcf24ca5184d83dc1df60c307│ │ ├── 5f│ │ │ └── 694b1bd973389b9c0cdbf6b6893bbad2c0ebc6│ │ ├── 61│ │ │ └── d5f990a1bee976a2f99b202f1dc14e33b43702│ │ ├── 67│ │ │ └── 3b06660535a92d0fdd72fe51c70c9ada47f22d│ │ ├── 70│ │ │ └── 1490f13b01089d7da8fa830bae3b6909d12875│ │ ├── 72│ │ │ └── a0ddbcc242d223cd71ee5a058fc99de2fa53cc│ │ ├── a3│ │ │ └── b5ebf7e3b752fa0da823aeb258b96e007b97ef│ │ ├── af│ │ │ └── 8017769b22fcba5945e836c3c2d454efa16bd1│ │ ├── c1│ │ │ └── 694ff5e7fe6493206eebf59ac31bf493eb7e6b│ │ ├── d7│ │ │ └── 39682b1f99f9a684cecdf976c24ddf3266b823│ │ ├── e4│ │ │ └── 5eca3c70f6f47e0a12f00b489aabc526c86e8b│ │ ├── e6│ │ │ └── 9de29bb2d1d6434b8b29ae775ad8c2e48c5391│ │ ├── ee│ │ │ └── 75f0e66a68873ac2f767c212c56411cd729eb2│ │ ├── info│ │ └── pack│ └── refs│ ├── heads│ │ └── master│ ├── remotes│ │ └── origin│ │ └── master│ └── tags├── README.md└── requirements.txt
Next, we create a .gitignore in the root of your repository for the rest of the files we don’t want to track (eg. Python compiled bytecode files, .pyc) with Git (38).
# 38) Add .gitignore for script files on our repositoryecho "*.pyc" >> .gitignoregit add .gitignoregit commit -m 'Add .gitignore for regular files'git push
Now we have our development environment configured and ready. Our JupyterLab has the kernel matching our conda environment, our data files are being versioned by DVC and our Git repository is tracking the rest of the files. So any change made on our project is going to be documented and can easily be replicated and tracked.
After setting our Git repository and configuring our DVC storage folder, we can replicate it on any new machine. Simply clone the repository (39), create a conda environment from the YAML file (40), activate it (41), create a JupyterLab kernel for our environment (42) and finally pull the data file from S3 bucket using DVC (43).
# 39) On a new machine, clone the repositorygit clone https://github.com/$GitHubName/DataScience_DevEnv.git# 40) Create conda environmentconda env create --file=datascience_devenv.yaml# 41) Activate environmentconda activate datascience_devenv# 42) Install the JupyterLab kernelipython kernel install --user --name=datascience_devenv# 43) Pull the data file from the S3 bucket using DVCdvc pull
So we can have the exactly same development environment on a new machine (including the data files and installed libraries) with just 5 commands.
In this article, we presented key tools to create a solid and reproducible development environment for Data Scientists. We do believe that Data Science is a field that can become even more mature by using best practices in project development and that Conda, Git, DVC, and JupyterLab are key components of this new approach
For a perspective on Data Science development environment more focused on practices and methods, please take a look at Will Koehrsen’s article.
You can find my other articles on my profile page 🔬
If you enjoyed it and want to become Medium a member you can use my referral link to also support me 👍
|
[
{
"code": null,
"e": 846,
"s": 172,
"text": "Starting a Data Science project is usually fun, at least in the beginning. You get some data, start asking questions and exploring it, make some plots, try some models and after a few minutes, you have a bunch of interesting and chaotic insights and more data wrangling to do. Then you realize you have to organize your Jupyter notebook, start commenting and versioning your code, and that you need to dedicate some time to the “not so fun” part of your analysis. And more problems ahead if you need to share your findings with others, or put the model into production, as you find out that you don’t know exactly which libraries and versions you used during your analysis."
},
{
"code": null,
"e": 1077,
"s": 846,
"text": "In general, we Data Scientists tend to focus more on the results (a model, a visualization, etc) than the process itself, meaning that we don’t pay enough attention to documentation and versioning as a much as a software engineer."
},
{
"code": null,
"e": 1230,
"s": 1077,
"text": "That being so, there is a general need to establish good practices for the development of Data Science projects, using the proper tools available today."
},
{
"code": null,
"e": 1624,
"s": 1230,
"text": "OBJECTIVE: The goal of this article is to present tools and directions for Data Scientists to manage their projects in a solid and reproducible manner by using four key tools: Conda, Git, DVC, and JupyterLab. By the end of this tutorial, you are going to be able to create a repository, version your scrips, datasets and models, and replicate this same development environment on new machines."
},
{
"code": null,
"e": 1828,
"s": 1624,
"text": "This tutorial was performed on a Linux machine running Ubuntu 18.04, but can be easily replicated on Mac or Windows using other command-line package managers like Homebrew (Mac), or Chocolatey (Windows)."
},
{
"code": null,
"e": 1998,
"s": 1828,
"text": "Also, we are going to use AWS S3 to store our data files with DVC. To follow the same steps on the tutorial you need an AWS account with awscli installed and configured."
},
{
"code": null,
"e": 2088,
"s": 1998,
"text": "The project repository created following this tutorial can be accessed on my GitHub page."
},
{
"code": null,
"e": 2524,
"s": 2088,
"text": "Conda is an environment and package manager that can replace pipenv and pip in Python. It is part of Anaconda, a Python (and R) distribution focused on Data Science. You can choose to install the full version (Anaconda, around 3GB) or the light version (Miniconda, around 400MB). I recommend using Miniconda as you’ll only install the libraries you need. For a broader review, please take a look on Gergely Szerovay's article on Conda."
},
{
"code": null,
"e": 2958,
"s": 2524,
"text": "Git is a version control system for managing software development. With Git you can keep track of all the changes made on your code stored on your repository folder. You usually use cloud services like GitHub, Bitbucket or GitLab to connect to your local repositories to manage and store your repositories. We are going to use GitHub to store our project repository, so you need an active account to follow the steps of the tutorial."
},
{
"code": null,
"e": 3324,
"s": 2958,
"text": "DVC (Data Version Control) is the Git equivalent for managing your datasets and machine learning models. You link your Git repository to a cloud (AWS, Azure, Google Cloud Platform, etc) or local storage through DVC to store large files, as Git is not suited for files larger than 100MB. For a complete tutorial on DVC, please take a look on Dmitry Petrov’s article."
},
{
"code": null,
"e": 3727,
"s": 3324,
"text": "JupyterLab is an interactive development environment for Jupyter notebooks, code, and data. It is the latest release from Project Jupyter and it offers all the functionalities found in traditional Jupyter notebooks, with a more solid interface. Notebooks have become popular on Data Science projects for doing data wrangling and visualization, as it offers a great way to dynamically explore your data."
},
{
"code": null,
"e": 3912,
"s": 3727,
"text": "Code Editors are a must-have tool for programmers, and there are many open-source and paid options available today. So feel free to choose the code editor that better suits your needs."
},
{
"code": null,
"e": 4085,
"s": 3912,
"text": "Git Clients are tools that offer a graphical user interface for versioning your code and can be an interesting addition to the set of tools to help you manage your project."
},
{
"code": null,
"e": 4246,
"s": 4085,
"text": "To start organizing our development environment we need first to install the tools. We’ll start by installing Git (1) and configuring it (2) using our terminal."
},
{
"code": null,
"e": 4410,
"s": 4246,
"text": "# 1) Install Gitsudo apt-get install git# 2) Configure your Git accountgit config --global user.name \"Your Name\" git config --global user.email \"yourmail@mail.com\""
},
{
"code": null,
"e": 4686,
"s": 4410,
"text": "Next, we’ll install Miniconda, by downloading its latest release (3), changing the permission for the installation file (4) and running it (5). It is also important to add the Miniconda folder to your system’s path (6) to run its command by just typing conda on the terminal."
},
{
"code": null,
"e": 5079,
"s": 4686,
"text": "# 3) Download Miniconda latest release for Linuxwget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh# 4) Change the permission to run the Miniconda bash filechmod +x Miniconda3-latest-Linux-x86_64.sh# 5) Run Miniconda installation file./Miniconda3-latest-Linux-x86_64.sh# 6) Export the path to Miniconda installation folderexport PATH=/home/YOURNAME/miniconda3/bin:$PATH"
},
{
"code": null,
"e": 5172,
"s": 5079,
"text": "Now that we have the tools installed it’s time to start setting our development environment."
},
{
"code": null,
"e": 5516,
"s": 5172,
"text": "First, we are going to define the variables with our GitHub information (8), create a remote repository on GitHub(9), and check if the creation was successful (10). Next, we create a local folder to store our project repository (11) and README file (12). Then we initiate our local Git repository (13) and push our first commit to GitHub (14)."
},
{
"code": null,
"e": 6456,
"s": 5516,
"text": "# 8) Define the your GitHub information as variablesGitHubName=<YourGitHubName>GitHubPassword=<YourGitHubPassword># 9) Create a new git repository on GitHub # named \"DataScience_DevEnv\"curl -u $GitHubName:$GitHubPassword https://api.github.com/user/repos -d '{\"name\":\"DataScience_DevEnv\"}'# 10) Check if your new repository is available on GitHubcurl \"https://api.github.com/users/$GitHubName/repos?per_page=100\" | grep -w clone_url | grep -o '[^\"]\\+://.\\+.git'# 11) Create a folder with the name of your repositorymkdir DataScience_DevEnvcd DataScience_DevEnv# 12) Create a README file for your repositoryecho \"# Data Science development environment repository\" >> README.md# 13) Initiate our local Git repositorygit init# 14) Add, commit and push README.md to GitHubgit add README.mdgit commit -m \"first commit with README file\"git remote add origin https://github.com/GabrielSGoncalves/DataScience_DevEnv.gitgit push -u origin master"
},
{
"code": null,
"e": 6578,
"s": 6456,
"text": "We can check on our GitHub page if the repository were properly created with the first commit containing the README file."
},
{
"code": null,
"e": 6912,
"s": 6578,
"text": "Now that we have our Git repository all set, we are going to create our conda environment (15). We only need to define the name of our environment (-n), the python version and the libraries (eg. pandas and scikit-learn) we want to install. After the creation, we only need to type conda activate and the name of the environment (16)."
},
{
"code": null,
"e": 7074,
"s": 6912,
"text": "# 15) Create o Conda environmentconda create -n datascience_devenv python=3.7 pandas scikit-learn# 16) Activate your environmentconda activate datascience_devenv"
},
{
"code": null,
"e": 7284,
"s": 7074,
"text": "Now that we are working inside our conda environment, we can install JupyterLab (17) and DVC (18). Another great aspect of using conda is that it can also be used to install packages, just like we do with pip."
},
{
"code": null,
"e": 7474,
"s": 7284,
"text": "# 17) Install JupyterLab with# condaconda install -c conda-forge jupyterlab# or pippip install jupyterlab# 18) Install DVC with# condaconda install -c conda-forge dvc# or pippip install dvc"
},
{
"code": null,
"e": 7655,
"s": 7474,
"text": "We can list the libraries available on our current environment by using the command list(19). We can also generate requirements files for your environments using conda or pip (20)."
},
{
"code": null,
"e": 7849,
"s": 7655,
"text": "# 19) List your packages installed# with condaconda list# with pippip list# 20) Create requirements file# with condaconda list --export > requirements.txt# with pippip freeze > requirements.txt"
},
{
"code": null,
"e": 8901,
"s": 7849,
"text": "To use DVC to store your large data files you need to configure a remote storage folder. We are going to use AWS S3 on our tutorial, but you have other options (local folder, Azure Blob Storage, Google Cloud Storage, Secure Shell, Hadoop Distributed File System, HTTP, and HTTPS protocols). During DVC installation you have to define the type of storage you are going to use and specify it under brackets (21). After the installation of the AWS S3 dependency for DVC, we initialize our DVC repository (22). Next, we are going to create a folder named data inside our repository to store our data files and to be versioned with DVC (23). Then we create an S3 bucket to remotely store our data files (24). It’s important to remember that we have already configured our awscli with our IAM credentials to run AWS commands using the terminal. After creating the S3 bucket, we define it as our DVC remote folder (25) and check if the last step was accepted (26). Now we can download a csv file to our data folder (27) and start versioning it with DVC (28)."
},
{
"code": null,
"e": 9468,
"s": 8901,
"text": "# 21) Install DVC and its dependecies for connection with S3pip install dvc[s3]# 22) Initialize DVC repositorydvc init# 23) Create folder on repository to store data filesmkdir data# 24) Create S3 bucketaws s3 mb s3://dvc-datascience-devenv# 25) Define the new bucket as remote storage for DVCdvc remote add -d myremote s3://dvc-datascience-devenv# 26) List your DVC remote folderdvc remote list # 27) Download data filewget -P data/ https://dvc-repos-gsg.s3.amazonaws.com/models_pytorch_n_params.csv# 28) Add data file to DVCdvc add data/models_pytorch_n_params.csv"
},
{
"code": null,
"e": 9850,
"s": 9468,
"text": "Whenever we add a file to DVC, it creates a .dvc file that tracks the changes made on the original file and can be versioned with Git. DVC also creates a .gitignore inside the data folder and adds the data file to it so that Git can ignore it, and we don't need to set it manually (29). Finally, we push our data file to our remote folder (the S3 bucket we created) using DVC (30)."
},
{
"code": null,
"e": 10105,
"s": 9850,
"text": "# 29) Start tracking DVC file and .gitignore with Gitgit add data/.gitignore data/models_pytorch_n_params.csv.dvcgit commit -m \"Start versioning csv file stored with DVC on S3 bucket\"git push# 30) Push data file to DVC remote storage on S3 bucketdvc push"
},
{
"code": null,
"e": 10309,
"s": 10105,
"text": "DVC can also help us built pipelines and perform experiments, making it easier to test and reproduce specific ETL steps. For more information on DVC features, please check out Gleb Ivashkevich’s article."
},
{
"code": null,
"e": 10983,
"s": 10309,
"text": "After installing JupyterLab we can run it by typing jupyter lab on our terminal. As a default setting, JupyterLab uses our base Python installation as the kernel, so if we try importing a library that you installed on our newly created conda environment (but not on base Python environment) we’ll get a ModuleNotFoundError . To fix this issue, we need to install the ipython kernel (31) from our environment (32). By doing this, we’ll have a kernel that corresponds to our conda environment, so every installed and newly installed library is going to be available on our JupyterLab environment. We can also check the available Jupyter kernels installed on our machine (33)."
},
{
"code": null,
"e": 11218,
"s": 10983,
"text": "# 31) Install ipython using condaconda install ipykernel# 32) Install your kernel based on your working environmentipython kernel install --user --name=datascience_devenv# 33) List the kernels you have availablejupyter kernelspec list"
},
{
"code": null,
"e": 11526,
"s": 11218,
"text": "As mentioned in the introduction, one important aspect of a solid development environment is the possibility to easily replicate it. One way to do it is by exporting the information about your conda environment to a YAML file (34). Remember that in order to do it you need to activate the environment first."
},
{
"code": null,
"e": 11754,
"s": 11526,
"text": "# 34) To export your current conda environment to YAMLconda env export > datascience_devenv.yaml# 35) Add the yaml file to our GitHub repositorygit add datascience_devenv.yamlgit commit -m 'add environment yaml to repo'git push"
},
{
"code": null,
"e": 11821,
"s": 11754,
"text": "Until now our project repository has the following structure (36)."
},
{
"code": null,
"e": 12003,
"s": 11821,
"text": "# 36) Project repository structuretree.├── data│ ├── models_pytorch_n_params.csv│ └── models_pytorch_n_params.csv.dvc├── datascience_devenv.yaml├── README.md└── requirements.txt"
},
{
"code": null,
"e": 12239,
"s": 12003,
"text": "If we use the parameter -a with the command tree we can have a better notion of the configuration files that make Git and DVC (37). As mentioned before, DVC creates a .gitignore for each data file we add, so that Git avoid tracking it."
},
{
"code": null,
"e": 14521,
"s": 12239,
"text": "# 37) Detailed repository structuretree -a.├── data│ ├── .gitignore│ ├── models_pytorch_n_params.csv│ └── models_pytorch_n_params.csv.dvc├── datascience_devenv.yaml├── .dvc│ ├── cache│ │ └── 6f│ │ └── 387350081297a29ecde86ebfdf632c│ ├── config│ ├── .gitignore│ ├── state│ ├── tmp│ └── updater├── .git│ ├── branches│ ├── COMMIT_EDITMSG│ ├── config│ ├── description│ ├── HEAD│ ├── hooks│ │ ├── applypatch-msg.sample│ │ ├── commit-msg.sample│ │ ├── fsmonitor-watchman.sample│ │ ├── post-update.sample│ │ ├── pre-applypatch.sample│ │ ├── pre-commit.sample│ │ ├── prepare-commit-msg.sample│ │ ├── pre-push.sample│ │ ├── pre-rebase.sample│ │ ├── pre-receive.sample│ │ └── update.sample│ ├── index│ ├── info│ │ └── exclude│ ├── logs│ │ ├── HEAD│ │ └── refs│ │ ├── heads│ │ │ └── master│ │ └── remotes│ │ └── origin│ │ └── master│ ├── objects│ │ ├── 10│ │ │ └── c06accd2ad99b6cde7fc6e3f3cd36e766ce88f│ │ ├── 19│ │ │ └── 193f4a173c56c8d174ecc19700204d250e9067│ │ ├── 4e│ │ │ └── 0790499d1d09db63aaf1436ddbd91bfa043058│ │ ├── 52│ │ │ └── 4cb7d319626c1bcf24ca5184d83dc1df60c307│ │ ├── 5f│ │ │ └── 694b1bd973389b9c0cdbf6b6893bbad2c0ebc6│ │ ├── 61│ │ │ └── d5f990a1bee976a2f99b202f1dc14e33b43702│ │ ├── 67│ │ │ └── 3b06660535a92d0fdd72fe51c70c9ada47f22d│ │ ├── 70│ │ │ └── 1490f13b01089d7da8fa830bae3b6909d12875│ │ ├── 72│ │ │ └── a0ddbcc242d223cd71ee5a058fc99de2fa53cc│ │ ├── a3│ │ │ └── b5ebf7e3b752fa0da823aeb258b96e007b97ef│ │ ├── af│ │ │ └── 8017769b22fcba5945e836c3c2d454efa16bd1│ │ ├── c1│ │ │ └── 694ff5e7fe6493206eebf59ac31bf493eb7e6b│ │ ├── d7│ │ │ └── 39682b1f99f9a684cecdf976c24ddf3266b823│ │ ├── e4│ │ │ └── 5eca3c70f6f47e0a12f00b489aabc526c86e8b│ │ ├── e6│ │ │ └── 9de29bb2d1d6434b8b29ae775ad8c2e48c5391│ │ ├── ee│ │ │ └── 75f0e66a68873ac2f767c212c56411cd729eb2│ │ ├── info│ │ └── pack│ └── refs│ ├── heads│ │ └── master│ ├── remotes│ │ └── origin│ │ └── master│ └── tags├── README.md└── requirements.txt"
},
{
"code": null,
"e": 14688,
"s": 14521,
"text": "Next, we create a .gitignore in the root of your repository for the rest of the files we don’t want to track (eg. Python compiled bytecode files, .pyc) with Git (38)."
},
{
"code": null,
"e": 14844,
"s": 14688,
"text": "# 38) Add .gitignore for script files on our repositoryecho \"*.pyc\" >> .gitignoregit add .gitignoregit commit -m 'Add .gitignore for regular files'git push"
},
{
"code": null,
"e": 15170,
"s": 14844,
"text": "Now we have our development environment configured and ready. Our JupyterLab has the kernel matching our conda environment, our data files are being versioned by DVC and our Git repository is tracking the rest of the files. So any change made on our project is going to be documented and can easily be replicated and tracked."
},
{
"code": null,
"e": 15501,
"s": 15170,
"text": "After setting our Git repository and configuring our DVC storage folder, we can replicate it on any new machine. Simply clone the repository (39), create a conda environment from the YAML file (40), activate it (41), create a JupyterLab kernel for our environment (42) and finally pull the data file from S3 bucket using DVC (43)."
},
{
"code": null,
"e": 15896,
"s": 15501,
"text": "# 39) On a new machine, clone the repositorygit clone https://github.com/$GitHubName/DataScience_DevEnv.git# 40) Create conda environmentconda env create --file=datascience_devenv.yaml# 41) Activate environmentconda activate datascience_devenv# 42) Install the JupyterLab kernelipython kernel install --user --name=datascience_devenv# 43) Pull the data file from the S3 bucket using DVCdvc pull"
},
{
"code": null,
"e": 16042,
"s": 15896,
"text": "So we can have the exactly same development environment on a new machine (including the data files and installed libraries) with just 5 commands."
},
{
"code": null,
"e": 16366,
"s": 16042,
"text": "In this article, we presented key tools to create a solid and reproducible development environment for Data Scientists. We do believe that Data Science is a field that can become even more mature by using best practices in project development and that Conda, Git, DVC, and JupyterLab are key components of this new approach"
},
{
"code": null,
"e": 16510,
"s": 16366,
"text": "For a perspective on Data Science development environment more focused on practices and methods, please take a look at Will Koehrsen’s article."
},
{
"code": null,
"e": 16562,
"s": 16510,
"text": "You can find my other articles on my profile page 🔬"
}
] |
Divide HuggingFace training time by 2 | Towards Data Science
|
update 06/04/2020: following a suggestion, experiments performed on large flavor of CamemBERT have been added to the report. TL;DR: training times have been reduced from 4h to 1h30.
I work at Lefebvre Sarrut, a publishing company which is a major player in the European legal industry. As explained in precedent articles, our needs require us to apply deep learning on very large text datasets (legal case anonymization, document classification, etc.), that is why we are so interested in making all our (machine learning) tools much faster.
In the spirit of a precedent article, the purpose of this one is to explore 2 very simple optimizations which may significantly decrease training time on Transformers library without negative effect on accuracy. We ran 21 experiments + 12 reproducibility experiments on a large well-known NLP dataset (French part of X-NLI), and we show that by simply using an out-of-the-box French BERT model (CamemBERT), default parameters, a single consumer grade GPU, and these optimizations, for base flavor of the model, we can reach, for 128 max token length, in a 16 min training an accuracy of 81.5%, beating by 0.5 points the score obtained with a 56 min training without any optimization, and beating by 0.3 points the score reported for this task by the CamemBERT model authors. Gains are even more impressive on the same model, for 493 max token length, where training time decreases from 4h38 without any optimization to 1h01 with all optimizations, still reaching the same score. Similar training time reduction have been reached with large model (from 4h to 1h30 for 128 tokens length).
Source code to reproduce the experiments is available there.
These optimizations are not task / model / language specific but provided code below is written for Pytorch.
If you are interested in this topic, follow me on Twitter: https://twitter.com/pommedeterre33
Moreover, we logged all our experiments on Weights & Biases, a kind of online Tensorboard with a larger scope, so you can analyze by yourself our experiment results, the report here.
(note that “uniform length batching” is named “smart batching” on the report)
“Dynamic/variable length padding” was a thing in NLP in 2017–2018, but now that a single neural network architecture makes any GPU owner able to reach SOTA scores on almost any task, it seems the NLP community has switched its focus from finding the optimal batch size to building stuff over the magic architecture. “Uniform length batching” is a naive idea to push dynamic padding gains further that we wanted to check.
At the time of this writing, both are not available out of the box on Transformers library for most common tasks.
You can find dynamic padding only for text generation/language modeling tasks. Hopefully, we will see that both techniques are easy to implement on the user side for common tasks (classification, etc.) and we think that most NLP practitioners should test/use them.
Over the last year, Transformers library from Hugging Face became the standard way to use large pre-trained language NLP models. It comes with plenty of features covering most NLP use cases, and has a polished API up to a point where you start to expect it to be perfect. This feeling is even stronger since version 2.9 bringing us the Trainer class, an adaptation of the carefully designed William Falcon’s Pytorch Lightning training API to specific Transformers requirements, which free users from most engineering aspects of training (Tensorboard logging, mixed precision, gradient accumulation, multi-GPU setup, etc.) and therefore is the new default way to fine-tune models.
In a situation where everything is so polished, you tend to believe that everything has been optimized to its maximum. One should not forget that the library is still young, and the team is working on several fronts at the same time (recent example being working with Tianlei Wu from Azure DevOps to leverage ONNX and reduce inference times in some setup). When you go deep inside the library, you may still find some interesting low-hanging fruits to seize.
We ran experiments and summarized what we found below and there.
If you are not yet a “padding / attention mask” expert, you may want to read this excellent article written for old style RNN (from William Falcon... again!). To make it short, training neural networks on a batch of sequences requires them to have the exact same length to build the batch matrix representation. Because real life NLP datasets are always made of texts of variable lengths, we often need to make some sequences shorter by truncating them, and some others longer by adding at the end a repeated fake token called “pad” token. Because the pad token doesn’t represent a real word/subword/signal, when most computations are done, before computing the loss, we erase the pad token signal by multiplying it by 0 through the attention mask matrix.
The main idea behind the 2 optimizations is to avoid as much unused computation as possible:
Dynamic padding: we limit the number of added pad tokens to reach the length of the longest sequence of each mini batch instead of a fixed value set for the whole train set. Because the number of added tokens changes across mini batches, we call it “dynamic” padding ;
Uniform length batching: we push the logic further by generating batches made of similar length sequences, so we avoid extreme cases where most sequences in the mini batch are short and we are required to add lots of pad tokens to each of them because 1 sequence of the same mini batch is very long.
Moreover, we check the benefit of a third option, mixed precision, what it’s worth alone or combined with the 2 techniques described above.
To check if these optimizations work well with a transformer based language model, we ran 14 experiments with different settings on the French part of X-NLI.
If you don’t know X-NLI, it is basically a sentence pair classification task where the model needs to guess if the second sentence entails/contradicts/is neutral compared to the first one (3 classes). X-NLI train set is a machine translation of a large English dataset, and test set is made of 5K pairs manually translated in 15 languages (including French) from the same English dataset.
The model used for the experiments is CamemBERT, a Roberta architecture trained with French texts by Facebook FAIR and Inria labs. Several flavors exist, figures below are related to the first one which have been released and known as camembert-base in Transformers (110M parameters trained on 130 Gb data). camembert-large experiments are available in the report.
Camembert paper authors reached an accuracy of 81.2% in 10 epochs with early stopping,1e-5 learning rate, sequence length of 512 tokens and few other things.
For each experiment, we limit training to 1 epoch because we only have access to a single GPU to run all experiments. All runs are using the same seed (exception being “reproducibility” experiments with different seeds, as explained below). If not said otherwise, hyper parameters are kept to default values because we do not have the resources to perform a grid search for each experiment. As we will see, in most experiments we beat the author reported score on X-NLI, so default settings are probably good enough.
X-NLI is mainly made of pairs of short sentences: when both parts of the pair are concatenated in a single sequence, over 97% of pairs have a length shorter than 128 tokens. This length distribution has a large impact on training time reduction opportunities. To make it short, on this dataset, it is OK to truncate sequences at 128 tokens to build “large” batches even on a consumer-grade GPU. On a more balanced dataset like Ms Marco, you need a 512-token limit to reach close to SOTA Mean Reciprocal Rank (a common information retrieval measure). In both cases, the 2 techniques presented here bring large training time reduction (by a factor of 2 or more), but for different reasons that we will analyze below. In our use of these optimizations on our private datasets, we always got a significant effect on training times, whatever the characteristic of the dataset.
Time and accuracy are measured on a single Nvidia 2080 TI GPU. Each combination of the 3 optimization options has been run 2 times, one with a batch of 64 sequences truncated to 128 tokens and a second time with a batch of 16 sequences (2 steps of 8 sequences and a single gradient accumulation) truncated to 493 tokens. 493 is the number of Camembert subword tokens in the longest sequence in number of characters, and probably one of the longest token sequences in number of tokens in the train set. The step sizes have been set to the maximum this GPU can take in memory.
Timings include intermediary evaluations (in our case every 500 mini batches) as in real life that’s how most NLP practitioners run training.
TL;DR :
Dynamic padding used alone provides a significant training time reduction, that can be reinforced by using uniform size batching and mixed precision;
On some setup (small mini batch size + short sequences), mixed precision can produce a longer training time, in other cases it is a game changer (large mini batch size and/or long sequences).
Across the 14 runs, 11 obtained in a single epoch a score above 81.18% (the score reported in the Camembert paper for 10 epochs with early stopping);
When we compare pairs of runs (same settings with truncation at 128 VS. truncation at 493), it appears unsurprisingly that truncation has on average a (small) cost in accuracy, even if only 3% of the dataset is concerned by the 128-token truncation.
By using both optimizations and mixed precision, we beat in a 16mn training the score of a 4h38 training!
Findings for base model are the same for large model, measures from the additional 12 experiments are in the report.
As explained above, pad token signal is canceled by the application of the attention mask. More pad tokens you put at the end of a sequence, more unused computations you will perform.
In the Trainer class, you define a (fixed) sequence length, and all sequences of the train set are padded / truncated to reach this length, without any exception. On X-NLI, shortest sequences are 10 tokens long, if you provide a 128 tokens length, you will add 118 pad tokens to those 10 tokens sequences, and then perform computations over those 118 noisy tokens.
Worst, as written in the original BERT repo README, “...attention is quadratic to the sequence length. In other words, a batch of 64 sequences of length 512 is much more expensive than a batch of 256 sequences of length 128.”.
A mini batch is made of a small selection of sequences sampled from the dataset. Even when selected randomly in X-NLI, chances are that the longest sequence in a mini batch is shorter than the maximum sequence length set for the whole train set. Because the learning / gradient descent is performed at the mini batch level, we have the opportunity to limit the padding effect, more precisely we can first search for the longest sequence length in the mini batch, and then pad the other sequences accordingly.
Those operations can be performed in the collate_fn function. The purpose of this function is described in the Pytorch documentation, basically it takes the individual examples returned by the Dataset and merges them to build the tensor matrix to send to the model.
As explained above, the idea is to adjust the sequence length at the mini batch level instead of dataset level. That way we can limit unused computation. The work is performed inside the Pytorch Dataloader. Let’s remind how it works:
The components:
Dataset() is the brick having access to the original text data, being a simple list of strings or something else like a database connector ;
Sampler() generates indexes to target a datapoint in the Dataset. It follows a strategy, for instance sequential generation (for a test set) or random generation (for a train set).
collate_fn() : for each mini batch, it receives the data points (from the Dataset) selected by the Sampler and groups them in a Tensor (theoretically it can be something else, but usually that’s what you expect as Dataloader output / model input).
collate_fn is the perfect place to perform the dynamic padding. Fortunately, Pytorch Dataloader has a parameter to provide our own implementation in its constructor, no need to override anything. Trainer class from Transformers library has a similar parameter in its constructor, we will use it. Instead of a function, it waits for an instance of a “Collator” (a Transformers specific class) which has a single purpose, wrap the collate method.
Find below a possible implementation of Collator class.
# ...def pad_seq(seq: List[int], max_batch_len: int, pad_value: int) -> List[int]: # IRL, use pad_sequence # https://pytorch.org/docs/master/generated/torch.nn.utils.rnn.pad_sequence.html return seq + (max_batch_len - len(seq)) * [pad_value]@dataclassclass SmartCollator(DataCollator): pad_token_id: int def collate_batch(self, batch: List[Features]) -> Dict[str, torch.Tensor]: batch_inputs = list() batch_attention_masks = list() labels = list() # find the max length of the mini batch max_size = max([len(ex.input_ids) for ex in batch]) for item in batch: # apply padding at the mini batch level batch_inputs += [pad_seq(item.input_ids, max_size, self.pad_token_id)] batch_attention_masks += [pad_seq(item.attention_mask, max_size, 0)] labels.append(item.label) # expected Transformers input format (dict of Tensors) return {"input_ids": torch.tensor(batch_inputs, dtype=torch.long), "attention_mask": torch.tensor(batch_attention_masks, dtype=torch.long), "labels": torch.tensor(labels, dtype=torch.long) }
We run 4 experiments that we group per batch size, for each group we compare cases where dynamic padding is used and not. When it is enabled for:
batches of 16 not truncated sequences, timing decreased from 4h39 to 0h59 (-79%) ;
batches of 64 sequences truncated to 128 tokens, timing decreased from 0h56 to 0h48 (-15%).
Timing decrease is in both cases significant, and is 4X stronger for long sequences. It makes sense, in the train set, 97% of examples are shorter than 128 tokens, so for most of them, we pay a tax for having a 493 max sequence size. By using the optimization, we pay only for the useful computation.
For 128 tokens truncation, there is still a gain as most sequences are still much smaller than 128 tokens, and BERT complexity being quadratic regarding its input length, the avoided computation cost is much lower and training time decreases of “only” 15%.
We run 4 experiments that we group per batch size, for each group we compare cases where dynamic padding is used and not. When it is enabled for:
batches of 16 not truncated sequences, accuracy raised from 81.42% to 82.0% ;
batches of 64 sequences truncated to 128 tokens, accuracy raised from 81.0% to 82.0%.
It appears that accuracy improves with dynamic padding in both cases.
Uniform size batching consists of simply building batches made of similar length sequences. The purpose is to make padding as minimal as possible when combined with dynamic padding.
There are many ways to implement it, the one we followed was to:
order examples by length in a simple Python list,
randomly select an index,
extract the example and the n examples following (n being the batch/step size),
delete the extracted examples from the list,
do it again until there are no more examples in the list.
That way each batch is made of similar length sequences, but following batches are of different lengths.
Naive (simple to understand / not clean) implementation may look something like this:
For time reduction, we previously show that dynamic padding brings large training time reduction, let’s compare training time with dynamic padding and no uniform size batching, and with both optimizations enabled. For:
batch of 16 not truncated sequences, training time decreases from 1h01 to 0h52 (-15%) ;
batch of 64 sequences truncated to 128 tokens, training time decreases from 0h48 to 0h30 (-38%).
So in both situations, our naive idea seems to bring another significant training time decrease.
Usually neural networks are trained on randomly ordered data points. Uniform size batching limits this randomness, hence introduces a kind of bias which may, in theory, impact accuracy.
We will compare the setups with and without the uniform size batching only:
For a batch of 16 examples when uniform length batching is activated, accuracy increases from 81.4% to 81.6%;
For a batch of 64 examples, when uniform size batching is activated, accuracy increases from 81.0% to 81.7%.
In both cases, there is an improvement, and we may conclude that there is no negative impact on accuracy.
However, we run many experiments combining several options, and according to the Weights & Biases dashboard, the use of uniform size batching is negatively correlated with accuracy. After a manual checking of experiments pairs (with/without the option), this effect is not obvious.
Mixed precision is possible on Pytorch through the Nvidia apex library. To make it short, in its most common mode, mixed precision consists of performing most operations with half precision and accumulating results in full precision (more info in apex documentation).
Apex is known for bringing improvement in some scenarios, sometimes it also brings some instability (e.g., the loss amplitude during training is bigger than without mixed precision), and quite rarely it avoids the model to converge. Said otherwise, it’s not a silver bullet, but an interesting tool to test on your case.
The good news is that Trainer class implements it out of the box, to leverage it, you just need to add the right flag to your command line (“ — fp16”).
Regarding training time for mini batches of 16 long sequences, the situation is unusual. For:
mixed precision alone makes things better by reducing training time from 4h38 to 2h50 ;
mixed precision combined with dynamic padding and uniform size batching, it makes training slower, from 0h52 to 1h01!
The reason is probably that in the second case, it adds overhead and doesn’t help that much as most batches are only made of short sequences. Mixed precision helps the most with big matrix operations.
When applied to mini batches of 64 short sequences, things are as expected:
Used alone, time training decreases from 0h56 to 0h26
Combined with the 2 other options, time decreases from 0h30 to 0h17
This time, even when the step is made of short sequence, each contains 64 sequences, making the matrix big enough to benefit from mixed precision.
Regarding accuracy, there is no clear pattern. You can make your own idea by yourself by checking the Weights & Biases report.
All experiments have been run using the same seed. It may happen that we were lucky and our approach was hitting accuracy but not with this seed and on this dataset.
We reran the 16 min training with all optimizations enabled setting 5 times with different seeds and accuracy / timing are reproduced.
Same kind of reproduction experiments have been also performed for the large model. Results are the same.
We have shown that both techniques constantly provide significant time reduction without reducing accuracy. Moreover, we learned that on a dataset with small batches, one should be careful with mixed precision, because it can lead to unexpected slower training if there is not enough computation to perform.
We are convinced that both techniques are low-hanging fruits that should be widely used by Transformers users.
To finish on a more general thought, we are pleasantly surprised by the results obtained by such simple ideas. Just for the story, in another unrelated experiment, we noticed that the French train set of X-NLI (which is a machine translation of an english dataset) was of low quality (many examples are absolute nonsense in French), and we were wondering if translating it with a better quality would improve the accuracy on the test set (which is a manual translation). It represented an important opportunity to us, because if it worked it would mean having plenty of dataset in French to play with. We spent a few bucks on DeepL, the translation was much better... and the accuracy didn’t change (we even thought there was a bug in our measures). Not all simple ideas are created equal!
|
[
{
"code": null,
"e": 354,
"s": 172,
"text": "update 06/04/2020: following a suggestion, experiments performed on large flavor of CamemBERT have been added to the report. TL;DR: training times have been reduced from 4h to 1h30."
},
{
"code": null,
"e": 714,
"s": 354,
"text": "I work at Lefebvre Sarrut, a publishing company which is a major player in the European legal industry. As explained in precedent articles, our needs require us to apply deep learning on very large text datasets (legal case anonymization, document classification, etc.), that is why we are so interested in making all our (machine learning) tools much faster."
},
{
"code": null,
"e": 1801,
"s": 714,
"text": "In the spirit of a precedent article, the purpose of this one is to explore 2 very simple optimizations which may significantly decrease training time on Transformers library without negative effect on accuracy. We ran 21 experiments + 12 reproducibility experiments on a large well-known NLP dataset (French part of X-NLI), and we show that by simply using an out-of-the-box French BERT model (CamemBERT), default parameters, a single consumer grade GPU, and these optimizations, for base flavor of the model, we can reach, for 128 max token length, in a 16 min training an accuracy of 81.5%, beating by 0.5 points the score obtained with a 56 min training without any optimization, and beating by 0.3 points the score reported for this task by the CamemBERT model authors. Gains are even more impressive on the same model, for 493 max token length, where training time decreases from 4h38 without any optimization to 1h01 with all optimizations, still reaching the same score. Similar training time reduction have been reached with large model (from 4h to 1h30 for 128 tokens length)."
},
{
"code": null,
"e": 1862,
"s": 1801,
"text": "Source code to reproduce the experiments is available there."
},
{
"code": null,
"e": 1971,
"s": 1862,
"text": "These optimizations are not task / model / language specific but provided code below is written for Pytorch."
},
{
"code": null,
"e": 2065,
"s": 1971,
"text": "If you are interested in this topic, follow me on Twitter: https://twitter.com/pommedeterre33"
},
{
"code": null,
"e": 2248,
"s": 2065,
"text": "Moreover, we logged all our experiments on Weights & Biases, a kind of online Tensorboard with a larger scope, so you can analyze by yourself our experiment results, the report here."
},
{
"code": null,
"e": 2326,
"s": 2248,
"text": "(note that “uniform length batching” is named “smart batching” on the report)"
},
{
"code": null,
"e": 2747,
"s": 2326,
"text": "“Dynamic/variable length padding” was a thing in NLP in 2017–2018, but now that a single neural network architecture makes any GPU owner able to reach SOTA scores on almost any task, it seems the NLP community has switched its focus from finding the optimal batch size to building stuff over the magic architecture. “Uniform length batching” is a naive idea to push dynamic padding gains further that we wanted to check."
},
{
"code": null,
"e": 2861,
"s": 2747,
"text": "At the time of this writing, both are not available out of the box on Transformers library for most common tasks."
},
{
"code": null,
"e": 3126,
"s": 2861,
"text": "You can find dynamic padding only for text generation/language modeling tasks. Hopefully, we will see that both techniques are easy to implement on the user side for common tasks (classification, etc.) and we think that most NLP practitioners should test/use them."
},
{
"code": null,
"e": 3806,
"s": 3126,
"text": "Over the last year, Transformers library from Hugging Face became the standard way to use large pre-trained language NLP models. It comes with plenty of features covering most NLP use cases, and has a polished API up to a point where you start to expect it to be perfect. This feeling is even stronger since version 2.9 bringing us the Trainer class, an adaptation of the carefully designed William Falcon’s Pytorch Lightning training API to specific Transformers requirements, which free users from most engineering aspects of training (Tensorboard logging, mixed precision, gradient accumulation, multi-GPU setup, etc.) and therefore is the new default way to fine-tune models."
},
{
"code": null,
"e": 4265,
"s": 3806,
"text": "In a situation where everything is so polished, you tend to believe that everything has been optimized to its maximum. One should not forget that the library is still young, and the team is working on several fronts at the same time (recent example being working with Tianlei Wu from Azure DevOps to leverage ONNX and reduce inference times in some setup). When you go deep inside the library, you may still find some interesting low-hanging fruits to seize."
},
{
"code": null,
"e": 4330,
"s": 4265,
"text": "We ran experiments and summarized what we found below and there."
},
{
"code": null,
"e": 5086,
"s": 4330,
"text": "If you are not yet a “padding / attention mask” expert, you may want to read this excellent article written for old style RNN (from William Falcon... again!). To make it short, training neural networks on a batch of sequences requires them to have the exact same length to build the batch matrix representation. Because real life NLP datasets are always made of texts of variable lengths, we often need to make some sequences shorter by truncating them, and some others longer by adding at the end a repeated fake token called “pad” token. Because the pad token doesn’t represent a real word/subword/signal, when most computations are done, before computing the loss, we erase the pad token signal by multiplying it by 0 through the attention mask matrix."
},
{
"code": null,
"e": 5179,
"s": 5086,
"text": "The main idea behind the 2 optimizations is to avoid as much unused computation as possible:"
},
{
"code": null,
"e": 5448,
"s": 5179,
"text": "Dynamic padding: we limit the number of added pad tokens to reach the length of the longest sequence of each mini batch instead of a fixed value set for the whole train set. Because the number of added tokens changes across mini batches, we call it “dynamic” padding ;"
},
{
"code": null,
"e": 5748,
"s": 5448,
"text": "Uniform length batching: we push the logic further by generating batches made of similar length sequences, so we avoid extreme cases where most sequences in the mini batch are short and we are required to add lots of pad tokens to each of them because 1 sequence of the same mini batch is very long."
},
{
"code": null,
"e": 5888,
"s": 5748,
"text": "Moreover, we check the benefit of a third option, mixed precision, what it’s worth alone or combined with the 2 techniques described above."
},
{
"code": null,
"e": 6046,
"s": 5888,
"text": "To check if these optimizations work well with a transformer based language model, we ran 14 experiments with different settings on the French part of X-NLI."
},
{
"code": null,
"e": 6435,
"s": 6046,
"text": "If you don’t know X-NLI, it is basically a sentence pair classification task where the model needs to guess if the second sentence entails/contradicts/is neutral compared to the first one (3 classes). X-NLI train set is a machine translation of a large English dataset, and test set is made of 5K pairs manually translated in 15 languages (including French) from the same English dataset."
},
{
"code": null,
"e": 6800,
"s": 6435,
"text": "The model used for the experiments is CamemBERT, a Roberta architecture trained with French texts by Facebook FAIR and Inria labs. Several flavors exist, figures below are related to the first one which have been released and known as camembert-base in Transformers (110M parameters trained on 130 Gb data). camembert-large experiments are available in the report."
},
{
"code": null,
"e": 6958,
"s": 6800,
"text": "Camembert paper authors reached an accuracy of 81.2% in 10 epochs with early stopping,1e-5 learning rate, sequence length of 512 tokens and few other things."
},
{
"code": null,
"e": 7475,
"s": 6958,
"text": "For each experiment, we limit training to 1 epoch because we only have access to a single GPU to run all experiments. All runs are using the same seed (exception being “reproducibility” experiments with different seeds, as explained below). If not said otherwise, hyper parameters are kept to default values because we do not have the resources to perform a grid search for each experiment. As we will see, in most experiments we beat the author reported score on X-NLI, so default settings are probably good enough."
},
{
"code": null,
"e": 8347,
"s": 7475,
"text": "X-NLI is mainly made of pairs of short sentences: when both parts of the pair are concatenated in a single sequence, over 97% of pairs have a length shorter than 128 tokens. This length distribution has a large impact on training time reduction opportunities. To make it short, on this dataset, it is OK to truncate sequences at 128 tokens to build “large” batches even on a consumer-grade GPU. On a more balanced dataset like Ms Marco, you need a 512-token limit to reach close to SOTA Mean Reciprocal Rank (a common information retrieval measure). In both cases, the 2 techniques presented here bring large training time reduction (by a factor of 2 or more), but for different reasons that we will analyze below. In our use of these optimizations on our private datasets, we always got a significant effect on training times, whatever the characteristic of the dataset."
},
{
"code": null,
"e": 8922,
"s": 8347,
"text": "Time and accuracy are measured on a single Nvidia 2080 TI GPU. Each combination of the 3 optimization options has been run 2 times, one with a batch of 64 sequences truncated to 128 tokens and a second time with a batch of 16 sequences (2 steps of 8 sequences and a single gradient accumulation) truncated to 493 tokens. 493 is the number of Camembert subword tokens in the longest sequence in number of characters, and probably one of the longest token sequences in number of tokens in the train set. The step sizes have been set to the maximum this GPU can take in memory."
},
{
"code": null,
"e": 9064,
"s": 8922,
"text": "Timings include intermediary evaluations (in our case every 500 mini batches) as in real life that’s how most NLP practitioners run training."
},
{
"code": null,
"e": 9072,
"s": 9064,
"text": "TL;DR :"
},
{
"code": null,
"e": 9222,
"s": 9072,
"text": "Dynamic padding used alone provides a significant training time reduction, that can be reinforced by using uniform size batching and mixed precision;"
},
{
"code": null,
"e": 9414,
"s": 9222,
"text": "On some setup (small mini batch size + short sequences), mixed precision can produce a longer training time, in other cases it is a game changer (large mini batch size and/or long sequences)."
},
{
"code": null,
"e": 9564,
"s": 9414,
"text": "Across the 14 runs, 11 obtained in a single epoch a score above 81.18% (the score reported in the Camembert paper for 10 epochs with early stopping);"
},
{
"code": null,
"e": 9814,
"s": 9564,
"text": "When we compare pairs of runs (same settings with truncation at 128 VS. truncation at 493), it appears unsurprisingly that truncation has on average a (small) cost in accuracy, even if only 3% of the dataset is concerned by the 128-token truncation."
},
{
"code": null,
"e": 9920,
"s": 9814,
"text": "By using both optimizations and mixed precision, we beat in a 16mn training the score of a 4h38 training!"
},
{
"code": null,
"e": 10037,
"s": 9920,
"text": "Findings for base model are the same for large model, measures from the additional 12 experiments are in the report."
},
{
"code": null,
"e": 10221,
"s": 10037,
"text": "As explained above, pad token signal is canceled by the application of the attention mask. More pad tokens you put at the end of a sequence, more unused computations you will perform."
},
{
"code": null,
"e": 10586,
"s": 10221,
"text": "In the Trainer class, you define a (fixed) sequence length, and all sequences of the train set are padded / truncated to reach this length, without any exception. On X-NLI, shortest sequences are 10 tokens long, if you provide a 128 tokens length, you will add 118 pad tokens to those 10 tokens sequences, and then perform computations over those 118 noisy tokens."
},
{
"code": null,
"e": 10813,
"s": 10586,
"text": "Worst, as written in the original BERT repo README, “...attention is quadratic to the sequence length. In other words, a batch of 64 sequences of length 512 is much more expensive than a batch of 256 sequences of length 128.”."
},
{
"code": null,
"e": 11322,
"s": 10813,
"text": "A mini batch is made of a small selection of sequences sampled from the dataset. Even when selected randomly in X-NLI, chances are that the longest sequence in a mini batch is shorter than the maximum sequence length set for the whole train set. Because the learning / gradient descent is performed at the mini batch level, we have the opportunity to limit the padding effect, more precisely we can first search for the longest sequence length in the mini batch, and then pad the other sequences accordingly."
},
{
"code": null,
"e": 11588,
"s": 11322,
"text": "Those operations can be performed in the collate_fn function. The purpose of this function is described in the Pytorch documentation, basically it takes the individual examples returned by the Dataset and merges them to build the tensor matrix to send to the model."
},
{
"code": null,
"e": 11822,
"s": 11588,
"text": "As explained above, the idea is to adjust the sequence length at the mini batch level instead of dataset level. That way we can limit unused computation. The work is performed inside the Pytorch Dataloader. Let’s remind how it works:"
},
{
"code": null,
"e": 11838,
"s": 11822,
"text": "The components:"
},
{
"code": null,
"e": 11979,
"s": 11838,
"text": "Dataset() is the brick having access to the original text data, being a simple list of strings or something else like a database connector ;"
},
{
"code": null,
"e": 12160,
"s": 11979,
"text": "Sampler() generates indexes to target a datapoint in the Dataset. It follows a strategy, for instance sequential generation (for a test set) or random generation (for a train set)."
},
{
"code": null,
"e": 12408,
"s": 12160,
"text": "collate_fn() : for each mini batch, it receives the data points (from the Dataset) selected by the Sampler and groups them in a Tensor (theoretically it can be something else, but usually that’s what you expect as Dataloader output / model input)."
},
{
"code": null,
"e": 12853,
"s": 12408,
"text": "collate_fn is the perfect place to perform the dynamic padding. Fortunately, Pytorch Dataloader has a parameter to provide our own implementation in its constructor, no need to override anything. Trainer class from Transformers library has a similar parameter in its constructor, we will use it. Instead of a function, it waits for an instance of a “Collator” (a Transformers specific class) which has a single purpose, wrap the collate method."
},
{
"code": null,
"e": 12909,
"s": 12853,
"text": "Find below a possible implementation of Collator class."
},
{
"code": null,
"e": 14080,
"s": 12909,
"text": "# ...def pad_seq(seq: List[int], max_batch_len: int, pad_value: int) -> List[int]: # IRL, use pad_sequence # https://pytorch.org/docs/master/generated/torch.nn.utils.rnn.pad_sequence.html return seq + (max_batch_len - len(seq)) * [pad_value]@dataclassclass SmartCollator(DataCollator): pad_token_id: int def collate_batch(self, batch: List[Features]) -> Dict[str, torch.Tensor]: batch_inputs = list() batch_attention_masks = list() labels = list() # find the max length of the mini batch max_size = max([len(ex.input_ids) for ex in batch]) for item in batch: # apply padding at the mini batch level batch_inputs += [pad_seq(item.input_ids, max_size, self.pad_token_id)] batch_attention_masks += [pad_seq(item.attention_mask, max_size, 0)] labels.append(item.label) # expected Transformers input format (dict of Tensors) return {\"input_ids\": torch.tensor(batch_inputs, dtype=torch.long), \"attention_mask\": torch.tensor(batch_attention_masks, dtype=torch.long), \"labels\": torch.tensor(labels, dtype=torch.long) }"
},
{
"code": null,
"e": 14226,
"s": 14080,
"text": "We run 4 experiments that we group per batch size, for each group we compare cases where dynamic padding is used and not. When it is enabled for:"
},
{
"code": null,
"e": 14309,
"s": 14226,
"text": "batches of 16 not truncated sequences, timing decreased from 4h39 to 0h59 (-79%) ;"
},
{
"code": null,
"e": 14401,
"s": 14309,
"text": "batches of 64 sequences truncated to 128 tokens, timing decreased from 0h56 to 0h48 (-15%)."
},
{
"code": null,
"e": 14702,
"s": 14401,
"text": "Timing decrease is in both cases significant, and is 4X stronger for long sequences. It makes sense, in the train set, 97% of examples are shorter than 128 tokens, so for most of them, we pay a tax for having a 493 max sequence size. By using the optimization, we pay only for the useful computation."
},
{
"code": null,
"e": 14959,
"s": 14702,
"text": "For 128 tokens truncation, there is still a gain as most sequences are still much smaller than 128 tokens, and BERT complexity being quadratic regarding its input length, the avoided computation cost is much lower and training time decreases of “only” 15%."
},
{
"code": null,
"e": 15105,
"s": 14959,
"text": "We run 4 experiments that we group per batch size, for each group we compare cases where dynamic padding is used and not. When it is enabled for:"
},
{
"code": null,
"e": 15183,
"s": 15105,
"text": "batches of 16 not truncated sequences, accuracy raised from 81.42% to 82.0% ;"
},
{
"code": null,
"e": 15269,
"s": 15183,
"text": "batches of 64 sequences truncated to 128 tokens, accuracy raised from 81.0% to 82.0%."
},
{
"code": null,
"e": 15339,
"s": 15269,
"text": "It appears that accuracy improves with dynamic padding in both cases."
},
{
"code": null,
"e": 15521,
"s": 15339,
"text": "Uniform size batching consists of simply building batches made of similar length sequences. The purpose is to make padding as minimal as possible when combined with dynamic padding."
},
{
"code": null,
"e": 15586,
"s": 15521,
"text": "There are many ways to implement it, the one we followed was to:"
},
{
"code": null,
"e": 15636,
"s": 15586,
"text": "order examples by length in a simple Python list,"
},
{
"code": null,
"e": 15662,
"s": 15636,
"text": "randomly select an index,"
},
{
"code": null,
"e": 15742,
"s": 15662,
"text": "extract the example and the n examples following (n being the batch/step size),"
},
{
"code": null,
"e": 15787,
"s": 15742,
"text": "delete the extracted examples from the list,"
},
{
"code": null,
"e": 15845,
"s": 15787,
"text": "do it again until there are no more examples in the list."
},
{
"code": null,
"e": 15950,
"s": 15845,
"text": "That way each batch is made of similar length sequences, but following batches are of different lengths."
},
{
"code": null,
"e": 16036,
"s": 15950,
"text": "Naive (simple to understand / not clean) implementation may look something like this:"
},
{
"code": null,
"e": 16255,
"s": 16036,
"text": "For time reduction, we previously show that dynamic padding brings large training time reduction, let’s compare training time with dynamic padding and no uniform size batching, and with both optimizations enabled. For:"
},
{
"code": null,
"e": 16343,
"s": 16255,
"text": "batch of 16 not truncated sequences, training time decreases from 1h01 to 0h52 (-15%) ;"
},
{
"code": null,
"e": 16440,
"s": 16343,
"text": "batch of 64 sequences truncated to 128 tokens, training time decreases from 0h48 to 0h30 (-38%)."
},
{
"code": null,
"e": 16537,
"s": 16440,
"text": "So in both situations, our naive idea seems to bring another significant training time decrease."
},
{
"code": null,
"e": 16723,
"s": 16537,
"text": "Usually neural networks are trained on randomly ordered data points. Uniform size batching limits this randomness, hence introduces a kind of bias which may, in theory, impact accuracy."
},
{
"code": null,
"e": 16799,
"s": 16723,
"text": "We will compare the setups with and without the uniform size batching only:"
},
{
"code": null,
"e": 16909,
"s": 16799,
"text": "For a batch of 16 examples when uniform length batching is activated, accuracy increases from 81.4% to 81.6%;"
},
{
"code": null,
"e": 17018,
"s": 16909,
"text": "For a batch of 64 examples, when uniform size batching is activated, accuracy increases from 81.0% to 81.7%."
},
{
"code": null,
"e": 17124,
"s": 17018,
"text": "In both cases, there is an improvement, and we may conclude that there is no negative impact on accuracy."
},
{
"code": null,
"e": 17406,
"s": 17124,
"text": "However, we run many experiments combining several options, and according to the Weights & Biases dashboard, the use of uniform size batching is negatively correlated with accuracy. After a manual checking of experiments pairs (with/without the option), this effect is not obvious."
},
{
"code": null,
"e": 17674,
"s": 17406,
"text": "Mixed precision is possible on Pytorch through the Nvidia apex library. To make it short, in its most common mode, mixed precision consists of performing most operations with half precision and accumulating results in full precision (more info in apex documentation)."
},
{
"code": null,
"e": 17995,
"s": 17674,
"text": "Apex is known for bringing improvement in some scenarios, sometimes it also brings some instability (e.g., the loss amplitude during training is bigger than without mixed precision), and quite rarely it avoids the model to converge. Said otherwise, it’s not a silver bullet, but an interesting tool to test on your case."
},
{
"code": null,
"e": 18147,
"s": 17995,
"text": "The good news is that Trainer class implements it out of the box, to leverage it, you just need to add the right flag to your command line (“ — fp16”)."
},
{
"code": null,
"e": 18241,
"s": 18147,
"text": "Regarding training time for mini batches of 16 long sequences, the situation is unusual. For:"
},
{
"code": null,
"e": 18329,
"s": 18241,
"text": "mixed precision alone makes things better by reducing training time from 4h38 to 2h50 ;"
},
{
"code": null,
"e": 18447,
"s": 18329,
"text": "mixed precision combined with dynamic padding and uniform size batching, it makes training slower, from 0h52 to 1h01!"
},
{
"code": null,
"e": 18648,
"s": 18447,
"text": "The reason is probably that in the second case, it adds overhead and doesn’t help that much as most batches are only made of short sequences. Mixed precision helps the most with big matrix operations."
},
{
"code": null,
"e": 18724,
"s": 18648,
"text": "When applied to mini batches of 64 short sequences, things are as expected:"
},
{
"code": null,
"e": 18778,
"s": 18724,
"text": "Used alone, time training decreases from 0h56 to 0h26"
},
{
"code": null,
"e": 18846,
"s": 18778,
"text": "Combined with the 2 other options, time decreases from 0h30 to 0h17"
},
{
"code": null,
"e": 18993,
"s": 18846,
"text": "This time, even when the step is made of short sequence, each contains 64 sequences, making the matrix big enough to benefit from mixed precision."
},
{
"code": null,
"e": 19120,
"s": 18993,
"text": "Regarding accuracy, there is no clear pattern. You can make your own idea by yourself by checking the Weights & Biases report."
},
{
"code": null,
"e": 19286,
"s": 19120,
"text": "All experiments have been run using the same seed. It may happen that we were lucky and our approach was hitting accuracy but not with this seed and on this dataset."
},
{
"code": null,
"e": 19421,
"s": 19286,
"text": "We reran the 16 min training with all optimizations enabled setting 5 times with different seeds and accuracy / timing are reproduced."
},
{
"code": null,
"e": 19527,
"s": 19421,
"text": "Same kind of reproduction experiments have been also performed for the large model. Results are the same."
},
{
"code": null,
"e": 19835,
"s": 19527,
"text": "We have shown that both techniques constantly provide significant time reduction without reducing accuracy. Moreover, we learned that on a dataset with small batches, one should be careful with mixed precision, because it can lead to unexpected slower training if there is not enough computation to perform."
},
{
"code": null,
"e": 19946,
"s": 19835,
"text": "We are convinced that both techniques are low-hanging fruits that should be widely used by Transformers users."
}
] |
Wiggle Sort in C++
|
Suppose we have an unsorted array called nums, we have to reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3].... and so on.
So, if the input is like nums = [3,5,2,1,6,4], then the output will be [3,5,1,6,2,4], there may be some other answers.
To solve this, we will follow these steps −
n := size of nums
n := size of nums
for initialize i := 0, when i < n - 1, update i := i + 1, do −if i is even and nums[i] > nums[i+1] is true or i is odd and nums[i] > nums[i+1] is false, thenswap(nums[i], nums[i + 1])
for initialize i := 0, when i < n - 1, update i := i + 1, do −
if i is even and nums[i] > nums[i+1] is true or i is odd and nums[i] > nums[i+1] is false, thenswap(nums[i], nums[i + 1])
if i is even and nums[i] > nums[i+1] is true or i is odd and nums[i] > nums[i+1] is false, then
swap(nums[i], nums[i + 1])
swap(nums[i], nums[i + 1])
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto< v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
class Solution {
public:
void wiggleSort(vector<int<& nums) {
int n = nums.size();
for(int i = 0; i < n - 1; i+=1){
if((i % 2 == 0) == ( nums[i] > nums[i + 1])){
swap(nums[i], nums[i + 1]);
}
}
}
};
main(){
vector<int< v = {3,5,2,1,6,4};
Solution ob;
ob.wiggleSort(v);
print_vector(v);
}
{3,5,2,1,6,4}
[3, 5, 1, 6, 2, 4, ]
|
[
{
"code": null,
"e": 1206,
"s": 1062,
"text": "Suppose we have an unsorted array called nums, we have to reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3].... and so on."
},
{
"code": null,
"e": 1325,
"s": 1206,
"text": "So, if the input is like nums = [3,5,2,1,6,4], then the output will be [3,5,1,6,2,4], there may be some other answers."
},
{
"code": null,
"e": 1369,
"s": 1325,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1387,
"s": 1369,
"text": "n := size of nums"
},
{
"code": null,
"e": 1405,
"s": 1387,
"text": "n := size of nums"
},
{
"code": null,
"e": 1589,
"s": 1405,
"text": "for initialize i := 0, when i < n - 1, update i := i + 1, do −if i is even and nums[i] > nums[i+1] is true or i is odd and nums[i] > nums[i+1] is false, thenswap(nums[i], nums[i + 1])"
},
{
"code": null,
"e": 1652,
"s": 1589,
"text": "for initialize i := 0, when i < n - 1, update i := i + 1, do −"
},
{
"code": null,
"e": 1774,
"s": 1652,
"text": "if i is even and nums[i] > nums[i+1] is true or i is odd and nums[i] > nums[i+1] is false, thenswap(nums[i], nums[i + 1])"
},
{
"code": null,
"e": 1870,
"s": 1774,
"text": "if i is even and nums[i] > nums[i+1] is true or i is odd and nums[i] > nums[i+1] is false, then"
},
{
"code": null,
"e": 1897,
"s": 1870,
"text": "swap(nums[i], nums[i + 1])"
},
{
"code": null,
"e": 1924,
"s": 1897,
"text": "swap(nums[i], nums[i + 1])"
},
{
"code": null,
"e": 1994,
"s": 1924,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2005,
"s": 1994,
"text": " Live Demo"
},
{
"code": null,
"e": 2549,
"s": 2005,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid print_vector(vector<auto< v){\n cout << \"[\";\n for(int i = 0; i<v.size(); i++){\n cout << v[i] << \", \";\n }\n cout << \"]\"<<endl;\n}\nclass Solution {\npublic:\n void wiggleSort(vector<int<& nums) {\n int n = nums.size();\n for(int i = 0; i < n - 1; i+=1){\n if((i % 2 == 0) == ( nums[i] > nums[i + 1])){\n swap(nums[i], nums[i + 1]);\n }\n }\n }\n};\nmain(){\n vector<int< v = {3,5,2,1,6,4};\n Solution ob;\n ob.wiggleSort(v);\n print_vector(v);\n}"
},
{
"code": null,
"e": 2563,
"s": 2549,
"text": "{3,5,2,1,6,4}"
},
{
"code": null,
"e": 2584,
"s": 2563,
"text": "[3, 5, 1, 6, 2, 4, ]"
}
] |
Count smaller values whose XOR with x is greater than x - GeeksforGeeks
|
06 May, 2021
Given a integer ‘x’, find the number of values of ‘a’ satisfying the following conditions:
a XOR x > x0 < a < x
a XOR x > x
0 < a < x
Examples :
Input : x = 10
Output : 5
Explanation: For x = 10, following 5 values
of 'a' satisfy the conditions:
1 XOR 10 = 11
4 XOR 10 = 14
5 XOR 10 = 15
6 XOR 10 = 12
7 XOR 10 = 13
Input : x = 2
Output : 1
Explanation: For x=2, we have just one value
1 XOR 2 = 3.
Naive Approach A Simple approach is to check for all values of ‘a’ between 0 and ‘x’ and calculate its XOR with x and check if the condition 1 satisfies.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find count of values// whose XOR with x is greater than x// and values are smaller than x#include<bits/stdc++.h>using namespace std; int countValues(int x){ int count = 0; for (int i=1; i < x; i++) if ((i ^ x) > x) count++; return count;} // Driver codeint main(){ int x = 10; cout << countValues(x); return 0;}
// Java program to find count of values// whose XOR with x is greater than x// and values are smaller than x public class XOR{ static int countValues(int x) { int count = 0; for (int i=1; i < x; i++) if ((i ^ x) > x) count++; return count; } public static void main (String[] args) { int x = 10; System.out.println(countValues(x)); }} // This code is contributed by Saket Kumar
# Python3 program to find# count of values whose# XOR with x is greater# than x and values are# smaller than x def countValues(x): count = 0 for i in range(1 ,x): if ((i ^ x) > x): count += 1 return count # Driver codex = 10print(countValues(x)) # This code is contributed# by Smitha
// C# program to find count of values// whose XOR with x is greater than x// and values are smaller than xusing System; class GFG{ static int countValues(int x) { int count = 0; for (int i = 1; i < x; i++) if ((i ^ x) > x) count++; return count; } public static void Main () { int x = 10; Console.Write(countValues(x)); }} // This code is contributed by nitin mittal.
<?php// PHP program to find count of values// whose XOR with x is greater than x// and values are smaller than x function countValues($x){ $count = 0; for ($i = 1; $i < $x; $i++) if (($i ^ $x) > $x) $count++; return $count;} // Driver code $x = 10; echo countValues($x); // This code is contributed by anuj_67.?>
<script> // Javascript program to find count of values// whose XOR with x is greater than x// and values are smaller than x function countValues(x){ let count = 0; for (let i=1; i < x; i++) if ((i ^ x) > x) count++; return count;} // Driver code let x = 10; document.write(countValues(x)); </script>
Output :
5
The time complexity of the above approach is O(x).
Efficient Approach The efficient solution lies in the binary representation of the number. We consider all 0’s in binary representation. For every 0 at the i-th position, we can have 2i numbers smaller than or equal to x with greater XOR.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find count of values// whose XOR with x is greater than x// and values are smaller than x#include<bits/stdc++.h>using namespace std; int countValues(int x){ // Initialize result int count = 0, n = 1; // Traversing through all bits of x while (x != 0) { // If current last bit of x is set // then increment count by n. Here // n is a power of 2 corresponding // to position of bit if (x%2 == 0) count += n; // Simultaneously calculate the 2^n n *= 2; // Replace x with x/2; x /= 2; } return count;} // Driver codeint main(){ int x = 10; cout << countValues(x); return 0;}
// Java program to find count of values// whose XOR with x is greater than x// and values are smaller than x class GFG{ static int countValues(int x) { // Initialize result int count = 0, n = 1; // Traversing through all bits of x while (x != 0) { // If current last bit of x is set // then increment count by n. Here // n is a power of 2 corresponding // to position of bit if (x % 2 == 0) count += n; // Simultaneously calculate the 2^n n *= 2; // Replace x with x/2; x /= 2; } return count; } // Driver code public static void main (String[] args) { int x = 10; System.out.println(countValues(x)); } } // This code is contributed by Saket Kumar
# Python3 program to find count# of values whose XOR with# x is greater than x and# values are smaller than x def countValues(x): # Initialize result count = 0; n = 1; # Traversing through # all bits of x while (x > 0): # If current last bit # of x is set then # increment count by # n. Here n is a power # of 2 corresponding # to position of bit if (x % 2 == 0): count += n; # Simultaneously # calculate the 2^n n *= 2; # Replace x with x/2; x /= 2; x = int(x); return count; # Driver codex = 10;print(countValues(x)); # This code is contributed# by mits
// C# program to find count of values// whose XOR with x is greater than x// and values are smaller than xusing System; class GFG{ static int countValues(int x) { // Initialize result int count = 0, n = 1; // Traversing through all bits of x while (x != 0) { // If current last bit of x is set // then increment count by n. Here // n is a power of 2 corresponding // to position of bit if (x % 2 == 0) count += n; // Simultaneously calculate the 2^n n *= 2; // Replace x with x/2; x /= 2; } return count; } // Driver code public static void Main () { int x = 10; Console.Write(countValues(x)); } } // This code is contributed by nitin mittal
<?php// PHP program to find count// of values whose XOR with// x is greater than x and// values are smaller than x function countValues($x){ // Initialize result $count = 0; $n = 1; // Traversing through // all bits of x while ($x != 0) { // If current last bit // of x is set then // increment count by // n. Here n is a power // of 2 corresponding // to position of bit if ($x % 2 == 0) $count += $n; // Simultaneously // calculate the 2^n $n *= 2; // Replace x with x/2; $x /= 2; $x = (int)$x; } return $count;} // Driver code$x = 10;echo countValues($x); // This code is contributed// by Smitha?>
<script> // Javascript program to find count of// values whose XOR with x is greater// than x and values are smaller than x function countValues(x){ // Initialize result var count = 0, n = 1; // Traversing through all bits of x while (x != 0) { // If current last bit of x is set // then increment count by n. Here // n is a power of 2 corresponding // to position of bit if (x % 2 == 0) count += n; // Simultaneously calculate the 2^n n *= 2; // Replace x with x/2; x = parseInt(x / 2); } return count;} // Driver codevar x = 10;document.write(countValues(x)); // This code is contributed by Princi Singh </script>
Output :
5
Time complexity of this solution is O(Log x)
This article is contributed by DANISH KALEEM. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.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.
nitin mittal
vt_m
Smitha Dinesh Semwal
Mithun Kumar
nidhi_biet
rishavmahato348
princi singh
binary-representation
Bitwise-XOR
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Cyclic Redundancy Check and Modulo-2 Division
Little and Big Endian Mystery
Program to find whether a given number is power of 2
Binary representation of a given number
Add two numbers without using arithmetic operators
Bit Fields in C
Find the element that appears once
Set, Clear and Toggle a given bit of a number in C
Josephus problem | Set 1 (A O(n) Solution)
C++ bitset and its application
|
[
{
"code": null,
"e": 25084,
"s": 25056,
"text": "\n06 May, 2021"
},
{
"code": null,
"e": 25176,
"s": 25084,
"text": "Given a integer ‘x’, find the number of values of ‘a’ satisfying the following conditions: "
},
{
"code": null,
"e": 25197,
"s": 25176,
"text": "a XOR x > x0 < a < x"
},
{
"code": null,
"e": 25209,
"s": 25197,
"text": "a XOR x > x"
},
{
"code": null,
"e": 25219,
"s": 25209,
"text": "0 < a < x"
},
{
"code": null,
"e": 25231,
"s": 25219,
"text": "Examples : "
},
{
"code": null,
"e": 25579,
"s": 25231,
"text": "Input : x = 10 \nOutput : 5\nExplanation: For x = 10, following 5 values\n of 'a' satisfy the conditions:\n 1 XOR 10 = 11\n 4 XOR 10 = 14\n 5 XOR 10 = 15\n 6 XOR 10 = 12\n 7 XOR 10 = 13 \n\nInput : x = 2\nOutput : 1\nExplanation: For x=2, we have just one value\n 1 XOR 2 = 3."
},
{
"code": null,
"e": 25734,
"s": 25579,
"text": "Naive Approach A Simple approach is to check for all values of ‘a’ between 0 and ‘x’ and calculate its XOR with x and check if the condition 1 satisfies. "
},
{
"code": null,
"e": 25738,
"s": 25734,
"text": "C++"
},
{
"code": null,
"e": 25743,
"s": 25738,
"text": "Java"
},
{
"code": null,
"e": 25751,
"s": 25743,
"text": "Python3"
},
{
"code": null,
"e": 25754,
"s": 25751,
"text": "C#"
},
{
"code": null,
"e": 25758,
"s": 25754,
"text": "PHP"
},
{
"code": null,
"e": 25769,
"s": 25758,
"text": "Javascript"
},
{
"code": "// C++ program to find count of values// whose XOR with x is greater than x// and values are smaller than x#include<bits/stdc++.h>using namespace std; int countValues(int x){ int count = 0; for (int i=1; i < x; i++) if ((i ^ x) > x) count++; return count;} // Driver codeint main(){ int x = 10; cout << countValues(x); return 0;}",
"e": 26135,
"s": 25769,
"text": null
},
{
"code": "// Java program to find count of values// whose XOR with x is greater than x// and values are smaller than x public class XOR{ static int countValues(int x) { int count = 0; for (int i=1; i < x; i++) if ((i ^ x) > x) count++; return count; } public static void main (String[] args) { int x = 10; System.out.println(countValues(x)); }} // This code is contributed by Saket Kumar",
"e": 26597,
"s": 26135,
"text": null
},
{
"code": "# Python3 program to find# count of values whose# XOR with x is greater# than x and values are# smaller than x def countValues(x): count = 0 for i in range(1 ,x): if ((i ^ x) > x): count += 1 return count # Driver codex = 10print(countValues(x)) # This code is contributed# by Smitha",
"e": 26909,
"s": 26597,
"text": null
},
{
"code": "// C# program to find count of values// whose XOR with x is greater than x// and values are smaller than xusing System; class GFG{ static int countValues(int x) { int count = 0; for (int i = 1; i < x; i++) if ((i ^ x) > x) count++; return count; } public static void Main () { int x = 10; Console.Write(countValues(x)); }} // This code is contributed by nitin mittal.",
"e": 27361,
"s": 26909,
"text": null
},
{
"code": "<?php// PHP program to find count of values// whose XOR with x is greater than x// and values are smaller than x function countValues($x){ $count = 0; for ($i = 1; $i < $x; $i++) if (($i ^ $x) > $x) $count++; return $count;} // Driver code $x = 10; echo countValues($x); // This code is contributed by anuj_67.?>",
"e": 27711,
"s": 27361,
"text": null
},
{
"code": "<script> // Javascript program to find count of values// whose XOR with x is greater than x// and values are smaller than x function countValues(x){ let count = 0; for (let i=1; i < x; i++) if ((i ^ x) > x) count++; return count;} // Driver code let x = 10; document.write(countValues(x)); </script>",
"e": 28044,
"s": 27711,
"text": null
},
{
"code": null,
"e": 28054,
"s": 28044,
"text": "Output : "
},
{
"code": null,
"e": 28056,
"s": 28054,
"text": "5"
},
{
"code": null,
"e": 28107,
"s": 28056,
"text": "The time complexity of the above approach is O(x)."
},
{
"code": null,
"e": 28347,
"s": 28107,
"text": "Efficient Approach The efficient solution lies in the binary representation of the number. We consider all 0’s in binary representation. For every 0 at the i-th position, we can have 2i numbers smaller than or equal to x with greater XOR. "
},
{
"code": null,
"e": 28351,
"s": 28347,
"text": "C++"
},
{
"code": null,
"e": 28356,
"s": 28351,
"text": "Java"
},
{
"code": null,
"e": 28364,
"s": 28356,
"text": "Python3"
},
{
"code": null,
"e": 28367,
"s": 28364,
"text": "C#"
},
{
"code": null,
"e": 28371,
"s": 28367,
"text": "PHP"
},
{
"code": null,
"e": 28382,
"s": 28371,
"text": "Javascript"
},
{
"code": "// C++ program to find count of values// whose XOR with x is greater than x// and values are smaller than x#include<bits/stdc++.h>using namespace std; int countValues(int x){ // Initialize result int count = 0, n = 1; // Traversing through all bits of x while (x != 0) { // If current last bit of x is set // then increment count by n. Here // n is a power of 2 corresponding // to position of bit if (x%2 == 0) count += n; // Simultaneously calculate the 2^n n *= 2; // Replace x with x/2; x /= 2; } return count;} // Driver codeint main(){ int x = 10; cout << countValues(x); return 0;}",
"e": 29079,
"s": 28382,
"text": null
},
{
"code": "// Java program to find count of values// whose XOR with x is greater than x// and values are smaller than x class GFG{ static int countValues(int x) { // Initialize result int count = 0, n = 1; // Traversing through all bits of x while (x != 0) { // If current last bit of x is set // then increment count by n. Here // n is a power of 2 corresponding // to position of bit if (x % 2 == 0) count += n; // Simultaneously calculate the 2^n n *= 2; // Replace x with x/2; x /= 2; } return count; } // Driver code public static void main (String[] args) { int x = 10; System.out.println(countValues(x)); } } // This code is contributed by Saket Kumar",
"e": 29973,
"s": 29079,
"text": null
},
{
"code": "# Python3 program to find count# of values whose XOR with# x is greater than x and# values are smaller than x def countValues(x): # Initialize result count = 0; n = 1; # Traversing through # all bits of x while (x > 0): # If current last bit # of x is set then # increment count by # n. Here n is a power # of 2 corresponding # to position of bit if (x % 2 == 0): count += n; # Simultaneously # calculate the 2^n n *= 2; # Replace x with x/2; x /= 2; x = int(x); return count; # Driver codex = 10;print(countValues(x)); # This code is contributed# by mits",
"e": 30670,
"s": 29973,
"text": null
},
{
"code": "// C# program to find count of values// whose XOR with x is greater than x// and values are smaller than xusing System; class GFG{ static int countValues(int x) { // Initialize result int count = 0, n = 1; // Traversing through all bits of x while (x != 0) { // If current last bit of x is set // then increment count by n. Here // n is a power of 2 corresponding // to position of bit if (x % 2 == 0) count += n; // Simultaneously calculate the 2^n n *= 2; // Replace x with x/2; x /= 2; } return count; } // Driver code public static void Main () { int x = 10; Console.Write(countValues(x)); } } // This code is contributed by nitin mittal",
"e": 31558,
"s": 30670,
"text": null
},
{
"code": "<?php// PHP program to find count// of values whose XOR with// x is greater than x and// values are smaller than x function countValues($x){ // Initialize result $count = 0; $n = 1; // Traversing through // all bits of x while ($x != 0) { // If current last bit // of x is set then // increment count by // n. Here n is a power // of 2 corresponding // to position of bit if ($x % 2 == 0) $count += $n; // Simultaneously // calculate the 2^n $n *= 2; // Replace x with x/2; $x /= 2; $x = (int)$x; } return $count;} // Driver code$x = 10;echo countValues($x); // This code is contributed// by Smitha?>",
"e": 32297,
"s": 31558,
"text": null
},
{
"code": "<script> // Javascript program to find count of// values whose XOR with x is greater// than x and values are smaller than x function countValues(x){ // Initialize result var count = 0, n = 1; // Traversing through all bits of x while (x != 0) { // If current last bit of x is set // then increment count by n. Here // n is a power of 2 corresponding // to position of bit if (x % 2 == 0) count += n; // Simultaneously calculate the 2^n n *= 2; // Replace x with x/2; x = parseInt(x / 2); } return count;} // Driver codevar x = 10;document.write(countValues(x)); // This code is contributed by Princi Singh </script>",
"e": 33046,
"s": 32297,
"text": null
},
{
"code": null,
"e": 33057,
"s": 33046,
"text": "Output : "
},
{
"code": null,
"e": 33059,
"s": 33057,
"text": "5"
},
{
"code": null,
"e": 33104,
"s": 33059,
"text": "Time complexity of this solution is O(Log x)"
},
{
"code": null,
"e": 33525,
"s": 33104,
"text": "This article is contributed by DANISH KALEEM. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.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. "
},
{
"code": null,
"e": 33538,
"s": 33525,
"text": "nitin mittal"
},
{
"code": null,
"e": 33543,
"s": 33538,
"text": "vt_m"
},
{
"code": null,
"e": 33564,
"s": 33543,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 33577,
"s": 33564,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 33588,
"s": 33577,
"text": "nidhi_biet"
},
{
"code": null,
"e": 33604,
"s": 33588,
"text": "rishavmahato348"
},
{
"code": null,
"e": 33617,
"s": 33604,
"text": "princi singh"
},
{
"code": null,
"e": 33639,
"s": 33617,
"text": "binary-representation"
},
{
"code": null,
"e": 33651,
"s": 33639,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 33661,
"s": 33651,
"text": "Bit Magic"
},
{
"code": null,
"e": 33671,
"s": 33661,
"text": "Bit Magic"
},
{
"code": null,
"e": 33769,
"s": 33671,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33815,
"s": 33769,
"text": "Cyclic Redundancy Check and Modulo-2 Division"
},
{
"code": null,
"e": 33845,
"s": 33815,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 33898,
"s": 33845,
"text": "Program to find whether a given number is power of 2"
},
{
"code": null,
"e": 33938,
"s": 33898,
"text": "Binary representation of a given number"
},
{
"code": null,
"e": 33989,
"s": 33938,
"text": "Add two numbers without using arithmetic operators"
},
{
"code": null,
"e": 34005,
"s": 33989,
"text": "Bit Fields in C"
},
{
"code": null,
"e": 34040,
"s": 34005,
"text": "Find the element that appears once"
},
{
"code": null,
"e": 34091,
"s": 34040,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 34134,
"s": 34091,
"text": "Josephus problem | Set 1 (A O(n) Solution)"
}
] |
HTML - Image Links
|
We have seen how to create hypertext link using text and we also learnt how to use images in our webpages. Now, we will learn how to use images to create hyperlinks.
It's simple to use an image as hyperlink. We just need to use an image inside hyperlink at the place of text as shown below −
<!DOCTYPE html>
<html>
<head>
<title>Image Hyperlink Example</title>
</head>
<body>
<p>Click following link</p>
<a href = "https://www.tutorialspoint.com" target = "_self">
<img src = "/images/logo.png" alt = "Tutorials Point" border = "0"/>
</a>
</body>
</html>
This will produce the following result, where you can click on the images to reach to the home page of Tutorials Point.
Click following link
This was the simplest way of creating hyperlinks using images. Next we will see how we can create Mouse-Sensitive Image Links.
The HTML and XHTML standards provides a feature that lets you embed many different links inside a single image. You can create different links on the single image based on different coordinates available on the image. Once different links are attached to different coordinates, we can click different parts of the image to open target documents. Such mouse-sensitive images are known as image maps.
There are two ways to create image maps −
Server-side image maps − This is enabled by the ismap attribute of the <img> tag and requires access to a server and related image-map processing applications.
Server-side image maps − This is enabled by the ismap attribute of the <img> tag and requires access to a server and related image-map processing applications.
Client-side image maps − This is created with the usemap attribute of the <img> tag, along with corresponding <map> and <area> tags.
Client-side image maps − This is created with the usemap attribute of the <img> tag, along with corresponding <map> and <area> tags.
Here you simply put your image inside a hyper link and use ismap attribute which makes it special image and when the user clicks some place within the image, the browser passes the coordinates of the mouse pointer along with the URL specified in the <a> tag to the web server. The server uses the mouse-pointer coordinates to determine which document to deliver back to the browser.
When ismap is used, the href attribute of the containing <a> tag must contain the URL of a server application like a cgi or PHP script etc. to process the incoming request based on the passed coordinates.
The coordinates of the mouse position are screen pixels counted from the upper-left corner of the image, beginning with (0,0). The coordinates, preceded by a question mark, are added to the end of the URL.
For example, if a user clicks 20 pixels over and 30 pixels down from the upper-left corner of the following image −
Which has been generated by the following code snippet −
<!DOCTYPE html>
<html>
<head>
<title>ISMAP Hyperlink Example</title>
</head>
<body>
<p>Click following link</p>
<a href = "/cgi-bin/ismap.cgi" target = "_self">
<img ismap src = "/images/logo.png" alt = "Tutorials Point" border = "0"/>
</a>
</body>
</html>
Click following link
Then the browser sends the following search parameters to the web server which can be processed by ismap.cgi script or map file and you can link whatever documents you like to these coordinates −
/cgi-bin/ismap.cgi?20,30
This way you can assign different links to different coordinates of the image and when those coordinates are clicked, you can open corresponding linked document. To learn more about ismap attribute, you can check How to use Image ismap?
Note − You will learn CGI programming when you will study Perl programming. You can write your script to process these passed coordinates using PHP or any other script as well. For now, let's concentrate on learning HTML and later you can revisit this section.
Client side image maps are enabled by the usemap attribute of the <img /> tag and defined by special <map> and <area> extension tags.
The image that is going to form the map is inserted into the page using the <img /> tag as a normal image, except it carries an extra attribute called usemap. The value of the usemap attribute is the value which will be used in a <map> tag to link map and image tags. The <map> along with <area> tags define all the image coordinates and corresponding links.
The <area> tag inside the map tag, specifies the shape and the coordinates to define the boundaries of each clickable hotspot available on the image. Here's an example from the image map −
<!DOCTYPE html>
<html>
<head>
<title>USEMAP Hyperlink Example</title>
</head>
<body>
<p>Search and click the hotspot</p>
<img src = /images/html.gif alt = "HTML Map" border = "0" usemap = "#html"/>
<!-- Create Mappings -->
<map name = "html">
<area shape = "circle" coords = "80,80,20"
href = "/css/index.htm" alt = "CSS Link" target = "_self" />
<area shape = "rect" coords = "5,5,40,40" alt = "jQuery Link"
href = "/jquery/index.htm" target = "_self" />
</map>
</body>
</html>
This will produce the following result −
Search and click the hotspot
The actual value of coords is totally dependent on the shape in question. Here is a summary, to be followed by detailed examples −
rect = x1 , y1 , x2 , y2
x1 and y1 are the coordinates of the upper left corner of the rectangle; x2 and y2 are the coordinates of the lower right corner.
rect = x1 , y1 , x2 , y2
x1 and y1 are the coordinates of the upper left corner of the rectangle; x2 and y2 are the coordinates of the lower right corner.
circle = xc , yc , radius
xc and yc are the coordinates of the center of the circle, and radius is the circle's radius. A circle centered at 200,50 with a radius of 25 would have the attribute coords = "200,50,25"
circle = xc , yc , radius
xc and yc are the coordinates of the center of the circle, and radius is the circle's radius. A circle centered at 200,50 with a radius of 25 would have the attribute coords = "200,50,25"
poly = x1 , y1 , x2 , y2 , x3 , y3 , ... xn , yn
The various x-y pairs define vertices (points) of the polygon, with a "line" being drawn from one point to the next point. A diamond-shaped polygon with its top point at 20,20 and 40 pixels across at its widest points would have the attribute coords = "20,20,40,40,20,60,0,40".
poly = x1 , y1 , x2 , y2 , x3 , y3 , ... xn , yn
The various x-y pairs define vertices (points) of the polygon, with a "line" being drawn from one point to the next point. A diamond-shaped polygon with its top point at 20,20 and 40 pixels across at its widest points would have the attribute coords = "20,20,40,40,20,60,0,40".
All coordinates are relative to the upper-left corner of the image (0,0). Each shape has a related URL. You can use any image software to know the coordinates of different positions.
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2540,
"s": 2374,
"text": "We have seen how to create hypertext link using text and we also learnt how to use images in our webpages. Now, we will learn how to use images to create hyperlinks."
},
{
"code": null,
"e": 2666,
"s": 2540,
"text": "It's simple to use an image as hyperlink. We just need to use an image inside hyperlink at the place of text as shown below −"
},
{
"code": null,
"e": 2981,
"s": 2666,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Image Hyperlink Example</title>\n </head>\n\t\n <body>\n <p>Click following link</p>\n <a href = \"https://www.tutorialspoint.com\" target = \"_self\"> \n <img src = \"/images/logo.png\" alt = \"Tutorials Point\" border = \"0\"/> \n </a>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 3101,
"s": 2981,
"text": "This will produce the following result, where you can click on the images to reach to the home page of Tutorials Point."
},
{
"code": null,
"e": 3122,
"s": 3101,
"text": "Click following link"
},
{
"code": null,
"e": 3249,
"s": 3122,
"text": "This was the simplest way of creating hyperlinks using images. Next we will see how we can create Mouse-Sensitive Image Links."
},
{
"code": null,
"e": 3648,
"s": 3249,
"text": "The HTML and XHTML standards provides a feature that lets you embed many different links inside a single image. You can create different links on the single image based on different coordinates available on the image. Once different links are attached to different coordinates, we can click different parts of the image to open target documents. Such mouse-sensitive images are known as image maps."
},
{
"code": null,
"e": 3690,
"s": 3648,
"text": "There are two ways to create image maps −"
},
{
"code": null,
"e": 3850,
"s": 3690,
"text": "Server-side image maps − This is enabled by the ismap attribute of the <img> tag and requires access to a server and related image-map processing applications."
},
{
"code": null,
"e": 4010,
"s": 3850,
"text": "Server-side image maps − This is enabled by the ismap attribute of the <img> tag and requires access to a server and related image-map processing applications."
},
{
"code": null,
"e": 4143,
"s": 4010,
"text": "Client-side image maps − This is created with the usemap attribute of the <img> tag, along with corresponding <map> and <area> tags."
},
{
"code": null,
"e": 4276,
"s": 4143,
"text": "Client-side image maps − This is created with the usemap attribute of the <img> tag, along with corresponding <map> and <area> tags."
},
{
"code": null,
"e": 4659,
"s": 4276,
"text": "Here you simply put your image inside a hyper link and use ismap attribute which makes it special image and when the user clicks some place within the image, the browser passes the coordinates of the mouse pointer along with the URL specified in the <a> tag to the web server. The server uses the mouse-pointer coordinates to determine which document to deliver back to the browser."
},
{
"code": null,
"e": 4864,
"s": 4659,
"text": "When ismap is used, the href attribute of the containing <a> tag must contain the URL of a server application like a cgi or PHP script etc. to process the incoming request based on the passed coordinates."
},
{
"code": null,
"e": 5070,
"s": 4864,
"text": "The coordinates of the mouse position are screen pixels counted from the upper-left corner of the image, beginning with (0,0). The coordinates, preceded by a question mark, are added to the end of the URL."
},
{
"code": null,
"e": 5186,
"s": 5070,
"text": "For example, if a user clicks 20 pixels over and 30 pixels down from the upper-left corner of the following image −"
},
{
"code": null,
"e": 5243,
"s": 5186,
"text": "Which has been generated by the following code snippet −"
},
{
"code": null,
"e": 5559,
"s": 5243,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>ISMAP Hyperlink Example</title>\n </head>\n\t\n <body>\n <p>Click following link</p>\n \n <a href = \"/cgi-bin/ismap.cgi\" target = \"_self\"> \n <img ismap src = \"/images/logo.png\" alt = \"Tutorials Point\" border = \"0\"/> \n </a>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 5580,
"s": 5559,
"text": "Click following link"
},
{
"code": null,
"e": 5776,
"s": 5580,
"text": "Then the browser sends the following search parameters to the web server which can be processed by ismap.cgi script or map file and you can link whatever documents you like to these coordinates −"
},
{
"code": null,
"e": 5802,
"s": 5776,
"text": "/cgi-bin/ismap.cgi?20,30\n"
},
{
"code": null,
"e": 6039,
"s": 5802,
"text": "This way you can assign different links to different coordinates of the image and when those coordinates are clicked, you can open corresponding linked document. To learn more about ismap attribute, you can check How to use Image ismap?"
},
{
"code": null,
"e": 6300,
"s": 6039,
"text": "Note − You will learn CGI programming when you will study Perl programming. You can write your script to process these passed coordinates using PHP or any other script as well. For now, let's concentrate on learning HTML and later you can revisit this section."
},
{
"code": null,
"e": 6434,
"s": 6300,
"text": "Client side image maps are enabled by the usemap attribute of the <img /> tag and defined by special <map> and <area> extension tags."
},
{
"code": null,
"e": 6793,
"s": 6434,
"text": "The image that is going to form the map is inserted into the page using the <img /> tag as a normal image, except it carries an extra attribute called usemap. The value of the usemap attribute is the value which will be used in a <map> tag to link map and image tags. The <map> along with <area> tags define all the image coordinates and corresponding links."
},
{
"code": null,
"e": 6982,
"s": 6793,
"text": "The <area> tag inside the map tag, specifies the shape and the coordinates to define the boundaries of each clickable hotspot available on the image. Here's an example from the image map −"
},
{
"code": null,
"e": 7578,
"s": 6982,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>USEMAP Hyperlink Example</title>\n </head>\n\t\n <body>\n <p>Search and click the hotspot</p>\n <img src = /images/html.gif alt = \"HTML Map\" border = \"0\" usemap = \"#html\"/>\n <!-- Create Mappings -->\n \n <map name = \"html\">\n <area shape = \"circle\" coords = \"80,80,20\" \n href = \"/css/index.htm\" alt = \"CSS Link\" target = \"_self\" />\n \n <area shape = \"rect\" coords = \"5,5,40,40\" alt = \"jQuery Link\" \n href = \"/jquery/index.htm\" target = \"_self\" />\n </map>\n </body>\n \n</html>"
},
{
"code": null,
"e": 7619,
"s": 7578,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 7648,
"s": 7619,
"text": "Search and click the hotspot"
},
{
"code": null,
"e": 7779,
"s": 7648,
"text": "The actual value of coords is totally dependent on the shape in question. Here is a summary, to be followed by detailed examples −"
},
{
"code": null,
"e": 7934,
"s": 7779,
"text": "rect = x1 , y1 , x2 , y2\nx1 and y1 are the coordinates of the upper left corner of the rectangle; x2 and y2 are the coordinates of the lower right corner."
},
{
"code": null,
"e": 7959,
"s": 7934,
"text": "rect = x1 , y1 , x2 , y2"
},
{
"code": null,
"e": 8089,
"s": 7959,
"text": "x1 and y1 are the coordinates of the upper left corner of the rectangle; x2 and y2 are the coordinates of the lower right corner."
},
{
"code": null,
"e": 8303,
"s": 8089,
"text": "circle = xc , yc , radius\nxc and yc are the coordinates of the center of the circle, and radius is the circle's radius. A circle centered at 200,50 with a radius of 25 would have the attribute coords = \"200,50,25\""
},
{
"code": null,
"e": 8329,
"s": 8303,
"text": "circle = xc , yc , radius"
},
{
"code": null,
"e": 8517,
"s": 8329,
"text": "xc and yc are the coordinates of the center of the circle, and radius is the circle's radius. A circle centered at 200,50 with a radius of 25 would have the attribute coords = \"200,50,25\""
},
{
"code": null,
"e": 8844,
"s": 8517,
"text": "poly = x1 , y1 , x2 , y2 , x3 , y3 , ... xn , yn\nThe various x-y pairs define vertices (points) of the polygon, with a \"line\" being drawn from one point to the next point. A diamond-shaped polygon with its top point at 20,20 and 40 pixels across at its widest points would have the attribute coords = \"20,20,40,40,20,60,0,40\"."
},
{
"code": null,
"e": 8893,
"s": 8844,
"text": "poly = x1 , y1 , x2 , y2 , x3 , y3 , ... xn , yn"
},
{
"code": null,
"e": 9171,
"s": 8893,
"text": "The various x-y pairs define vertices (points) of the polygon, with a \"line\" being drawn from one point to the next point. A diamond-shaped polygon with its top point at 20,20 and 40 pixels across at its widest points would have the attribute coords = \"20,20,40,40,20,60,0,40\"."
},
{
"code": null,
"e": 9354,
"s": 9171,
"text": "All coordinates are relative to the upper-left corner of the image (0,0). Each shape has a related URL. You can use any image software to know the coordinates of different positions."
},
{
"code": null,
"e": 9387,
"s": 9354,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 9401,
"s": 9387,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 9436,
"s": 9401,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9450,
"s": 9436,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 9485,
"s": 9450,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9502,
"s": 9485,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 9537,
"s": 9502,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 9568,
"s": 9537,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 9601,
"s": 9568,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 9632,
"s": 9601,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 9667,
"s": 9632,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 9698,
"s": 9667,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 9705,
"s": 9698,
"text": " Print"
},
{
"code": null,
"e": 9716,
"s": 9705,
"text": " Add Notes"
}
] |
C++ Program to Implement Treap
|
This is a C++ program to implement Treap. Treap data structure is basically a randomized binary search tree. Here, we shall consider insert, delete and search operations on this.
function insetNod() to insert a given key into treap with priority recursively −
If root = nullptr
return data as root.
If given data is less then root node,
Insert data in left subtree.
Rotate left if heap property violated.
else
Insert data in right subtree.
Rotate right if heap property violated.
function searchNod() for searching key in treap recursively −
If key is not present return false.
If key is present return true.
If key is less than root, search in left subtree.
Else
search in right subtree.
function deleteNod() to delete key from treap recursively −
If key is not present return false
If key is present return true.
If key is less than root, go to left subtree.
Else
Go to right subtree.
If key is found:
node to be deleted which is a leaf node
deallocate the memory and update root to null.
delete root.
node to be deleted which has two children
if left child has less priority than right child
call rotLeft() on root
recursively delete the left child
else
call rotRight() on root
recursively delete the right child
node to be deleted has only one child
find child node
deallocate the memory
Print the result.
End
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
struct TreapNod { //node declaration
int data;
int priority;
TreapNod* l, *r;
TreapNod(int d) { //constructor
this->data = d;
this->priority = rand() % 100;
this->l= this->r = nullptr;
}
};
void rotLeft(TreapNod* &root) { //left rotation
TreapNod* R = root->r;
TreapNod* X = root->r->l;
R->l = root;
root->r= X;
root = R;
}
void rotRight(TreapNod* &root) { //right rotation
TreapNod* L = root->l;
TreapNod* Y = root->l->r;
L->r = root;
root->l= Y;
root = L;
}
void insertNod(TreapNod* &root, int d) { //insertion
if (root == nullptr) {
root = new TreapNod(d);
return;
}
if (d < root->data) {
insertNod(root->l, d);
if (root->l != nullptr && root->l->priority > root->priority)
rotRight(root);
} else {
insertNod(root->r, d);
if (root->r!= nullptr && root->r->priority > root->priority)
rotLeft(root);
}
}
bool searchNod(TreapNod* root, int key) {
if (root == nullptr)
return false;
if (root->data == key)
return true;
if (key < root->data)
return searchNod(root->l, key);
return searchNod(root->r, key);
}
void deleteNod(TreapNod* &root, int key) {
//node to be deleted which is a leaf node
if (root == nullptr)
return;
if (key < root->data)
deleteNod(root->l, key);
else if (key > root->data)
deleteNod(root->r, key);
//node to be deleted which has two children
else {
if (root->l ==nullptr && root->r == nullptr) {
delete root;
root = nullptr;
}
else if (root->l && root->r) {
if (root->l->priority < root->r->priority) {
rotLeft(root);
deleteNod(root->l, key);
} else {
rotRight(root);
deleteNod(root->r, key);
}
}
//node to be deleted has only one child
else {
TreapNod* child = (root->l)? root->l: root->r;
TreapNod* curr = root;
root = child;
delete curr;
}
}
}
void displayTreap(TreapNod *root, int space = 0, int height =10) { //display treap
if (root == nullptr)
return;
space += height;
displayTreap(root->l, space);
cout << endl;
for (int i = height; i < space; i++)
cout << ' ';
cout << root->data << "(" << root->priority << ")\n";
cout << endl;
displayTreap(root->r, space);
}
int main() {
int nums[] = {1,7,6,4,3,2,8,9,10 };
int a = sizeof(nums)/sizeof(int);
TreapNod* root = nullptr;
srand(time(nullptr));
for (int n: nums)
insertNod(root, n);
cout << "Constructed Treap:\n\n";
displayTreap(root);
cout << "\nDeleting node 8:\n\n";
deleteNod(root, 8);
displayTreap(root);
cout << "\nDeleting node 3:\n\n";
deleteNod(root, 3);
displayTreap(root);
return 0;
}
Constructed Treap:
1(12)
2(27)
3(97)
4(46)
6(75)
7(88)
8(20)
9(41)
10(25)
Deleting node 8:
1(12)
2(27)
3(97)
4(46)
6(75)
7(88)
9(41)
10(25)
Deleting node 3:
1(12)
2(27)
4(46)
6(75)
7(88)
9(41)
10(25)
|
[
{
"code": null,
"e": 1241,
"s": 1062,
"text": "This is a C++ program to implement Treap. Treap data structure is basically a randomized binary search tree. Here, we shall consider insert, delete and search operations on this."
},
{
"code": null,
"e": 1322,
"s": 1241,
"text": "function insetNod() to insert a given key into treap with priority recursively −"
},
{
"code": null,
"e": 1557,
"s": 1322,
"text": "If root = nullptr\n return data as root.\nIf given data is less then root node,\n Insert data in left subtree.\n Rotate left if heap property violated.\nelse\n Insert data in right subtree.\n Rotate right if heap property violated."
},
{
"code": null,
"e": 1619,
"s": 1557,
"text": "function searchNod() for searching key in treap recursively −"
},
{
"code": null,
"e": 1769,
"s": 1619,
"text": "If key is not present return false.\nIf key is present return true.\nIf key is less than root, search in left subtree.\nElse\n search in right subtree."
},
{
"code": null,
"e": 1829,
"s": 1769,
"text": "function deleteNod() to delete key from treap recursively −"
},
{
"code": null,
"e": 2484,
"s": 1829,
"text": "If key is not present return false\nIf key is present return true.\nIf key is less than root, go to left subtree.\nElse\n Go to right subtree.\nIf key is found:\n node to be deleted which is a leaf node\n deallocate the memory and update root to null.\n delete root.\n node to be deleted which has two children\n if left child has less priority than right child\n call rotLeft() on root\n recursively delete the left child\n else\n call rotRight() on root\n recursively delete the right child\n node to be deleted has only one child\n find child node\n deallocate the memory\n Print the result.\nEnd"
},
{
"code": null,
"e": 5398,
"s": 2484,
"text": "#include <iostream>\n#include <cstdlib>\n#include <ctime>\nusing namespace std;\nstruct TreapNod { //node declaration\n int data;\n int priority;\n TreapNod* l, *r;\n TreapNod(int d) { //constructor\n this->data = d;\n this->priority = rand() % 100;\n this->l= this->r = nullptr;\n }\n};\nvoid rotLeft(TreapNod* &root) { //left rotation\n TreapNod* R = root->r;\n TreapNod* X = root->r->l;\n R->l = root;\n root->r= X;\n root = R;\n}\nvoid rotRight(TreapNod* &root) { //right rotation\n TreapNod* L = root->l;\n TreapNod* Y = root->l->r;\n L->r = root;\n root->l= Y;\n root = L;\n}\nvoid insertNod(TreapNod* &root, int d) { //insertion\n if (root == nullptr) {\n root = new TreapNod(d);\n return;\n }\n if (d < root->data) {\n insertNod(root->l, d);\n if (root->l != nullptr && root->l->priority > root->priority)\n rotRight(root);\n } else {\n insertNod(root->r, d);\n if (root->r!= nullptr && root->r->priority > root->priority)\n rotLeft(root);\n }\n}\nbool searchNod(TreapNod* root, int key) {\n if (root == nullptr)\n return false;\n if (root->data == key)\n return true;\n if (key < root->data)\n return searchNod(root->l, key);\n return searchNod(root->r, key);\n}\nvoid deleteNod(TreapNod* &root, int key) {\n //node to be deleted which is a leaf node\n if (root == nullptr)\n return;\n if (key < root->data)\n deleteNod(root->l, key);\n else if (key > root->data)\n deleteNod(root->r, key);\n //node to be deleted which has two children\n else {\n if (root->l ==nullptr && root->r == nullptr) {\n delete root;\n root = nullptr;\n }\n else if (root->l && root->r) {\n if (root->l->priority < root->r->priority) {\n rotLeft(root);\n deleteNod(root->l, key);\n } else {\n rotRight(root);\n deleteNod(root->r, key);\n }\n }\n //node to be deleted has only one child\n else {\n TreapNod* child = (root->l)? root->l: root->r;\n TreapNod* curr = root;\n root = child;\n delete curr;\n }\n }\n}\nvoid displayTreap(TreapNod *root, int space = 0, int height =10) { //display treap\n if (root == nullptr)\n return;\n space += height;\n displayTreap(root->l, space);\n cout << endl;\n for (int i = height; i < space; i++)\n cout << ' ';\n cout << root->data << \"(\" << root->priority << \")\\n\";\n cout << endl;\n displayTreap(root->r, space);\n}\nint main() {\n int nums[] = {1,7,6,4,3,2,8,9,10 };\n int a = sizeof(nums)/sizeof(int);\n TreapNod* root = nullptr;\n srand(time(nullptr));\n for (int n: nums)\n insertNod(root, n);\n cout << \"Constructed Treap:\\n\\n\";\n displayTreap(root);\n cout << \"\\nDeleting node 8:\\n\\n\";\n deleteNod(root, 8);\n displayTreap(root);\n cout << \"\\nDeleting node 3:\\n\\n\";\n deleteNod(root, 3);\n displayTreap(root);\n return 0;\n}"
},
{
"code": null,
"e": 5624,
"s": 5398,
"text": "Constructed Treap:\n\n1(12)\n\n2(27)\n\n3(97)\n\n4(46)\n\n6(75)\n\n7(88)\n\n8(20)\n\n9(41)\n\n10(25)\n\nDeleting node 8:\n\n1(12)\n\n2(27)\n\n3(97)\n\n4(46)\n\n6(75)\n\n7(88)\n\n9(41)\n\n10(25)\n\nDeleting node 3:\n\n1(12)\n\n2(27)\n\n4(46)\n\n6(75)\n\n7(88)\n\n9(41)\n\n10(25)"
}
] |
Fortran - Do Loop Construct
|
The do loop construct enables a statement, or a series of statements, to be carried out iteratively, while a given condition is true.
The general form of the do loop is −
do var = start, stop [,step]
! statement(s)
...
end do
Where,
the loop variable var should be an integer
the loop variable var should be an integer
start is initial value
start is initial value
stop is the final value
stop is the final value
step is the increment, if this is omitted, then the variable var is increased by unity
step is the increment, if this is omitted, then the variable var is increased by unity
! compute factorials
do n = 1, 10
nfact = nfact * n
! printing the value of n and its factorial
print*, n, " ", nfact
end do
Here is the flow of control for the do loop construct −
The initial step is executed first, and only once. This step allows you to declare and initialize any loop control variables. In our case, the variable var is initialised with the value start.
The initial step is executed first, and only once. This step allows you to declare and initialize any loop control variables. In our case, the variable var is initialised with the value start.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the loop. In our case, the condition is that the variable var reaches its final value stop.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the loop. In our case, the condition is that the variable var reaches its final value stop.
After the body of the loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update the loop control variable var.
After the body of the loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update the loop control variable var.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the loop terminates.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the loop terminates.
This example prints the numbers 11 to 20 −
program printNum
implicit none
! define variables
integer :: n
do n = 11, 20
! printing the value of n
print*, n
end do
end program printNum
When the above code is compiled and executed, it produces the following result −
11
12
13
14
15
16
17
18
19
20
This program calculates the factorials of numbers 1 to 10 −
program factorial
implicit none
! define variables
integer :: nfact = 1
integer :: n
! compute factorials
do n = 1, 10
nfact = nfact * n
! print values
print*, n, " ", nfact
end do
end program factorial
When the above code is compiled and executed, it produces the following result −
1 1
2 2
3 6
4 24
5 120
6 720
7 5040
8 40320
9 362880
10 3628800
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2280,
"s": 2146,
"text": "The do loop construct enables a statement, or a series of statements, to be carried out iteratively, while a given condition is true."
},
{
"code": null,
"e": 2317,
"s": 2280,
"text": "The general form of the do loop is −"
},
{
"code": null,
"e": 2383,
"s": 2317,
"text": "do var = start, stop [,step] \n ! statement(s)\n ...\nend do\n"
},
{
"code": null,
"e": 2390,
"s": 2383,
"text": "Where,"
},
{
"code": null,
"e": 2433,
"s": 2390,
"text": "the loop variable var should be an integer"
},
{
"code": null,
"e": 2476,
"s": 2433,
"text": "the loop variable var should be an integer"
},
{
"code": null,
"e": 2499,
"s": 2476,
"text": "start is initial value"
},
{
"code": null,
"e": 2522,
"s": 2499,
"text": "start is initial value"
},
{
"code": null,
"e": 2546,
"s": 2522,
"text": "stop is the final value"
},
{
"code": null,
"e": 2570,
"s": 2546,
"text": "stop is the final value"
},
{
"code": null,
"e": 2657,
"s": 2570,
"text": "step is the increment, if this is omitted, then the variable var is increased by unity"
},
{
"code": null,
"e": 2744,
"s": 2657,
"text": "step is the increment, if this is omitted, then the variable var is increased by unity"
},
{
"code": null,
"e": 2884,
"s": 2744,
"text": "! compute factorials\ndo n = 1, 10\n nfact = nfact * n \n ! printing the value of n and its factorial\n print*, n, \" \", nfact \nend do"
},
{
"code": null,
"e": 2940,
"s": 2884,
"text": "Here is the flow of control for the do loop construct −"
},
{
"code": null,
"e": 3133,
"s": 2940,
"text": "The initial step is executed first, and only once. This step allows you to declare and initialize any loop control variables. In our case, the variable var is initialised with the value start."
},
{
"code": null,
"e": 3326,
"s": 3133,
"text": "The initial step is executed first, and only once. This step allows you to declare and initialize any loop control variables. In our case, the variable var is initialised with the value start."
},
{
"code": null,
"e": 3614,
"s": 3326,
"text": "Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the loop. In our case, the condition is that the variable var reaches its final value stop."
},
{
"code": null,
"e": 3902,
"s": 3614,
"text": "Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the loop. In our case, the condition is that the variable var reaches its final value stop."
},
{
"code": null,
"e": 4068,
"s": 3902,
"text": "After the body of the loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update the loop control variable var."
},
{
"code": null,
"e": 4234,
"s": 4068,
"text": "After the body of the loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update the loop control variable var."
},
{
"code": null,
"e": 4455,
"s": 4234,
"text": "The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the loop terminates."
},
{
"code": null,
"e": 4676,
"s": 4455,
"text": "The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the loop terminates."
},
{
"code": null,
"e": 4719,
"s": 4676,
"text": "This example prints the numbers 11 to 20 −"
},
{
"code": null,
"e": 4907,
"s": 4719,
"text": "program printNum \nimplicit none \n\n ! define variables\n integer :: n\n \n do n = 11, 20 \n ! printing the value of n \n print*, n \n end do \n \nend program printNum "
},
{
"code": null,
"e": 4988,
"s": 4907,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5019,
"s": 4988,
"text": "11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n"
},
{
"code": null,
"e": 5079,
"s": 5019,
"text": "This program calculates the factorials of numbers 1 to 10 −"
},
{
"code": null,
"e": 5353,
"s": 5079,
"text": "program factorial \nimplicit none \n\n ! define variables\n integer :: nfact = 1 \n integer :: n \n \n ! compute factorials \n do n = 1, 10 \n nfact = nfact * n \n ! print values\n print*, n, \" \", nfact \n end do \n \nend program factorial "
},
{
"code": null,
"e": 5434,
"s": 5353,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5596,
"s": 5434,
"text": "1 1\n2 2\n3 6\n4 24\n5 120\n6 720\n7 5040\n8 40320\n9 362880\n10 3628800\n"
},
{
"code": null,
"e": 5603,
"s": 5596,
"text": " Print"
},
{
"code": null,
"e": 5614,
"s": 5603,
"text": " Add Notes"
}
] |
8085 program to convert an 8 bit BCD number into hexadecimal number - GeeksforGeeks
|
28 Aug, 2019
Problem – Write an assembly language program in 8085 microprocessor to convert an 8 bit BCD number into hexadecimal number.
Assumptions – Assume that starting address of the program is 2000, input memory locations, 2050, 2051, and output memory location is 2052.
Example –
INPUT: 2050:02H
2051: 09H
OUTPUT:2052: 1DH
Algorithm –
Initialize memory pointer to 2050Get the most significant digitMultiply the MSD by 10 using repeated additionAdd LSD to result obtained in above stepStore the converted result in memory 2052
Initialize memory pointer to 2050
Get the most significant digit
Multiply the MSD by 10 using repeated addition
Add LSD to result obtained in above step
Store the converted result in memory 2052
Program –
Explanation – Registers H, L, B, A are used for general purpose.
LXI H, 2050: will load the HL pair register with the address 2050 of memory location.MOV A, M: copies the content of memory into register A.ADD A: add the content of accumulator with itself.MOV B, A: move the content of accumulator into register B.ADD A: add the content of accumulator with itself.ADD A: add the content of accumulator with itself.ADD B: add the content of accumulator with register B and store the result in accumulator.INX H: increment register pair HL.ADD M: add the content of accumulator with memory and store the result in accumulator.INX H: increment register pair HL.MOV M, A: copies the content of accumulator into memory.HLT: stops executing the program and halts any further execution.
LXI H, 2050: will load the HL pair register with the address 2050 of memory location.
MOV A, M: copies the content of memory into register A.
ADD A: add the content of accumulator with itself.
MOV B, A: move the content of accumulator into register B.
ADD A: add the content of accumulator with itself.
ADD A: add the content of accumulator with itself.
ADD B: add the content of accumulator with register B and store the result in accumulator.
INX H: increment register pair HL.
ADD M: add the content of accumulator with memory and store the result in accumulator.
INX H: increment register pair HL.
MOV M, A: copies the content of accumulator into memory.
HLT: stops executing the program and halts any further execution.
Akanksha_Rai
microprocessor
system-programming
Computer Organization & Architecture
microprocessor
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Logical and Physical Address in Operating System
Addressing modes in 8085 microprocessor
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Computer Organization | RISC and CISC
Computer Organization | Instruction Formats (Zero, One, Two and Three Address Instruction)
Memory Hierarchy Design and its Characteristics
Computer Organization | Booth's Algorithm
Difference between Von Neumann and Harvard Architecture
Architecture of 8085 microprocessor
8085 program to add two 8 bit numbers
|
[
{
"code": null,
"e": 24840,
"s": 24812,
"text": "\n28 Aug, 2019"
},
{
"code": null,
"e": 24964,
"s": 24840,
"text": "Problem – Write an assembly language program in 8085 microprocessor to convert an 8 bit BCD number into hexadecimal number."
},
{
"code": null,
"e": 25103,
"s": 24964,
"text": "Assumptions – Assume that starting address of the program is 2000, input memory locations, 2050, 2051, and output memory location is 2052."
},
{
"code": null,
"e": 25113,
"s": 25103,
"text": "Example –"
},
{
"code": null,
"e": 25165,
"s": 25113,
"text": "INPUT: 2050:02H\n 2051: 09H\n\nOUTPUT:2052: 1DH "
},
{
"code": null,
"e": 25177,
"s": 25165,
"text": "Algorithm –"
},
{
"code": null,
"e": 25368,
"s": 25177,
"text": "Initialize memory pointer to 2050Get the most significant digitMultiply the MSD by 10 using repeated additionAdd LSD to result obtained in above stepStore the converted result in memory 2052"
},
{
"code": null,
"e": 25402,
"s": 25368,
"text": "Initialize memory pointer to 2050"
},
{
"code": null,
"e": 25433,
"s": 25402,
"text": "Get the most significant digit"
},
{
"code": null,
"e": 25480,
"s": 25433,
"text": "Multiply the MSD by 10 using repeated addition"
},
{
"code": null,
"e": 25521,
"s": 25480,
"text": "Add LSD to result obtained in above step"
},
{
"code": null,
"e": 25563,
"s": 25521,
"text": "Store the converted result in memory 2052"
},
{
"code": null,
"e": 25573,
"s": 25563,
"text": "Program –"
},
{
"code": null,
"e": 25638,
"s": 25573,
"text": "Explanation – Registers H, L, B, A are used for general purpose."
},
{
"code": null,
"e": 26352,
"s": 25638,
"text": "LXI H, 2050: will load the HL pair register with the address 2050 of memory location.MOV A, M: copies the content of memory into register A.ADD A: add the content of accumulator with itself.MOV B, A: move the content of accumulator into register B.ADD A: add the content of accumulator with itself.ADD A: add the content of accumulator with itself.ADD B: add the content of accumulator with register B and store the result in accumulator.INX H: increment register pair HL.ADD M: add the content of accumulator with memory and store the result in accumulator.INX H: increment register pair HL.MOV M, A: copies the content of accumulator into memory.HLT: stops executing the program and halts any further execution."
},
{
"code": null,
"e": 26438,
"s": 26352,
"text": "LXI H, 2050: will load the HL pair register with the address 2050 of memory location."
},
{
"code": null,
"e": 26494,
"s": 26438,
"text": "MOV A, M: copies the content of memory into register A."
},
{
"code": null,
"e": 26545,
"s": 26494,
"text": "ADD A: add the content of accumulator with itself."
},
{
"code": null,
"e": 26604,
"s": 26545,
"text": "MOV B, A: move the content of accumulator into register B."
},
{
"code": null,
"e": 26655,
"s": 26604,
"text": "ADD A: add the content of accumulator with itself."
},
{
"code": null,
"e": 26706,
"s": 26655,
"text": "ADD A: add the content of accumulator with itself."
},
{
"code": null,
"e": 26797,
"s": 26706,
"text": "ADD B: add the content of accumulator with register B and store the result in accumulator."
},
{
"code": null,
"e": 26832,
"s": 26797,
"text": "INX H: increment register pair HL."
},
{
"code": null,
"e": 26919,
"s": 26832,
"text": "ADD M: add the content of accumulator with memory and store the result in accumulator."
},
{
"code": null,
"e": 26954,
"s": 26919,
"text": "INX H: increment register pair HL."
},
{
"code": null,
"e": 27011,
"s": 26954,
"text": "MOV M, A: copies the content of accumulator into memory."
},
{
"code": null,
"e": 27077,
"s": 27011,
"text": "HLT: stops executing the program and halts any further execution."
},
{
"code": null,
"e": 27090,
"s": 27077,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 27105,
"s": 27090,
"text": "microprocessor"
},
{
"code": null,
"e": 27124,
"s": 27105,
"text": "system-programming"
},
{
"code": null,
"e": 27161,
"s": 27124,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 27176,
"s": 27161,
"text": "microprocessor"
},
{
"code": null,
"e": 27274,
"s": 27176,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27283,
"s": 27274,
"text": "Comments"
},
{
"code": null,
"e": 27296,
"s": 27283,
"text": "Old Comments"
},
{
"code": null,
"e": 27345,
"s": 27296,
"text": "Logical and Physical Address in Operating System"
},
{
"code": null,
"e": 27385,
"s": 27345,
"text": "Addressing modes in 8085 microprocessor"
},
{
"code": null,
"e": 27480,
"s": 27385,
"text": "Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)"
},
{
"code": null,
"e": 27518,
"s": 27480,
"text": "Computer Organization | RISC and CISC"
},
{
"code": null,
"e": 27609,
"s": 27518,
"text": "Computer Organization | Instruction Formats (Zero, One, Two and Three Address Instruction)"
},
{
"code": null,
"e": 27657,
"s": 27609,
"text": "Memory Hierarchy Design and its Characteristics"
},
{
"code": null,
"e": 27699,
"s": 27657,
"text": "Computer Organization | Booth's Algorithm"
},
{
"code": null,
"e": 27755,
"s": 27699,
"text": "Difference between Von Neumann and Harvard Architecture"
},
{
"code": null,
"e": 27791,
"s": 27755,
"text": "Architecture of 8085 microprocessor"
}
] |
Python | Check for ASCII string - GeeksforGeeks
|
25 Jun, 2019
Many times it is desirable to work with the strings that only contain alphabets and the other special characters are undesirable and sometimes this very task becomes the point to filter the strings and hence requires the way to check if a string is whole ASCII. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using ord() + all()The combination of this method can be used to achieve the desirable task. In this method, we search for all the string and check for each character, a value in range of ASCII characters.
# Python3 code to demonstrate# Check for ASCII string# using all() + ord() # initializing string test_string = "G4G is best" # printing original string print("The original string : " + str(test_string)) # using all() + ord()# Check for ASCII stringres = all(ord(c) < 128 for c in test_string) # print resultprint("Is the string full ASCII ? : " + str(res))
The original string : G4G is best
Is the string full ASCII ? : True
Method #2 : Using lambda + encode()This task can also be achieved using the above functions. In this combination, lambda function is used to extend the size check logic to whole string and encode function checks if the size of original and encoded strings match.
# Python3 code to demonstrate# Check for ASCII string# using lambda + encode() # initializing string test_string = "G4G is best" # printing original string print("The original string : " + str(test_string)) # using lambda + encode()# Check for ASCII stringres = lambda ele: len(ele) == len(ele.encode()) # print resultprint("Is the string full ASCII ? : " + str(res(test_string)))
The original string : G4G is best
Is the string full ASCII ? : True
Python string-programs
Python
Python Programs
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
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n25 Jun, 2019"
},
{
"code": null,
"e": 24618,
"s": 24292,
"text": "Many times it is desirable to work with the strings that only contain alphabets and the other special characters are undesirable and sometimes this very task becomes the point to filter the strings and hence requires the way to check if a string is whole ASCII. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 24836,
"s": 24618,
"text": "Method #1 : Using ord() + all()The combination of this method can be used to achieve the desirable task. In this method, we search for all the string and check for each character, a value in range of ASCII characters."
},
{
"code": "# Python3 code to demonstrate# Check for ASCII string# using all() + ord() # initializing string test_string = \"G4G is best\" # printing original string print(\"The original string : \" + str(test_string)) # using all() + ord()# Check for ASCII stringres = all(ord(c) < 128 for c in test_string) # print resultprint(\"Is the string full ASCII ? : \" + str(res))",
"e": 25197,
"s": 24836,
"text": null
},
{
"code": null,
"e": 25266,
"s": 25197,
"text": "The original string : G4G is best\nIs the string full ASCII ? : True\n"
},
{
"code": null,
"e": 25531,
"s": 25268,
"text": "Method #2 : Using lambda + encode()This task can also be achieved using the above functions. In this combination, lambda function is used to extend the size check logic to whole string and encode function checks if the size of original and encoded strings match."
},
{
"code": "# Python3 code to demonstrate# Check for ASCII string# using lambda + encode() # initializing string test_string = \"G4G is best\" # printing original string print(\"The original string : \" + str(test_string)) # using lambda + encode()# Check for ASCII stringres = lambda ele: len(ele) == len(ele.encode()) # print resultprint(\"Is the string full ASCII ? : \" + str(res(test_string)))",
"e": 25916,
"s": 25531,
"text": null
},
{
"code": null,
"e": 25985,
"s": 25916,
"text": "The original string : G4G is best\nIs the string full ASCII ? : True\n"
},
{
"code": null,
"e": 26008,
"s": 25985,
"text": "Python string-programs"
},
{
"code": null,
"e": 26015,
"s": 26008,
"text": "Python"
},
{
"code": null,
"e": 26031,
"s": 26015,
"text": "Python Programs"
},
{
"code": null,
"e": 26129,
"s": 26031,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26138,
"s": 26129,
"text": "Comments"
},
{
"code": null,
"e": 26151,
"s": 26138,
"text": "Old Comments"
},
{
"code": null,
"e": 26183,
"s": 26151,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26239,
"s": 26183,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26294,
"s": 26239,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26336,
"s": 26294,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26378,
"s": 26336,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26400,
"s": 26378,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26446,
"s": 26400,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 26485,
"s": 26446,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26523,
"s": 26485,
"text": "Python | Convert a list to dictionary"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.